diff --git a/cpython_2/environment/repo/Doc/c-api/float.rst b/cpython_2/environment/repo/Doc/c-api/float.rst new file mode 100644 index 0000000000000000000000000000000000000000..b29937dbecdcfdac966de4d6468c77a0fc65fa3a --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/float.rst @@ -0,0 +1,78 @@ +.. highlight:: c + +.. _floatobjects: + +Floating Point Objects +---------------------- + +.. index:: object: floating point + + +.. c:type:: PyFloatObject + + This subtype of :c:type:`PyObject` represents a Python floating point object. + + +.. c:var:: PyTypeObject PyFloat_Type + + This instance of :c:type:`PyTypeObject` represents the Python floating point + type. This is the same object as :class:`float` in the Python layer. + + +.. c:function:: int PyFloat_Check(PyObject *p) + + Return true if its argument is a :c:type:`PyFloatObject` or a subtype of + :c:type:`PyFloatObject`. + + +.. c:function:: int PyFloat_CheckExact(PyObject *p) + + Return true if its argument is a :c:type:`PyFloatObject`, but not a subtype of + :c:type:`PyFloatObject`. + + +.. c:function:: PyObject* PyFloat_FromString(PyObject *str) + + Create a :c:type:`PyFloatObject` object based on the string value in *str*, or + ``NULL`` on failure. + + +.. c:function:: PyObject* PyFloat_FromDouble(double v) + + Create a :c:type:`PyFloatObject` object from *v*, or ``NULL`` on failure. + + +.. c:function:: double PyFloat_AsDouble(PyObject *pyfloat) + + Return a C :c:type:`double` representation of the contents of *pyfloat*. If + *pyfloat* is not a Python floating point object but has a :meth:`__float__` + method, this method will first be called to convert *pyfloat* into a float. + If ``__float__()`` is not defined then it falls back to :meth:`__index__`. + This method returns ``-1.0`` upon failure, so one should call + :c:func:`PyErr_Occurred` to check for errors. + + .. versionchanged:: 3.8 + Use :meth:`__index__` if available. + + +.. c:function:: double PyFloat_AS_DOUBLE(PyObject *pyfloat) + + Return a C :c:type:`double` representation of the contents of *pyfloat*, but + without error checking. + + +.. c:function:: PyObject* PyFloat_GetInfo(void) + + Return a structseq instance which contains information about the + precision, minimum and maximum values of a float. It's a thin wrapper + around the header file :file:`float.h`. + + +.. c:function:: double PyFloat_GetMax() + + Return the maximum representable finite float *DBL_MAX* as C :c:type:`double`. + + +.. c:function:: double PyFloat_GetMin() + + Return the minimum normalized positive float *DBL_MIN* as C :c:type:`double`. diff --git a/cpython_2/environment/repo/Doc/c-api/function.rst b/cpython_2/environment/repo/Doc/c-api/function.rst new file mode 100644 index 0000000000000000000000000000000000000000..bb416f4bb63aa2b16bba3cd6a1b30bc5abc7566e --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/function.rst @@ -0,0 +1,108 @@ +.. highlight:: c + +.. _function-objects: + +Function Objects +---------------- + +.. index:: object: function + +There are a few functions specific to Python functions. + + +.. c:type:: PyFunctionObject + + The C structure used for functions. + + +.. c:var:: PyTypeObject PyFunction_Type + + .. index:: single: MethodType (in module types) + + This is an instance of :c:type:`PyTypeObject` and represents the Python function + type. It is exposed to Python programmers as ``types.FunctionType``. + + +.. c:function:: int PyFunction_Check(PyObject *o) + + Return true if *o* is a function object (has type :c:data:`PyFunction_Type`). + The parameter must not be ``NULL``. + + +.. c:function:: PyObject* PyFunction_New(PyObject *code, PyObject *globals) + + Return a new function object associated with the code object *code*. *globals* + must be a dictionary with the global variables accessible to the function. + + The function's docstring and name are retrieved from the code object. *__module__* + is retrieved from *globals*. The argument defaults, annotations and closure are + set to ``NULL``. *__qualname__* is set to the same value as the function's name. + + +.. c:function:: PyObject* PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname) + + As :c:func:`PyFunction_New`, but also allows setting the function object's + ``__qualname__`` attribute. *qualname* should be a unicode object or ``NULL``; + if ``NULL``, the ``__qualname__`` attribute is set to the same value as its + ``__name__`` attribute. + + .. versionadded:: 3.3 + + +.. c:function:: PyObject* PyFunction_GetCode(PyObject *op) + + Return the code object associated with the function object *op*. + + +.. c:function:: PyObject* PyFunction_GetGlobals(PyObject *op) + + Return the globals dictionary associated with the function object *op*. + + +.. c:function:: PyObject* PyFunction_GetModule(PyObject *op) + + Return the *__module__* attribute of the function object *op*. This is normally + a string containing the module name, but can be set to any other object by + Python code. + + +.. c:function:: PyObject* PyFunction_GetDefaults(PyObject *op) + + Return the argument default values of the function object *op*. This can be a + tuple of arguments or ``NULL``. + + +.. c:function:: int PyFunction_SetDefaults(PyObject *op, PyObject *defaults) + + Set the argument default values for the function object *op*. *defaults* must be + ``Py_None`` or a tuple. + + Raises :exc:`SystemError` and returns ``-1`` on failure. + + +.. c:function:: PyObject* PyFunction_GetClosure(PyObject *op) + + Return the closure associated with the function object *op*. This can be ``NULL`` + or a tuple of cell objects. + + +.. c:function:: int PyFunction_SetClosure(PyObject *op, PyObject *closure) + + Set the closure associated with the function object *op*. *closure* must be + ``Py_None`` or a tuple of cell objects. + + Raises :exc:`SystemError` and returns ``-1`` on failure. + + +.. c:function:: PyObject *PyFunction_GetAnnotations(PyObject *op) + + Return the annotations of the function object *op*. This can be a + mutable dictionary or ``NULL``. + + +.. c:function:: int PyFunction_SetAnnotations(PyObject *op, PyObject *annotations) + + Set the annotations for the function object *op*. *annotations* + must be a dictionary or ``Py_None``. + + Raises :exc:`SystemError` and returns ``-1`` on failure. diff --git a/cpython_2/environment/repo/Doc/c-api/gcsupport.rst b/cpython_2/environment/repo/Doc/c-api/gcsupport.rst new file mode 100644 index 0000000000000000000000000000000000000000..eee114c19d59049c8fce8263271853e17b9a3d69 --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/gcsupport.rst @@ -0,0 +1,175 @@ +.. highlight:: c + +.. _supporting-cycle-detection: + +Supporting Cyclic Garbage Collection +==================================== + +Python's support for detecting and collecting garbage which involves circular +references requires support from object types which are "containers" for other +objects which may also be containers. Types which do not store references to +other objects, or which only store references to atomic types (such as numbers +or strings), do not need to provide any explicit support for garbage +collection. + +To create a container type, the :c:member:`~PyTypeObject.tp_flags` field of the type object must +include the :const:`Py_TPFLAGS_HAVE_GC` and provide an implementation of the +:c:member:`~PyTypeObject.tp_traverse` handler. If instances of the type are mutable, a +:c:member:`~PyTypeObject.tp_clear` implementation must also be provided. + + +.. data:: Py_TPFLAGS_HAVE_GC + :noindex: + + Objects with a type with this flag set must conform with the rules + documented here. For convenience these objects will be referred to as + container objects. + +Constructors for container types must conform to two rules: + +#. The memory for the object must be allocated using :c:func:`PyObject_GC_New` + or :c:func:`PyObject_GC_NewVar`. + +#. Once all the fields which may contain references to other containers are + initialized, it must call :c:func:`PyObject_GC_Track`. + + +.. c:function:: TYPE* PyObject_GC_New(TYPE, PyTypeObject *type) + + Analogous to :c:func:`PyObject_New` but for container objects with the + :const:`Py_TPFLAGS_HAVE_GC` flag set. + + +.. c:function:: TYPE* PyObject_GC_NewVar(TYPE, PyTypeObject *type, Py_ssize_t size) + + Analogous to :c:func:`PyObject_NewVar` but for container objects with the + :const:`Py_TPFLAGS_HAVE_GC` flag set. + + +.. c:function:: TYPE* PyObject_GC_Resize(TYPE, PyVarObject *op, Py_ssize_t newsize) + + Resize an object allocated by :c:func:`PyObject_NewVar`. Returns the + resized object or ``NULL`` on failure. *op* must not be tracked by the collector yet. + + +.. c:function:: void PyObject_GC_Track(PyObject *op) + + Adds the object *op* to the set of container objects tracked by the + collector. The collector can run at unexpected times so objects must be + valid while being tracked. This should be called once all the fields + followed by the :c:member:`~PyTypeObject.tp_traverse` handler become valid, usually near the + end of the constructor. + + +.. c:function:: int PyObject_IS_GC(PyObject *obj) + + Returns non-zero if the object implements the garbage collector protocol, + otherwise returns 0. + + The object cannot be tracked by the garbage collector if this function returns 0. + + +.. c:function:: int PyObject_GC_IsTracked(PyObject *op) + + Returns 1 if the object type of *op* implements the GC protocol and *op* is being + currently tracked by the garbage collector and 0 otherwise. + + This is analogous to the Python function :func:`gc.is_tracked`. + + .. versionadded:: 3.9 + + +.. c:function:: int PyObject_GC_IsFinalized(PyObject *op) + + Returns 1 if the object type of *op* implements the GC protocol and *op* has been + already finalized by the garbage collector and 0 otherwise. + + This is analogous to the Python function :func:`gc.is_finalized`. + + .. versionadded:: 3.9 + +Similarly, the deallocator for the object must conform to a similar pair of +rules: + +#. Before fields which refer to other containers are invalidated, + :c:func:`PyObject_GC_UnTrack` must be called. + +#. The object's memory must be deallocated using :c:func:`PyObject_GC_Del`. + + +.. c:function:: void PyObject_GC_Del(void *op) + + Releases memory allocated to an object using :c:func:`PyObject_GC_New` or + :c:func:`PyObject_GC_NewVar`. + + +.. c:function:: void PyObject_GC_UnTrack(void *op) + + Remove the object *op* from the set of container objects tracked by the + collector. Note that :c:func:`PyObject_GC_Track` can be called again on + this object to add it back to the set of tracked objects. The deallocator + (:c:member:`~PyTypeObject.tp_dealloc` handler) should call this for the object before any of + the fields used by the :c:member:`~PyTypeObject.tp_traverse` handler become invalid. + + +.. versionchanged:: 3.8 + + The :c:func:`_PyObject_GC_TRACK` and :c:func:`_PyObject_GC_UNTRACK` macros + have been removed from the public C API. + +The :c:member:`~PyTypeObject.tp_traverse` handler accepts a function parameter of this type: + + +.. c:type:: int (*visitproc)(PyObject *object, void *arg) + + Type of the visitor function passed to the :c:member:`~PyTypeObject.tp_traverse` handler. + The function should be called with an object to traverse as *object* and + the third parameter to the :c:member:`~PyTypeObject.tp_traverse` handler as *arg*. The + Python core uses several visitor functions to implement cyclic garbage + detection; it's not expected that users will need to write their own + visitor functions. + +The :c:member:`~PyTypeObject.tp_traverse` handler must have the following type: + + +.. c:type:: int (*traverseproc)(PyObject *self, visitproc visit, void *arg) + + Traversal function for a container object. Implementations must call the + *visit* function for each object directly contained by *self*, with the + parameters to *visit* being the contained object and the *arg* value passed + to the handler. The *visit* function must not be called with a ``NULL`` + object argument. If *visit* returns a non-zero value that value should be + returned immediately. + +To simplify writing :c:member:`~PyTypeObject.tp_traverse` handlers, a :c:func:`Py_VISIT` macro is +provided. In order to use this macro, the :c:member:`~PyTypeObject.tp_traverse` implementation +must name its arguments exactly *visit* and *arg*: + + +.. c:function:: void Py_VISIT(PyObject *o) + + If *o* is not ``NULL``, call the *visit* callback, with arguments *o* + and *arg*. If *visit* returns a non-zero value, then return it. + Using this macro, :c:member:`~PyTypeObject.tp_traverse` handlers + look like:: + + static int + my_traverse(Noddy *self, visitproc visit, void *arg) + { + Py_VISIT(self->foo); + Py_VISIT(self->bar); + return 0; + } + +The :c:member:`~PyTypeObject.tp_clear` handler must be of the :c:type:`inquiry` type, or ``NULL`` +if the object is immutable. + + +.. c:type:: int (*inquiry)(PyObject *self) + + Drop references that may have created reference cycles. Immutable objects + do not have to define this method since they can never directly create + reference cycles. Note that the object must still be valid after calling + this method (don't just call :c:func:`Py_DECREF` on a reference). The + collector will call this method if it detects that this object is involved + in a reference cycle. diff --git a/cpython_2/environment/repo/Doc/c-api/gen.rst b/cpython_2/environment/repo/Doc/c-api/gen.rst new file mode 100644 index 0000000000000000000000000000000000000000..74410927bfde107c8a8c1e4a5ee1f0a4a9302a0a --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/gen.rst @@ -0,0 +1,44 @@ +.. highlight:: c + +.. _gen-objects: + +Generator Objects +----------------- + +Generator objects are what Python uses to implement generator iterators. They +are normally created by iterating over a function that yields values, rather +than explicitly calling :c:func:`PyGen_New` or :c:func:`PyGen_NewWithQualName`. + + +.. c:type:: PyGenObject + + The C structure used for generator objects. + + +.. c:var:: PyTypeObject PyGen_Type + + The type object corresponding to generator objects. + + +.. c:function:: int PyGen_Check(PyObject *ob) + + Return true if *ob* is a generator object; *ob* must not be ``NULL``. + + +.. c:function:: int PyGen_CheckExact(PyObject *ob) + + Return true if *ob*'s type is :c:type:`PyGen_Type`; *ob* must not be ``NULL``. + + +.. c:function:: PyObject* PyGen_New(PyFrameObject *frame) + + Create and return a new generator object based on the *frame* object. + A reference to *frame* is stolen by this function. The argument must not be + ``NULL``. + +.. c:function:: PyObject* PyGen_NewWithQualName(PyFrameObject *frame, PyObject *name, PyObject *qualname) + + Create and return a new generator object based on the *frame* object, + with ``__name__`` and ``__qualname__`` set to *name* and *qualname*. + A reference to *frame* is stolen by this function. The *frame* argument + must not be ``NULL``. diff --git a/cpython_2/environment/repo/Doc/c-api/import.rst b/cpython_2/environment/repo/Doc/c-api/import.rst new file mode 100644 index 0000000000000000000000000000000000000000..c6fc33076f0f516e6b470bcce50be5f8bf3c35c0 --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/import.rst @@ -0,0 +1,302 @@ +.. highlight:: c + +.. _importing: + +Importing Modules +================= + + +.. c:function:: PyObject* PyImport_ImportModule(const char *name) + + .. index:: + single: package variable; __all__ + single: __all__ (package variable) + single: modules (in module sys) + + This is a simplified interface to :c:func:`PyImport_ImportModuleEx` below, + leaving the *globals* and *locals* arguments set to ``NULL`` and *level* set + to 0. When the *name* + argument contains a dot (when it specifies a submodule of a package), the + *fromlist* argument is set to the list ``['*']`` so that the return value is the + named module rather than the top-level package containing it as would otherwise + be the case. (Unfortunately, this has an additional side effect when *name* in + fact specifies a subpackage instead of a submodule: the submodules specified in + the package's ``__all__`` variable are loaded.) Return a new reference to the + imported module, or ``NULL`` with an exception set on failure. A failing + import of a module doesn't leave the module in :data:`sys.modules`. + + This function always uses absolute imports. + + +.. c:function:: PyObject* PyImport_ImportModuleNoBlock(const char *name) + + This function is a deprecated alias of :c:func:`PyImport_ImportModule`. + + .. versionchanged:: 3.3 + This function used to fail immediately when the import lock was held + by another thread. In Python 3.3 though, the locking scheme switched + to per-module locks for most purposes, so this function's special + behaviour isn't needed anymore. + + +.. c:function:: PyObject* PyImport_ImportModuleEx(const char *name, PyObject *globals, PyObject *locals, PyObject *fromlist) + + .. index:: builtin: __import__ + + Import a module. This is best described by referring to the built-in Python + function :func:`__import__`. + + The return value is a new reference to the imported module or top-level + package, or ``NULL`` with an exception set on failure. Like for + :func:`__import__`, the return value when a submodule of a package was + requested is normally the top-level package, unless a non-empty *fromlist* + was given. + + Failing imports remove incomplete module objects, like with + :c:func:`PyImport_ImportModule`. + + +.. c:function:: PyObject* PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals, PyObject *locals, PyObject *fromlist, int level) + + Import a module. This is best described by referring to the built-in Python + function :func:`__import__`, as the standard :func:`__import__` function calls + this function directly. + + The return value is a new reference to the imported module or top-level package, + or ``NULL`` with an exception set on failure. Like for :func:`__import__`, + the return value when a submodule of a package was requested is normally the + top-level package, unless a non-empty *fromlist* was given. + + .. versionadded:: 3.3 + + +.. c:function:: PyObject* PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals, PyObject *fromlist, int level) + + Similar to :c:func:`PyImport_ImportModuleLevelObject`, but the name is a + UTF-8 encoded string instead of a Unicode object. + + .. versionchanged:: 3.3 + Negative values for *level* are no longer accepted. + +.. c:function:: PyObject* PyImport_Import(PyObject *name) + + This is a higher-level interface that calls the current "import hook + function" (with an explicit *level* of 0, meaning absolute import). It + invokes the :func:`__import__` function from the ``__builtins__`` of the + current globals. This means that the import is done using whatever import + hooks are installed in the current environment. + + This function always uses absolute imports. + + +.. c:function:: PyObject* PyImport_ReloadModule(PyObject *m) + + Reload a module. Return a new reference to the reloaded module, or ``NULL`` with + an exception set on failure (the module still exists in this case). + + +.. c:function:: PyObject* PyImport_AddModuleObject(PyObject *name) + + Return the module object corresponding to a module name. The *name* argument + may be of the form ``package.module``. First check the modules dictionary if + there's one there, and if not, create a new one and insert it in the modules + dictionary. Return ``NULL`` with an exception set on failure. + + .. note:: + + This function does not load or import the module; if the module wasn't already + loaded, you will get an empty module object. Use :c:func:`PyImport_ImportModule` + or one of its variants to import a module. Package structures implied by a + dotted name for *name* are not created if not already present. + + .. versionadded:: 3.3 + + +.. c:function:: PyObject* PyImport_AddModule(const char *name) + + Similar to :c:func:`PyImport_AddModuleObject`, but the name is a UTF-8 + encoded string instead of a Unicode object. + + +.. c:function:: PyObject* PyImport_ExecCodeModule(const char *name, PyObject *co) + + .. index:: builtin: compile + + Given a module name (possibly of the form ``package.module``) and a code object + read from a Python bytecode file or obtained from the built-in function + :func:`compile`, load the module. Return a new reference to the module object, + or ``NULL`` with an exception set if an error occurred. *name* + is removed from :attr:`sys.modules` in error cases, even if *name* was already + in :attr:`sys.modules` on entry to :c:func:`PyImport_ExecCodeModule`. Leaving + incompletely initialized modules in :attr:`sys.modules` is dangerous, as imports of + such modules have no way to know that the module object is an unknown (and + probably damaged with respect to the module author's intents) state. + + The module's :attr:`__spec__` and :attr:`__loader__` will be set, if + not set already, with the appropriate values. The spec's loader will + be set to the module's ``__loader__`` (if set) and to an instance of + :class:`SourceFileLoader` otherwise. + + The module's :attr:`__file__` attribute will be set to the code object's + :c:member:`co_filename`. If applicable, :attr:`__cached__` will also + be set. + + This function will reload the module if it was already imported. See + :c:func:`PyImport_ReloadModule` for the intended way to reload a module. + + If *name* points to a dotted name of the form ``package.module``, any package + structures not already created will still not be created. + + See also :c:func:`PyImport_ExecCodeModuleEx` and + :c:func:`PyImport_ExecCodeModuleWithPathnames`. + + +.. c:function:: PyObject* PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname) + + Like :c:func:`PyImport_ExecCodeModule`, but the :attr:`__file__` attribute of + the module object is set to *pathname* if it is non-``NULL``. + + See also :c:func:`PyImport_ExecCodeModuleWithPathnames`. + + +.. c:function:: PyObject* PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname, PyObject *cpathname) + + Like :c:func:`PyImport_ExecCodeModuleEx`, but the :attr:`__cached__` + attribute of the module object is set to *cpathname* if it is + non-``NULL``. Of the three functions, this is the preferred one to use. + + .. versionadded:: 3.3 + + +.. c:function:: PyObject* PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co, const char *pathname, const char *cpathname) + + Like :c:func:`PyImport_ExecCodeModuleObject`, but *name*, *pathname* and + *cpathname* are UTF-8 encoded strings. Attempts are also made to figure out + what the value for *pathname* should be from *cpathname* if the former is + set to ``NULL``. + + .. versionadded:: 3.2 + .. versionchanged:: 3.3 + Uses :func:`imp.source_from_cache()` in calculating the source path if + only the bytecode path is provided. + + +.. c:function:: long PyImport_GetMagicNumber() + + Return the magic number for Python bytecode files (a.k.a. :file:`.pyc` file). + The magic number should be present in the first four bytes of the bytecode + file, in little-endian byte order. Returns ``-1`` on error. + + .. versionchanged:: 3.3 + Return value of ``-1`` upon failure. + + +.. c:function:: const char * PyImport_GetMagicTag() + + Return the magic tag string for :pep:`3147` format Python bytecode file + names. Keep in mind that the value at ``sys.implementation.cache_tag`` is + authoritative and should be used instead of this function. + + .. versionadded:: 3.2 + +.. c:function:: PyObject* PyImport_GetModuleDict() + + Return the dictionary used for the module administration (a.k.a. + ``sys.modules``). Note that this is a per-interpreter variable. + +.. c:function:: PyObject* PyImport_GetModule(PyObject *name) + + Return the already imported module with the given name. If the + module has not been imported yet then returns ``NULL`` but does not set + an error. Returns ``NULL`` and sets an error if the lookup failed. + + .. versionadded:: 3.7 + +.. c:function:: PyObject* PyImport_GetImporter(PyObject *path) + + Return a finder object for a :data:`sys.path`/:attr:`pkg.__path__` item + *path*, possibly by fetching it from the :data:`sys.path_importer_cache` + dict. If it wasn't yet cached, traverse :data:`sys.path_hooks` until a hook + is found that can handle the path item. Return ``None`` if no hook could; + this tells our caller that the :term:`path based finder` could not find a + finder for this path item. Cache the result in :data:`sys.path_importer_cache`. + Return a new reference to the finder object. + + +.. c:function:: int PyImport_ImportFrozenModuleObject(PyObject *name) + + Load a frozen module named *name*. Return ``1`` for success, ``0`` if the + module is not found, and ``-1`` with an exception set if the initialization + failed. To access the imported module on a successful load, use + :c:func:`PyImport_ImportModule`. (Note the misnomer --- this function would + reload the module if it was already imported.) + + .. versionadded:: 3.3 + + .. versionchanged:: 3.4 + The ``__file__`` attribute is no longer set on the module. + + +.. c:function:: int PyImport_ImportFrozenModule(const char *name) + + Similar to :c:func:`PyImport_ImportFrozenModuleObject`, but the name is a + UTF-8 encoded string instead of a Unicode object. + + +.. c:type:: struct _frozen + + .. index:: single: freeze utility + + This is the structure type definition for frozen module descriptors, as + generated by the :program:`freeze` utility (see :file:`Tools/freeze/` in the + Python source distribution). Its definition, found in :file:`Include/import.h`, + is:: + + struct _frozen { + const char *name; + const unsigned char *code; + int size; + }; + + +.. c:var:: const struct _frozen* PyImport_FrozenModules + + This pointer is initialized to point to an array of :c:type:`struct _frozen` + records, terminated by one whose members are all ``NULL`` or zero. When a frozen + module is imported, it is searched in this table. Third-party code could play + tricks with this to provide a dynamically created collection of frozen modules. + + +.. c:function:: int PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void)) + + Add a single module to the existing table of built-in modules. This is a + convenience wrapper around :c:func:`PyImport_ExtendInittab`, returning ``-1`` if + the table could not be extended. The new module can be imported by the name + *name*, and uses the function *initfunc* as the initialization function called + on the first attempted import. This should be called before + :c:func:`Py_Initialize`. + + +.. c:type:: struct _inittab + + Structure describing a single entry in the list of built-in modules. Each of + these structures gives the name and initialization function for a module built + into the interpreter. The name is an ASCII encoded string. Programs which + embed Python may use an array of these structures in conjunction with + :c:func:`PyImport_ExtendInittab` to provide additional built-in modules. + The structure is defined in :file:`Include/import.h` as:: + + struct _inittab { + const char *name; /* ASCII encoded string */ + PyObject* (*initfunc)(void); + }; + + +.. c:function:: int PyImport_ExtendInittab(struct _inittab *newtab) + + Add a collection of modules to the table of built-in modules. The *newtab* + array must end with a sentinel entry which contains ``NULL`` for the :attr:`name` + field; failure to provide the sentinel value can result in a memory fault. + Returns ``0`` on success or ``-1`` if insufficient memory could be allocated to + extend the internal table. In the event of failure, no modules are added to the + internal table. This should be called before :c:func:`Py_Initialize`. diff --git a/cpython_2/environment/repo/Doc/c-api/index.rst b/cpython_2/environment/repo/Doc/c-api/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..9a8f1507b3f4cc57bdb6171d6081678f871ac8f7 --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/index.rst @@ -0,0 +1,27 @@ +.. _c-api-index: + +################################## + Python/C API Reference Manual +################################## + +This manual documents the API used by C and C++ programmers who want to write +extension modules or embed Python. It is a companion to :ref:`extending-index`, +which describes the general principles of extension writing but does not +document the API functions in detail. + +.. toctree:: + :maxdepth: 2 + + intro.rst + stable.rst + veryhigh.rst + refcounting.rst + exceptions.rst + utilities.rst + abstract.rst + concrete.rst + init.rst + init_config.rst + memory.rst + objimpl.rst + apiabiversion.rst diff --git a/cpython_2/environment/repo/Doc/c-api/init.rst b/cpython_2/environment/repo/Doc/c-api/init.rst new file mode 100644 index 0000000000000000000000000000000000000000..68fed2acc447ee94651c521a4fabf121b29fe527 --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/init.rst @@ -0,0 +1,1766 @@ +.. highlight:: c + + +.. _initialization: + +***************************************** +Initialization, Finalization, and Threads +***************************************** + +See also :ref:`Python Initialization Configuration `. + +.. _pre-init-safe: + +Before Python Initialization +============================ + +In an application embedding Python, the :c:func:`Py_Initialize` function must +be called before using any other Python/C API functions; with the exception of +a few functions and the :ref:`global configuration variables +`. + +The following functions can be safely called before Python is initialized: + +* Configuration functions: + + * :c:func:`PyImport_AppendInittab` + * :c:func:`PyImport_ExtendInittab` + * :c:func:`PyInitFrozenExtensions` + * :c:func:`PyMem_SetAllocator` + * :c:func:`PyMem_SetupDebugHooks` + * :c:func:`PyObject_SetArenaAllocator` + * :c:func:`Py_SetPath` + * :c:func:`Py_SetProgramName` + * :c:func:`Py_SetPythonHome` + * :c:func:`Py_SetStandardStreamEncoding` + * :c:func:`PySys_AddWarnOption` + * :c:func:`PySys_AddXOption` + * :c:func:`PySys_ResetWarnOptions` + +* Informative functions: + + * :c:func:`Py_IsInitialized` + * :c:func:`PyMem_GetAllocator` + * :c:func:`PyObject_GetArenaAllocator` + * :c:func:`Py_GetBuildInfo` + * :c:func:`Py_GetCompiler` + * :c:func:`Py_GetCopyright` + * :c:func:`Py_GetPlatform` + * :c:func:`Py_GetVersion` + +* Utilities: + + * :c:func:`Py_DecodeLocale` + +* Memory allocators: + + * :c:func:`PyMem_RawMalloc` + * :c:func:`PyMem_RawRealloc` + * :c:func:`PyMem_RawCalloc` + * :c:func:`PyMem_RawFree` + +.. note:: + + The following functions **should not be called** before + :c:func:`Py_Initialize`: :c:func:`Py_EncodeLocale`, :c:func:`Py_GetPath`, + :c:func:`Py_GetPrefix`, :c:func:`Py_GetExecPrefix`, + :c:func:`Py_GetProgramFullPath`, :c:func:`Py_GetPythonHome`, + :c:func:`Py_GetProgramName` and :c:func:`PyEval_InitThreads`. + + +.. _global-conf-vars: + +Global configuration variables +============================== + +Python has variables for the global configuration to control different features +and options. By default, these flags are controlled by :ref:`command line +options `. + +When a flag is set by an option, the value of the flag is the number of times +that the option was set. For example, ``-b`` sets :c:data:`Py_BytesWarningFlag` +to 1 and ``-bb`` sets :c:data:`Py_BytesWarningFlag` to 2. + +.. c:var:: Py_BytesWarningFlag + + Issue a warning when comparing :class:`bytes` or :class:`bytearray` with + :class:`str` or :class:`bytes` with :class:`int`. Issue an error if greater + or equal to ``2``. + + Set by the :option:`-b` option. + +.. c:var:: Py_DebugFlag + + Turn on parser debugging output (for expert only, depending on compilation + options). + + Set by the :option:`-d` option and the :envvar:`PYTHONDEBUG` environment + variable. + +.. c:var:: Py_DontWriteBytecodeFlag + + If set to non-zero, Python won't try to write ``.pyc`` files on the + import of source modules. + + Set by the :option:`-B` option and the :envvar:`PYTHONDONTWRITEBYTECODE` + environment variable. + +.. c:var:: Py_FrozenFlag + + Suppress error messages when calculating the module search path in + :c:func:`Py_GetPath`. + + Private flag used by ``_freeze_importlib`` and ``frozenmain`` programs. + +.. c:var:: Py_HashRandomizationFlag + + Set to ``1`` if the :envvar:`PYTHONHASHSEED` environment variable is set to + a non-empty string. + + If the flag is non-zero, read the :envvar:`PYTHONHASHSEED` environment + variable to initialize the secret hash seed. + +.. c:var:: Py_IgnoreEnvironmentFlag + + Ignore all :envvar:`PYTHON*` environment variables, e.g. + :envvar:`PYTHONPATH` and :envvar:`PYTHONHOME`, that might be set. + + Set by the :option:`-E` and :option:`-I` options. + +.. c:var:: Py_InspectFlag + + When a script is passed as first argument or the :option:`-c` option is used, + enter interactive mode after executing the script or the command, even when + :data:`sys.stdin` does not appear to be a terminal. + + Set by the :option:`-i` option and the :envvar:`PYTHONINSPECT` environment + variable. + +.. c:var:: Py_InteractiveFlag + + Set by the :option:`-i` option. + +.. c:var:: Py_IsolatedFlag + + Run Python in isolated mode. In isolated mode :data:`sys.path` contains + neither the script's directory nor the user's site-packages directory. + + Set by the :option:`-I` option. + + .. versionadded:: 3.4 + +.. c:var:: Py_LegacyWindowsFSEncodingFlag + + If the flag is non-zero, use the ``mbcs`` encoding instead of the UTF-8 + encoding for the filesystem encoding. + + Set to ``1`` if the :envvar:`PYTHONLEGACYWINDOWSFSENCODING` environment + variable is set to a non-empty string. + + See :pep:`529` for more details. + + .. availability:: Windows. + +.. c:var:: Py_LegacyWindowsStdioFlag + + If the flag is non-zero, use :class:`io.FileIO` instead of + :class:`WindowsConsoleIO` for :mod:`sys` standard streams. + + Set to ``1`` if the :envvar:`PYTHONLEGACYWINDOWSSTDIO` environment + variable is set to a non-empty string. + + See :pep:`528` for more details. + + .. availability:: Windows. + +.. c:var:: Py_NoSiteFlag + + Disable the import of the module :mod:`site` and the site-dependent + manipulations of :data:`sys.path` that it entails. Also disable these + manipulations if :mod:`site` is explicitly imported later (call + :func:`site.main` if you want them to be triggered). + + Set by the :option:`-S` option. + +.. c:var:: Py_NoUserSiteDirectory + + Don't add the :data:`user site-packages directory ` to + :data:`sys.path`. + + Set by the :option:`-s` and :option:`-I` options, and the + :envvar:`PYTHONNOUSERSITE` environment variable. + +.. c:var:: Py_OptimizeFlag + + Set by the :option:`-O` option and the :envvar:`PYTHONOPTIMIZE` environment + variable. + +.. c:var:: Py_QuietFlag + + Don't display the copyright and version messages even in interactive mode. + + Set by the :option:`-q` option. + + .. versionadded:: 3.2 + +.. c:var:: Py_UnbufferedStdioFlag + + Force the stdout and stderr streams to be unbuffered. + + Set by the :option:`-u` option and the :envvar:`PYTHONUNBUFFERED` + environment variable. + +.. c:var:: Py_VerboseFlag + + Print a message each time a module is initialized, showing the place + (filename or built-in module) from which it is loaded. If greater or equal + to ``2``, print a message for each file that is checked for when + searching for a module. Also provides information on module cleanup at exit. + + Set by the :option:`-v` option and the :envvar:`PYTHONVERBOSE` environment + variable. + + +Initializing and finalizing the interpreter +=========================================== + + +.. c:function:: void Py_Initialize() + + .. index:: + single: Py_SetProgramName() + single: PyEval_InitThreads() + single: modules (in module sys) + single: path (in module sys) + module: builtins + module: __main__ + module: sys + triple: module; search; path + single: PySys_SetArgv() + single: PySys_SetArgvEx() + single: Py_FinalizeEx() + + Initialize the Python interpreter. In an application embedding Python, + this should be called before using any other Python/C API functions; see + :ref:`Before Python Initialization ` for the few exceptions. + + This initializes + the table of loaded modules (``sys.modules``), and creates the fundamental + modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`. It also initializes + the module search path (``sys.path``). It does not set ``sys.argv``; use + :c:func:`PySys_SetArgvEx` for that. This is a no-op when called for a second time + (without calling :c:func:`Py_FinalizeEx` first). There is no return value; it is a + fatal error if the initialization fails. + + .. note:: + On Windows, changes the console mode from ``O_TEXT`` to ``O_BINARY``, which will + also affect non-Python uses of the console using the C Runtime. + + +.. c:function:: void Py_InitializeEx(int initsigs) + + This function works like :c:func:`Py_Initialize` if *initsigs* is ``1``. If + *initsigs* is ``0``, it skips initialization registration of signal handlers, which + might be useful when Python is embedded. + + +.. c:function:: int Py_IsInitialized() + + Return true (nonzero) when the Python interpreter has been initialized, false + (zero) if not. After :c:func:`Py_FinalizeEx` is called, this returns false until + :c:func:`Py_Initialize` is called again. + + +.. c:function:: int Py_FinalizeEx() + + Undo all initializations made by :c:func:`Py_Initialize` and subsequent use of + Python/C API functions, and destroy all sub-interpreters (see + :c:func:`Py_NewInterpreter` below) that were created and not yet destroyed since + the last call to :c:func:`Py_Initialize`. Ideally, this frees all memory + allocated by the Python interpreter. This is a no-op when called for a second + time (without calling :c:func:`Py_Initialize` again first). Normally the + return value is ``0``. If there were errors during finalization + (flushing buffered data), ``-1`` is returned. + + This function is provided for a number of reasons. An embedding application + might want to restart Python without having to restart the application itself. + An application that has loaded the Python interpreter from a dynamically + loadable library (or DLL) might want to free all memory allocated by Python + before unloading the DLL. During a hunt for memory leaks in an application a + developer might want to free all memory allocated by Python before exiting from + the application. + + **Bugs and caveats:** The destruction of modules and objects in modules is done + in random order; this may cause destructors (:meth:`__del__` methods) to fail + when they depend on other objects (even functions) or modules. Dynamically + loaded extension modules loaded by Python are not unloaded. Small amounts of + memory allocated by the Python interpreter may not be freed (if you find a leak, + please report it). Memory tied up in circular references between objects is not + freed. Some memory allocated by extension modules may not be freed. Some + extensions may not work properly if their initialization routine is called more + than once; this can happen if an application calls :c:func:`Py_Initialize` and + :c:func:`Py_FinalizeEx` more than once. + + .. audit-event:: cpython._PySys_ClearAuditHooks "" c.Py_FinalizeEx + + .. versionadded:: 3.6 + +.. c:function:: void Py_Finalize() + + This is a backwards-compatible version of :c:func:`Py_FinalizeEx` that + disregards the return value. + + +Process-wide parameters +======================= + + +.. c:function:: int Py_SetStandardStreamEncoding(const char *encoding, const char *errors) + + .. index:: + single: Py_Initialize() + single: main() + triple: stdin; stdout; sdterr + + This function should be called before :c:func:`Py_Initialize`, if it is + called at all. It specifies which encoding and error handling to use + with standard IO, with the same meanings as in :func:`str.encode`. + + It overrides :envvar:`PYTHONIOENCODING` values, and allows embedding code + to control IO encoding when the environment variable does not work. + + *encoding* and/or *errors* may be ``NULL`` to use + :envvar:`PYTHONIOENCODING` and/or default values (depending on other + settings). + + Note that :data:`sys.stderr` always uses the "backslashreplace" error + handler, regardless of this (or any other) setting. + + If :c:func:`Py_FinalizeEx` is called, this function will need to be called + again in order to affect subsequent calls to :c:func:`Py_Initialize`. + + Returns ``0`` if successful, a nonzero value on error (e.g. calling after the + interpreter has already been initialized). + + .. versionadded:: 3.4 + + +.. c:function:: void Py_SetProgramName(const wchar_t *name) + + .. index:: + single: Py_Initialize() + single: main() + single: Py_GetPath() + + This function should be called before :c:func:`Py_Initialize` is called for + the first time, if it is called at all. It tells the interpreter the value + of the ``argv[0]`` argument to the :c:func:`main` function of the program + (converted to wide characters). + This is used by :c:func:`Py_GetPath` and some other functions below to find + the Python run-time libraries relative to the interpreter executable. The + default value is ``'python'``. The argument should point to a + zero-terminated wide 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 :c:func:`Py_DecodeLocale` to decode a bytes string to get a + :c:type:`wchar_*` string. + + +.. c:function:: wchar* Py_GetProgramName() + + .. index:: single: Py_SetProgramName() + + Return the program name set with :c:func:`Py_SetProgramName`, or the default. + The returned string points into static storage; the caller should not modify its + value. + + +.. c:function:: wchar_t* Py_GetPrefix() + + Return the *prefix* for installed platform-independent files. This is derived + through a number of complicated rules from the program name set with + :c:func:`Py_SetProgramName` and some environment variables; 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 :makevar:`prefix` variable in the top-level + :file:`Makefile` and the ``--prefix`` argument to the :program:`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. + + +.. c:function:: wchar_t* Py_GetExecPrefix() + + Return the *exec-prefix* for installed platform-*dependent* files. This is + derived through a number of complicated rules from the program name set with + :c:func:`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 to the :makevar:`exec_prefix` + variable in the top-level :file:`Makefile` and the ``--exec-prefix`` + argument to the :program:`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 :file:`/usr/local/plat` subtree while platform independent may + be installed in :file:`/usr/local`. + + Generally speaking, a platform is a combination of hardware and software + families, e.g. Sparc machines running 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 + meaningless, 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 :program:`mount` or + :program:`automount` programs to share :file:`/usr/local` between platforms + while having :file:`/usr/local/plat` be a different filesystem for each + platform. + + +.. c:function:: wchar_t* Py_GetProgramFullPath() + + .. index:: + single: Py_SetProgramName() + single: executable (in module sys) + + 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 :c:func:`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``. + + +.. c:function:: wchar_t* Py_GetPath() + + .. index:: + triple: module; search; path + single: path (in module sys) + single: Py_SetPath() + + Return the default module search path; this is computed from the program name + (set by :c:func:`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 Mac OS X, ``';'`` on Windows. The returned string points into + static storage; the caller should not modify its value. The list + :data:`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. + + .. XXX should give the exact rules + + +.. c:function:: void Py_SetPath(const wchar_t *) + + .. index:: + triple: module; search; path + single: path (in module sys) + single: Py_GetPath() + + Set the default module search path. If this function is called before + :c:func:`Py_Initialize`, then :c:func:`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 Mac OS X, ``';'`` + on Windows. + + This also causes :data:`sys.executable` to be set to the program + full path (see :c:func:`Py_GetProgramFullPath`) and for :data:`sys.prefix` and + :data:`sys.exec_prefix` to be empty. It is up to the caller to modify these + if required after calling :c:func:`Py_Initialize`. + + Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a + :c:type:`wchar_*` string. + + The path argument is copied internally, so the caller may free it after the + call completes. + + .. versionchanged:: 3.8 + The program full path is now used for :data:`sys.executable`, instead + of the program name. + + +.. c:function:: const char* Py_GetVersion() + + 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]" + + .. index:: single: version (in module sys) + + The first word (up to the first space character) is the current Python version; + the first three 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 :data:`sys.version`. + + +.. c:function:: const char* Py_GetPlatform() + + .. index:: single: platform (in module sys) + + 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 Mac OS X, 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``. + + +.. c:function:: const char* Py_GetCopyright() + + Return the official copyright string for the current Python version, for example + + ``'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'`` + + .. index:: single: copyright (in module sys) + + The returned string points into static storage; the caller should not modify its + value. The value is available to Python code as ``sys.copyright``. + + +.. c:function:: const char* Py_GetCompiler() + + Return an indication of the compiler used to build the current Python version, + in square brackets, for example:: + + "[GCC 2.7.2.2]" + + .. index:: single: version (in module sys) + + The returned string points into static storage; the caller should not modify its + value. The value is available to Python code as part of the variable + ``sys.version``. + + +.. c:function:: const char* Py_GetBuildInfo() + + Return information about the sequence number and build date and time of the + current Python interpreter instance, for example :: + + "#67, Aug 1 1997, 22:34:28" + + .. index:: single: version (in module sys) + + The returned string points into static storage; the caller should not modify its + value. The value is available to Python code as part of the variable + ``sys.version``. + + +.. c:function:: void PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath) + + .. index:: + single: main() + single: Py_FatalError() + single: argv (in module sys) + + Set :data:`sys.argv` based on *argc* and *argv*. These parameters are + similar to those passed to the program's :c:func:`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 :data:`sys.argv`, a fatal + condition is signalled using :c:func:`Py_FatalError`. + + If *updatepath* is zero, this is all the function does. If *updatepath* + is non-zero, the function also modifies :data:`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 + :data:`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 + :data:`sys.path`, which is the same as prepending the current working + directory (``"."``). + + Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a + :c:type:`wchar_*` string. + + .. note:: + It is recommended that applications embedding the Python interpreter + for purposes other than executing a single script pass ``0`` as *updatepath*, + and update :data:`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 :data:`sys.path` element after having called + :c:func:`PySys_SetArgv`, for example using:: + + PyRun_SimpleString("import sys; sys.path.pop(0)\n"); + + .. versionadded:: 3.1.3 + + .. XXX impl. doesn't seem consistent in allowing ``0``/``NULL`` for the params; + check w/ Guido. + + +.. c:function:: void PySys_SetArgv(int argc, wchar_t **argv) + + This function works like :c:func:`PySys_SetArgvEx` with *updatepath* set + to ``1`` unless the :program:`python` interpreter was started with the + :option:`-I`. + + Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a + :c:type:`wchar_*` string. + + .. versionchanged:: 3.4 The *updatepath* value depends on :option:`-I`. + + +.. c:function:: void Py_SetPythonHome(const wchar_t *home) + + Set the default "home" directory, that is, the location of the standard + Python libraries. See :envvar:`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 :c:func:`Py_DecodeLocale` to decode a bytes string to get a + :c:type:`wchar_*` string. + + +.. c:function:: w_char* Py_GetPythonHome() + + Return the default "home", that is, the value set by a previous call to + :c:func:`Py_SetPythonHome`, or the value of the :envvar:`PYTHONHOME` + environment variable if it is set. + + +.. _threads: + +Thread State and the Global Interpreter Lock +============================================ + +.. index:: + single: global interpreter lock + single: interpreter lock + single: lock, interpreter + +The Python interpreter is not fully thread-safe. In order to support +multi-threaded Python programs, there's a global lock, called the :term:`global +interpreter lock` or :term:`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. + +.. 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. +In order to emulate concurrency of execution, the interpreter regularly +tries to switch threads (see :func:`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. + +.. index:: + single: PyThreadState + single: PyThreadState + +The Python interpreter keeps some thread-specific bookkeeping information +inside a data structure called :c:type:`PyThreadState`. There's also one +global variable pointing to the current :c:type:`PyThreadState`: it can +be retrieved using :c:func:`PyThreadState_Get`. + +Releasing the GIL from extension code +------------------------------------- + +Most extension code manipulating the :term:`GIL` has the following simple +structure:: + + 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. + +This is so common that a pair of macros exists to simplify it:: + + Py_BEGIN_ALLOW_THREADS + ... Do some blocking I/O operation ... + Py_END_ALLOW_THREADS + +.. index:: + single: Py_BEGIN_ALLOW_THREADS + single: Py_END_ALLOW_THREADS + +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 +block. + +The block above expands to the following code:: + + PyThreadState *_save; + + _save = PyEval_SaveThread(); + ... Do some blocking I/O operation ... + PyEval_RestoreThread(_save); + +.. index:: + single: PyEval_RestoreThread() + single: PyEval_SaveThread() + +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. + +.. note:: + 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 :mod:`zlib` and :mod:`hashlib` modules release the GIL when + compressing or hashing data. + + +.. _gilstate: + +Non-Python created threads +-------------------------- + +When threads are created using the dedicated Python APIs (such as the +:mod:`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 aforementioned 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 :c:func:`PyGILState_Ensure` and :c:func:`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 :c:func:`PyGILState_\*` functions assume there is only one global +interpreter (created automatically by :c:func:`Py_Initialize`). Python +supports the creation of additional interpreters (using +:c:func:`Py_NewInterpreter`), but mixing multiple interpreters and the +:c:func:`PyGILState_\*` API is unsupported. + + +.. _fork-and-threads: + +Cautions about fork() +--------------------- + +Another important thing to note about threads is their behaviour in the face +of the C :c:func:`fork` call. On most systems with :c:func:`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 :func:`os.fork` by acquiring the locks it uses internally before +the fork, and releasing them afterwards. In addition, it resets any +:ref:`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 +:c:func:`pthread_atfork` would need to be used to accomplish the same thing. +Additionally, when extending or embedding Python, calling :c:func:`fork` +directly rather than through :func:`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. +:c:func:`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 :func:`os.fork` +does. This means finalizing all other :c:type:`PyThreadState` objects +belonging to the current interpreter and all other +:c:type:`PyInterpreterState` objects. Due to this and the special +nature of the :ref:`"main" interpreter `, +:c:func:`fork` should only be called in that interpreter's "main" +thread, where the CPython global runtime was originally initialized. +The only exception is if :c:func:`exec` will be called immediately +after. + + +High-level API +-------------- + +These are the most commonly used types and functions when writing C extension +code, or when embedding the Python interpreter: + +.. c:type:: PyInterpreterState + + 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. + + +.. c:type:: PyThreadState + + This data structure represents the state of a single thread. The only public + data member is :c:type:`PyInterpreterState \*`:attr:`interp`, which points to + this thread's interpreter state. + + +.. c:function:: void PyEval_InitThreads() + + .. index:: + single: PyEval_AcquireThread() + single: PyEval_ReleaseThread() + single: PyEval_SaveThread() + single: PyEval_RestoreThread() + + Deprecated function which does nothing. + + In Python 3.6 and older, this function created the GIL if it didn't exist. + + .. versionchanged:: 3.9 + The function now does nothing. + + .. versionchanged:: 3.7 + This function is now called by :c:func:`Py_Initialize()`, so you don't + have to call it yourself anymore. + + .. versionchanged:: 3.2 + This function cannot be called before :c:func:`Py_Initialize()` anymore. + + .. deprecated-removed:: 3.9 3.11 + + .. index:: module: _thread + + +.. c:function:: int PyEval_ThreadsInitialized() + + Returns a non-zero value if :c:func:`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. + + .. versionchanged:: 3.7 + The :term:`GIL` is now initialized by :c:func:`Py_Initialize()`. + + .. deprecated-removed:: 3.9 3.11 + + +.. c:function:: PyThreadState* PyEval_SaveThread() + + 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. + + +.. c:function:: void PyEval_RestoreThread(PyThreadState *tstate) + + 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. + + .. note:: + 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 :c:func:`_Py_IsFinalizing` or :func:`sys.is_finalizing` to + check if the interpreter is in process of being finalized before calling + this function to avoid unwanted termination. + +.. c:function:: PyThreadState* PyThreadState_Get() + + 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``). + + +.. c:function:: PyThreadState* PyThreadState_Swap(PyThreadState *tstate) + + 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: + +.. c:function:: PyGILState_STATE PyGILState_Ensure() + + 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 :c:func:`PyGILState_Release`. In general, other + thread-related APIs may be used between :c:func:`PyGILState_Ensure` and + :c:func:`PyGILState_Release` calls as long as the thread state is restored to + its previous state before the Release(). For example, normal usage of the + :c:macro:`Py_BEGIN_ALLOW_THREADS` and :c:macro:`Py_END_ALLOW_THREADS` macros is + acceptable. + + The return value is an opaque "handle" to the thread state when + :c:func:`PyGILState_Ensure` was called, and must be passed to + :c:func:`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 :c:func:`PyGILState_Ensure` must save the handle for its call + to :c:func:`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. + + .. note:: + 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 :c:func:`_Py_IsFinalizing` or :func:`sys.is_finalizing` to + check if the interpreter is in process of being finalized before calling + this function to avoid unwanted termination. + +.. c:function:: void PyGILState_Release(PyGILState_STATE) + + Release any resources previously acquired. After this call, Python's state will + be the same as it was prior to the corresponding :c:func:`PyGILState_Ensure` call + (but generally this state will be unknown to the caller, hence the use of the + GILState API). + + Every call to :c:func:`PyGILState_Ensure` must be matched by a call to + :c:func:`PyGILState_Release` on the same thread. + + +.. c:function:: PyThreadState* PyGILState_GetThisThreadState() + + 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. + + +.. c: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. + + .. versionadded:: 3.4 + + +The following macros are normally used without a trailing semicolon; look for +example usage in the Python source distribution. + + +.. c:macro:: Py_BEGIN_ALLOW_THREADS + + This macro expands to ``{ PyThreadState *_save; _save = PyEval_SaveThread();``. + Note that it contains an opening brace; it must be matched with a following + :c:macro:`Py_END_ALLOW_THREADS` macro. See above for further discussion of this + macro. + + +.. c:macro:: Py_END_ALLOW_THREADS + + This macro expands to ``PyEval_RestoreThread(_save); }``. Note that it contains + a closing brace; it must be matched with an earlier + :c:macro:`Py_BEGIN_ALLOW_THREADS` macro. See above for further discussion of + this macro. + + +.. c:macro:: Py_BLOCK_THREADS + + This macro expands to ``PyEval_RestoreThread(_save);``: it is equivalent to + :c:macro:`Py_END_ALLOW_THREADS` without the closing brace. + + +.. c:macro:: Py_UNBLOCK_THREADS + + This macro expands to ``_save = PyEval_SaveThread();``: it is equivalent to + :c:macro:`Py_BEGIN_ALLOW_THREADS` without the opening brace and variable + declaration. + + +Low-level API +------------- + +All of the following functions must be called after :c:func:`Py_Initialize`. + +.. versionchanged:: 3.7 + :c:func:`Py_Initialize()` now initializes the :term:`GIL`. + + +.. c:function:: PyInterpreterState* PyInterpreterState_New() + + 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. + + .. audit-event:: cpython.PyInterpreterState_New "" c.PyInterpreterState_New + + +.. c:function:: void PyInterpreterState_Clear(PyInterpreterState *interp) + + Reset all information in an interpreter state object. The global interpreter + lock must be held. + + .. audit-event:: cpython.PyInterpreterState_Clear "" c.PyInterpreterState_Clear + + +.. c:function:: void PyInterpreterState_Delete(PyInterpreterState *interp) + + 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 + :c:func:`PyInterpreterState_Clear`. + + +.. c:function:: PyThreadState* PyThreadState_New(PyInterpreterState *interp) + + Create a new thread state object belonging to the given interpreter object. + The global interpreter lock need not be held, but may be held if it is + necessary to serialize calls to this function. + + +.. c:function:: void PyThreadState_Clear(PyThreadState *tstate) + + Reset all information in a thread state object. The global interpreter lock + must be held. + + .. versionchanged:: 3.9 + This function now calls the :c:member:`PyThreadState.on_delete` callback. + Previously, that happened in :c:func:`PyThreadState_Delete`. + + +.. c:function:: void PyThreadState_Delete(PyThreadState *tstate) + + 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 + :c:func:`PyThreadState_Clear`. + + +.. c:function:: void PyThreadState_DeleteCurrent(void) + + Destroy the current thread state and release the global interpreter lock. + Like :c:func:`PyThreadState_Delete`, the global interpreter lock need not + be held. The thread state must have been reset with a previous call + to :c:func:`PyThreadState_Clear`. + + +.. c:function:: PyFrameObject* PyThreadState_GetFrame(PyThreadState *tstate) + + Get the current frame of the Python thread state *tstate*. + + Return a strong reference. Return ``NULL`` if no frame is currently + executing. + + See also :c:func:`PyEval_GetFrame`. + + *tstate* must not be ``NULL``. + + .. versionadded:: 3.9 + + +.. c:function:: uint64_t PyThreadState_GetID(PyThreadState *tstate) + + Get the unique thread state identifier of the Python thread state *tstate*. + + *tstate* must not be ``NULL``. + + .. versionadded:: 3.9 + + +.. c:function:: PyInterpreterState* PyThreadState_GetInterpreter(PyThreadState *tstate) + + Get the interpreter of the Python thread state *tstate*. + + *tstate* must not be ``NULL``. + + .. versionadded:: 3.9 + + +.. c:function:: PyInterpreterState* PyInterpreterState_Get(void) + + Get the current interpreter. + + Issue a fatal error if there no current Python thread state or no current + interpreter. It cannot return NULL. + + The caller must hold the GIL. + + .. versionadded:: 3.9 + + +.. c:function:: int64_t PyInterpreterState_GetID(PyInterpreterState *interp) + + Return the interpreter's unique ID. If there was any error in doing + so then ``-1`` is returned and an error is set. + + The caller must hold the GIL. + + .. versionadded:: 3.7 + + +.. c:function:: PyObject* PyInterpreterState_GetDict(PyInterpreterState *interp) + + 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 :c:func:`PyModule_GetState()`, which + extensions should use to store interpreter-specific state information. + + .. versionadded:: 3.8 + +.. c:type:: PyObject* (*_PyFrameEvalFunction)(PyThreadState *tstate, PyFrameObject *frame, int throwflag) + + Type of a frame evaluation function. + + The *throwflag* parameter is used by the ``throw()`` method of generators: + if non-zero, handle the current exception. + + .. versionchanged:: 3.9 + The function now takes a *tstate* parameter. + +.. c:function:: _PyFrameEvalFunction _PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp) + + Get the frame evaluation function. + + See the :pep:`523` "Adding a frame evaluation API to CPython". + + .. versionadded:: 3.9 + +.. c:function:: void _PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp, _PyFrameEvalFunction eval_frame); + + Set the frame evaluation function. + + See the :pep:`523` "Adding a frame evaluation API to CPython". + + .. versionadded:: 3.9 + + +.. c:function:: PyObject* PyThreadState_GetDict() + + 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. + + +.. c:function:: int PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc) + + 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 :const:`NULL`, the pending + exception (if any) for the thread is cleared. This raises no exceptions. + + .. versionchanged:: 3.7 + The type of the *id* parameter changed from :c:type:`long` to + :c:type:`unsigned long`. + +.. c:function:: void PyEval_AcquireThread(PyThreadState *tstate) + + 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. + + .. note:: + 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 :c:func:`_Py_IsFinalizing` or :func:`sys.is_finalizing` to + check if the interpreter is in process of being finalized before calling + this function to avoid unwanted termination. + + .. versionchanged:: 3.8 + Updated to be consistent with :c:func:`PyEval_RestoreThread`, + :c:func:`Py_END_ALLOW_THREADS`, and :c:func:`PyGILState_Ensure`, + and terminate the current thread if called while the interpreter is finalizing. + + :c:func:`PyEval_RestoreThread` is a higher-level function which is always + available (even when threads have not been initialized). + + +.. c:function:: void PyEval_ReleaseThread(PyThreadState *tstate) + + 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. + + :c:func:`PyEval_SaveThread` is a higher-level function which is always + available (even when threads have not been initialized). + + +.. c:function:: void PyEval_AcquireLock() + + Acquire the global interpreter lock. The lock must have been created earlier. + If this thread already has the lock, a deadlock ensues. + + .. deprecated:: 3.2 + This function does not update the current thread state. Please use + :c:func:`PyEval_RestoreThread` or :c:func:`PyEval_AcquireThread` + instead. + + .. note:: + 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 :c:func:`_Py_IsFinalizing` or :func:`sys.is_finalizing` to + check if the interpreter is in process of being finalized before calling + this function to avoid unwanted termination. + + .. versionchanged:: 3.8 + Updated to be consistent with :c:func:`PyEval_RestoreThread`, + :c:func:`Py_END_ALLOW_THREADS`, and :c:func:`PyGILState_Ensure`, + and terminate the current thread if called while the interpreter is finalizing. + + +.. c:function:: void PyEval_ReleaseLock() + + Release the global interpreter lock. The lock must have been created earlier. + + .. deprecated:: 3.2 + This function does not update the current thread state. Please use + :c:func:`PyEval_SaveThread` or :c:func:`PyEval_ReleaseThread` + instead. + + +.. _sub-interpreter-support: + +Sub-interpreter support +======================= + +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 +:c:func:`PyInterpreterState_Main` function returns a pointer to its state. + +You can switch between sub-interpreters using the :c:func:`PyThreadState_Swap` +function. You can create and destroy them using the following functions: + + +.. c:function:: PyThreadState* Py_NewInterpreter() + + .. index:: + module: builtins + module: __main__ + module: sys + single: stdout (in module sys) + single: stderr (in module sys) + single: stdin (in module sys) + + 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 :mod:`builtins`, :mod:`__main__` and :mod:`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 return value points 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, ``NULL`` is + returned; 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; however, unlike most + other Python/C API functions, there needn't be a current thread state on + entry.) + + .. index:: + single: Py_FinalizeEx() + single: Py_Initialize() + + Extension modules are shared between (sub-)interpreters as follows: + + * For modules using multi-phase initialization, + e.g. :c:func:`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. :c:func:`PyModule_Create`, the first time a particular extension + is imported, it is initialized normally, and a (shallow) copy of its + module's dictionary is squirreled 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 module'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 :c:func:`Py_FinalizeEx` and :c:func:`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. + + .. index:: single: close() (in module os) + + +.. c:function:: void Py_EndInterpreter(PyThreadState *tstate) + + .. index:: single: Py_FinalizeEx() + + 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 must be held before calling this function and is still held + when it returns.) :c:func:`Py_FinalizeEx` will destroy all sub-interpreters that + haven't been explicitly destroyed at that point. + + +Bugs and caveats +---------------- + +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 :func:`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 :c:func:`PyGILState_\*` APIs +is delicate, because these APIs assume 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 :c:func:`PyGILState_Ensure` and :c:func:`PyGILState_Release` calls. +Furthermore, extensions (such as :mod:`ctypes`) using these APIs to allow calling +of Python code from non-Python created threads will probably be broken when using +sub-interpreters. + + +Asynchronous Notifications +========================== + +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. + + +.. 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. + + 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 conditions met: + + * on a :term:`bytecode` boundary; + * with the main thread holding the :term:`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. + + .. warning:: + 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 :ref:`PyGILState API`. + + .. versionchanged:: 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. + + .. versionadded:: 3.1 + +.. _profiling: + +Profiling and Tracing +===================== + +.. sectionauthor:: Fred L. Drake, Jr. + + +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. + + +.. c:type:: int (*Py_tracefunc)(PyObject *obj, PyFrameObject *frame, int what, PyObject *arg) + + The type of the trace function registered using :c:func:`PyEval_SetProfile` and + :c:func:`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 :const:`PyTrace_CALL`, + :const:`PyTrace_EXCEPTION`, :const:`PyTrace_LINE`, :const:`PyTrace_RETURN`, + :const:`PyTrace_C_CALL`, :const:`PyTrace_C_EXCEPTION`, :const:`PyTrace_C_RETURN`, + or :const:`PyTrace_OPCODE`, and *arg* depends on the value of *what*: + + +------------------------------+----------------------------------------+ + | Value of *what* | Meaning of *arg* | + +==============================+========================================+ + | :const:`PyTrace_CALL` | Always :c:data:`Py_None`. | + +------------------------------+----------------------------------------+ + | :const:`PyTrace_EXCEPTION` | Exception information as returned by | + | | :func:`sys.exc_info`. | + +------------------------------+----------------------------------------+ + | :const:`PyTrace_LINE` | Always :c:data:`Py_None`. | + +------------------------------+----------------------------------------+ + | :const:`PyTrace_RETURN` | Value being returned to the caller, | + | | or ``NULL`` if caused by an exception. | + +------------------------------+----------------------------------------+ + | :const:`PyTrace_C_CALL` | Function object being called. | + +------------------------------+----------------------------------------+ + | :const:`PyTrace_C_EXCEPTION` | Function object being called. | + +------------------------------+----------------------------------------+ + | :const:`PyTrace_C_RETURN` | Function object being called. | + +------------------------------+----------------------------------------+ + | :const:`PyTrace_OPCODE` | Always :c:data:`Py_None`. | + +------------------------------+----------------------------------------+ + +.. c:var:: int PyTrace_CALL + + The value of the *what* parameter to a :c:type:`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. + + +.. c:var:: int PyTrace_EXCEPTION + + The value of the *what* parameter to a :c:type:`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. + + +.. c:var:: int PyTrace_LINE + + The value passed as the *what* parameter to a :c:type:`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 :attr:`f_trace_lines` to *0* on that frame. + + +.. c:var:: int PyTrace_RETURN + + The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a + call is about to return. + + +.. c:var:: int PyTrace_C_CALL + + The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C + function is about to be called. + + +.. c:var:: int PyTrace_C_EXCEPTION + + The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C + function has raised an exception. + + +.. c:var:: int PyTrace_C_RETURN + + The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C + function has returned. + + +.. c:var:: int PyTrace_OPCODE + + The value for the *what* parameter to :c:type:`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 + :attr:`f_trace_opcodes` to *1* on the frame. + + +.. c:function:: 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 :const:`PyTrace_LINE` + :const:`PyTrace_OPCODE` and :const:`PyTrace_EXCEPTION`. + + The caller must hold the :term:`GIL`. + + +.. c:function:: void PyEval_SetTrace(Py_tracefunc func, PyObject *obj) + + Set the tracing function to *func*. This is similar to + :c:func:`PyEval_SetProfile`, except the tracing function does receive line-number + events and per-opcode events, but does not receive any event related to C function + objects being called. Any trace function registered using :c:func:`PyEval_SetTrace` + will not receive :const:`PyTrace_C_CALL`, :const:`PyTrace_C_EXCEPTION` or + :const:`PyTrace_C_RETURN` as a value for the *what* parameter. + + The caller must hold the :term:`GIL`. + + +.. _advanced-debugging: + +Advanced Debugger Support +========================= + +.. sectionauthor:: Fred L. Drake, Jr. + + +These functions are only intended to be used by advanced debugging tools. + + +.. c:function:: PyInterpreterState* PyInterpreterState_Head() + + Return the interpreter state object at the head of the list of all such objects. + + +.. c:function:: PyInterpreterState* PyInterpreterState_Main() + + Return the main interpreter state object. + + +.. c:function:: PyInterpreterState* PyInterpreterState_Next(PyInterpreterState *interp) + + Return the next interpreter state object after *interp* from the list of all + such objects. + + +.. c:function:: PyThreadState * PyInterpreterState_ThreadHead(PyInterpreterState *interp) + + Return the pointer to the first :c:type:`PyThreadState` object in the list of + threads associated with the interpreter *interp*. + + +.. c:function:: PyThreadState* PyThreadState_Next(PyThreadState *tstate) + + Return the next thread state object after *tstate* from the list of all such + objects belonging to the same :c:type:`PyInterpreterState` object. + + +.. _thread-local-storage: + +Thread Local Storage Support +============================ + +.. sectionauthor:: Masayuki Yamamoto + +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 (:class:`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 :c:type:`void\*` value per +thread. + +The GIL does *not* need to be held when calling these functions; they supply +their own locking. + +Note that :file:`Python.h` does not include the declaration of the TLS APIs, +you need to include :file:`pythread.h` to use thread-local storage. + +.. note:: + None of these API functions handle memory management on behalf of the + :c:type:`void\*` values. You need to allocate and deallocate them yourself. + If the :c:type:`void\*` values happen to be :c:type:`PyObject\*`, these + functions don't do refcount operations on them either. + +.. _thread-specific-storage-api: + +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 :c:type:`Py_tss_t` instead of +:c:type:`int` to represent thread keys. + +.. versionadded:: 3.7 + +.. seealso:: "A New C-API for Thread-Local Storage in CPython" (:pep:`539`) + + +.. c: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 :ref:`Py_LIMITED_API ` is not defined, static allocation of + this type by :c:macro:`Py_tss_NEEDS_INIT` is allowed. + + +.. c:macro:: Py_tss_NEEDS_INIT + + This macro expands to the initializer for :c:type:`Py_tss_t` variables. + Note that this macro won't be defined with :ref:`Py_LIMITED_API `. + + +Dynamic Allocation +~~~~~~~~~~~~~~~~~~ + +Dynamic allocation of the :c:type:`Py_tss_t`, required in extension modules +built with :ref:`Py_LIMITED_API `, where static allocation of this type +is not possible due to its implementation being opaque at build time. + + +.. c:function:: Py_tss_t* PyThread_tss_alloc() + + Return a value which is the same state as a value initialized with + :c:macro:`Py_tss_NEEDS_INIT`, or ``NULL`` in the case of dynamic allocation + failure. + + +.. c:function:: void PyThread_tss_free(Py_tss_t *key) + + Free the given *key* allocated by :c:func:`PyThread_tss_alloc`, after + first calling :c:func:`PyThread_tss_delete` to ensure any associated + thread locals have been unassigned. This is a no-op if the *key* + argument is `NULL`. + + .. note:: + A freed key becomes a dangling pointer, you should reset the key to + `NULL`. + + +Methods +~~~~~~~ + +The parameter *key* of these functions must not be ``NULL``. Moreover, the +behaviors of :c:func:`PyThread_tss_set` and :c:func:`PyThread_tss_get` are +undefined if the given :c:type:`Py_tss_t` has not been initialized by +:c:func:`PyThread_tss_create`. + + +.. c:function:: int PyThread_tss_is_created(Py_tss_t *key) + + Return a non-zero value if the given :c:type:`Py_tss_t` has been initialized + by :c:func:`PyThread_tss_create`. + + +.. c:function:: int PyThread_tss_create(Py_tss_t *key) + + 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 :c:macro:`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. + + +.. c:function:: void PyThread_tss_delete(Py_tss_t *key) + + 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 + :c:func:`PyThread_tss_create`. This function can be called repeatedly on + the same key -- calling it on an already destroyed key is a no-op. + + +.. c:function:: int PyThread_tss_set(Py_tss_t *key, void *value) + + Return a zero value to indicate successfully associating a :c:type:`void\*` + value with a TSS key in the current thread. Each thread has a distinct + mapping of the key to a :c:type:`void\*` value. + + +.. c:function:: void* PyThread_tss_get(Py_tss_t *key) + + Return the :c:type:`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. + + +.. _thread-local-storage-api: + +Thread Local Storage (TLS) API +------------------------------ + +.. deprecated:: 3.7 + This API is superseded by + :ref:`Thread Specific Storage (TSS) API `. + +.. note:: + 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, + :c:func:`PyThread_create_key` will return immediately with a failure status, + and the other TLS functions will all be no-ops on such platforms. + +Due to the compatibility problem noted above, this version of the API should not +be used in new code. + +.. c:function:: int PyThread_create_key() +.. c:function:: void PyThread_delete_key(int key) +.. c:function:: int PyThread_set_key_value(int key, void *value) +.. c:function:: void* PyThread_get_key_value(int key) +.. c:function:: void PyThread_delete_key_value(int key) +.. c:function:: void PyThread_ReInitTLS() + diff --git a/cpython_2/environment/repo/Doc/c-api/init_config.rst b/cpython_2/environment/repo/Doc/c-api/init_config.rst new file mode 100644 index 0000000000000000000000000000000000000000..fc82c3eb5902482f5060f38567141c1c1ceb118d --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/init_config.rst @@ -0,0 +1,1064 @@ +.. highlight:: c + +.. _init-config: + +*********************************** +Python Initialization Configuration +*********************************** + +.. versionadded:: 3.8 + +Structures: + +* :c:type:`PyConfig` +* :c:type:`PyPreConfig` +* :c:type:`PyStatus` +* :c:type:`PyWideStringList` + +Functions: + +* :c:func:`PyConfig_Clear` +* :c:func:`PyConfig_InitIsolatedConfig` +* :c:func:`PyConfig_InitPythonConfig` +* :c:func:`PyConfig_Read` +* :c:func:`PyConfig_SetArgv` +* :c:func:`PyConfig_SetBytesArgv` +* :c:func:`PyConfig_SetBytesString` +* :c:func:`PyConfig_SetString` +* :c:func:`PyConfig_SetWideStringList` +* :c:func:`PyPreConfig_InitIsolatedConfig` +* :c:func:`PyPreConfig_InitPythonConfig` +* :c:func:`PyStatus_Error` +* :c:func:`PyStatus_Exception` +* :c:func:`PyStatus_Exit` +* :c:func:`PyStatus_IsError` +* :c:func:`PyStatus_IsExit` +* :c:func:`PyStatus_NoMemory` +* :c:func:`PyStatus_Ok` +* :c:func:`PyWideStringList_Append` +* :c:func:`PyWideStringList_Insert` +* :c:func:`Py_ExitStatusException` +* :c:func:`Py_InitializeFromConfig` +* :c:func:`Py_PreInitialize` +* :c:func:`Py_PreInitializeFromArgs` +* :c:func:`Py_PreInitializeFromBytesArgs` +* :c:func:`Py_RunMain` + +The preconfiguration (``PyPreConfig`` type) is stored in +``_PyRuntime.preconfig`` and the configuration (``PyConfig`` type) is stored in +``PyInterpreterState.config``. + +See also :ref:`Initialization, Finalization, and Threads `. + +.. seealso:: + :pep:`587` "Python Initialization Configuration". + + +PyWideStringList +---------------- + +.. c:type:: PyWideStringList + + List of ``wchar_t*`` strings. + + If *length* is non-zero, *items* must be non-``NULL`` and all strings must be + non-``NULL``. + + Methods: + + .. c:function:: PyStatus PyWideStringList_Append(PyWideStringList *list, const wchar_t *item) + + Append *item* to *list*. + + Python must be preinitialized to call this function. + + .. c:function:: PyStatus PyWideStringList_Insert(PyWideStringList *list, Py_ssize_t index, const wchar_t *item) + + Insert *item* into *list* at *index*. + + If *index* is greater than or equal to *list* length, append *item* to + *list*. + + *index* must be greater than or equal to 0. + + Python must be preinitialized to call this function. + + Structure fields: + + .. c:member:: Py_ssize_t length + + List length. + + .. c:member:: wchar_t** items + + List items. + +PyStatus +-------- + +.. c:type:: PyStatus + + Structure to store an initialization function status: success, error + or exit. + + For an error, it can store the C function name which created the error. + + Structure fields: + + .. c:member:: int exitcode + + Exit code. Argument passed to ``exit()``. + + .. c:member:: const char *err_msg + + Error message. + + .. c:member:: const char *func + + Name of the function which created an error, can be ``NULL``. + + Functions to create a status: + + .. c:function:: PyStatus PyStatus_Ok(void) + + Success. + + .. c:function:: PyStatus PyStatus_Error(const char *err_msg) + + Initialization error with a message. + + .. c:function:: PyStatus PyStatus_NoMemory(void) + + Memory allocation failure (out of memory). + + .. c:function:: PyStatus PyStatus_Exit(int exitcode) + + Exit Python with the specified exit code. + + Functions to handle a status: + + .. c:function:: int PyStatus_Exception(PyStatus status) + + Is the status an error or an exit? If true, the exception must be + handled; by calling :c:func:`Py_ExitStatusException` for example. + + .. c:function:: int PyStatus_IsError(PyStatus status) + + Is the result an error? + + .. c:function:: int PyStatus_IsExit(PyStatus status) + + Is the result an exit? + + .. c:function:: void Py_ExitStatusException(PyStatus status) + + Call ``exit(exitcode)`` if *status* is an exit. Print the error + message and exit with a non-zero exit code if *status* is an error. Must + only be called if ``PyStatus_Exception(status)`` is non-zero. + +.. note:: + Internally, Python uses macros which set ``PyStatus.func``, + whereas functions to create a status set ``func`` to ``NULL``. + +Example:: + + PyStatus alloc(void **ptr, size_t size) + { + *ptr = PyMem_RawMalloc(size); + if (*ptr == NULL) { + return PyStatus_NoMemory(); + } + 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; + } + + +PyPreConfig +----------- + +.. c:type:: PyPreConfig + + Structure used to preinitialize Python: + + * Set the Python memory allocator + * Configure the LC_CTYPE locale + * Set the UTF-8 mode + + Function to initialize a preconfiguration: + + .. c:function:: void PyPreConfig_InitIsolatedConfig(PyPreConfig *preconfig) + + Initialize the preconfiguration with :ref:`Python Configuration + `. + + .. c:function:: void PyPreConfig_InitPythonConfig(PyPreConfig *preconfig) + + Initialize the preconfiguration with :ref:`Isolated Configuration + `. + + Structure fields: + + .. c:member:: int allocator + + Name of the memory allocator: + + * ``PYMEM_ALLOCATOR_NOT_SET`` (``0``): don't change memory allocators + (use defaults) + * ``PYMEM_ALLOCATOR_DEFAULT`` (``1``): default memory allocators + * ``PYMEM_ALLOCATOR_DEBUG`` (``2``): default memory allocators with + debug hooks + * ``PYMEM_ALLOCATOR_MALLOC`` (``3``): force usage of ``malloc()`` + * ``PYMEM_ALLOCATOR_MALLOC_DEBUG`` (``4``): force usage of + ``malloc()`` with debug hooks + * ``PYMEM_ALLOCATOR_PYMALLOC`` (``5``): :ref:`Python pymalloc memory + allocator ` + * ``PYMEM_ALLOCATOR_PYMALLOC_DEBUG`` (``6``): :ref:`Python pymalloc + memory allocator ` with debug hooks + + ``PYMEM_ALLOCATOR_PYMALLOC`` and ``PYMEM_ALLOCATOR_PYMALLOC_DEBUG`` + are not supported if Python is configured using ``--without-pymalloc`` + + See :ref:`Memory Management `. + + .. c:member:: int configure_locale + + Set the LC_CTYPE locale to the user preferred locale? If equals to 0, set + :c:member:`coerce_c_locale` and :c:member:`coerce_c_locale_warn` to 0. + + .. c:member:: int coerce_c_locale + + If equals to 2, coerce the C locale; if equals to 1, read the LC_CTYPE + locale to decide if it should be coerced. + + .. c:member:: int coerce_c_locale_warn + + If non-zero, emit a warning if the C locale is coerced. + + .. c:member:: int dev_mode + + See :c:member:`PyConfig.dev_mode`. + + .. c:member:: int isolated + + See :c:member:`PyConfig.isolated`. + + .. c:member:: int legacy_windows_fs_encoding (Windows only) + + If non-zero, disable UTF-8 Mode, set the Python filesystem encoding to + ``mbcs``, set the filesystem error handler to ``replace``. + + Only available on Windows. ``#ifdef MS_WINDOWS`` macro can be used for + Windows specific code. + + .. c:member:: int parse_argv + + If non-zero, :c:func:`Py_PreInitializeFromArgs` and + :c:func:`Py_PreInitializeFromBytesArgs` parse their ``argv`` argument the + same way the regular Python parses command line arguments: see + :ref:`Command Line Arguments `. + + .. c:member:: int use_environment + + See :c:member:`PyConfig.use_environment`. + + .. c:member:: int utf8_mode + + If non-zero, enable the UTF-8 mode. + +Preinitialization with PyPreConfig +---------------------------------- + +Functions to preinitialize Python: + +.. c:function:: PyStatus Py_PreInitialize(const PyPreConfig *preconfig) + + Preinitialize Python from *preconfig* preconfiguration. + +.. c:function:: PyStatus Py_PreInitializeFromBytesArgs(const PyPreConfig *preconfig, int argc, char * const *argv) + + Preinitialize Python from *preconfig* preconfiguration and command line + arguments (bytes strings). + +.. c:function:: PyStatus Py_PreInitializeFromArgs(const PyPreConfig *preconfig, int argc, wchar_t * const * argv) + + Preinitialize Python from *preconfig* preconfiguration and command line + arguments (wide strings). + +The caller is responsible to handle exceptions (error or exit) using +:c:func:`PyStatus_Exception` and :c:func:`Py_ExitStatusException`. + +For :ref:`Python Configuration ` +(:c:func:`PyPreConfig_InitPythonConfig`), if Python is initialized with +command line arguments, the command line arguments must also be passed to +preinitialize Python, since they have an effect on the pre-configuration +like encodings. For example, the :option:`-X utf8 <-X>` command line option +enables the UTF-8 Mode. + +``PyMem_SetAllocator()`` can be called after :c:func:`Py_PreInitialize` and +before :c:func:`Py_InitializeFromConfig` to install a custom memory allocator. +It can be called before :c:func:`Py_PreInitialize` if +:c:member:`PyPreConfig.allocator` is set to ``PYMEM_ALLOCATOR_NOT_SET``. + +Python memory allocation functions like :c:func:`PyMem_RawMalloc` must not be +used before Python preinitialization, whereas calling directly ``malloc()`` and +``free()`` is always safe. :c:func:`Py_DecodeLocale` must not be called before +the preinitialization. + +Example using the preinitialization to enable the UTF-8 Mode:: + + 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 will speak UTF-8 */ + + Py_Initialize(); + /* ... use Python API here ... */ + Py_Finalize(); + + +PyConfig +-------- + +.. c:type:: PyConfig + + Structure containing most parameters to configure Python. + + Structure methods: + + .. c:function:: void PyConfig_InitPythonConfig(PyConfig *config) + + Initialize configuration with :ref:`Python Configuration + `. + + .. c:function:: void PyConfig_InitIsolatedConfig(PyConfig *config) + + Initialize configuration with :ref:`Isolated Configuration + `. + + .. c:function:: PyStatus PyConfig_SetString(PyConfig *config, wchar_t * const *config_str, const wchar_t *str) + + Copy the wide character string *str* into ``*config_str``. + + Preinitialize Python if needed. + + .. c:function:: PyStatus PyConfig_SetBytesString(PyConfig *config, wchar_t * const *config_str, const char *str) + + Decode *str* using ``Py_DecodeLocale()`` and set the result into ``*config_str``. + + Preinitialize Python if needed. + + .. c:function:: PyStatus PyConfig_SetArgv(PyConfig *config, int argc, wchar_t * const *argv) + + Set command line arguments from wide character strings. + + Preinitialize Python if needed. + + .. c:function:: PyStatus PyConfig_SetBytesArgv(PyConfig *config, int argc, char * const *argv) + + Set command line arguments: decode bytes using :c:func:`Py_DecodeLocale`. + + Preinitialize Python if needed. + + .. c:function:: PyStatus PyConfig_SetWideStringList(PyConfig *config, PyWideStringList *list, Py_ssize_t length, wchar_t **items) + + Set the list of wide strings *list* to *length* and *items*. + + Preinitialize Python if needed. + + .. c:function:: PyStatus PyConfig_Read(PyConfig *config) + + Read all Python configuration. + + Fields which are already initialized are left unchanged. + + Preinitialize Python if needed. + + .. c:function:: void PyConfig_Clear(PyConfig *config) + + Release configuration memory. + + Most ``PyConfig`` methods preinitialize Python if needed. In that case, the + Python preinitialization configuration in based on the :c:type:`PyConfig`. + If configuration fields which are in common with :c:type:`PyPreConfig` are + tuned, they must be set before calling a :c:type:`PyConfig` method: + + * :c:member:`~PyConfig.dev_mode` + * :c:member:`~PyConfig.isolated` + * :c:member:`~PyConfig.parse_argv` + * :c:member:`~PyConfig.use_environment` + + Moreover, if :c:func:`PyConfig_SetArgv` or :c:func:`PyConfig_SetBytesArgv` + is used, this method must be called first, before other methods, since the + preinitialization configuration depends on command line arguments (if + :c:member:`parse_argv` is non-zero). + + The caller of these methods is responsible to handle exceptions (error or + exit) using ``PyStatus_Exception()`` and ``Py_ExitStatusException()``. + + Structure fields: + + .. c:member:: PyWideStringList argv + + Command line arguments, :data:`sys.argv`. See + :c:member:`~PyConfig.parse_argv` to parse :c:member:`~PyConfig.argv` the + same way the regular Python parses Python command line arguments. If + :c:member:`~PyConfig.argv` is empty, an empty string is added to ensure + that :data:`sys.argv` always exists and is never empty. + + .. c:member:: wchar_t* base_exec_prefix + + :data:`sys.base_exec_prefix`. + + .. c:member:: wchar_t* base_executable + + :data:`sys._base_executable`: ``__PYVENV_LAUNCHER__`` environment + variable value, or copy of :c:member:`PyConfig.executable`. + + .. c:member:: wchar_t* base_prefix + + :data:`sys.base_prefix`. + + .. c:member:: int buffered_stdio + + If equals to 0, enable unbuffered mode, making the stdout and stderr + streams unbuffered. + + stdin is always opened in buffered mode. + + .. c:member:: int bytes_warning + + If equals to 1, issue a warning when comparing :class:`bytes` or + :class:`bytearray` with :class:`str`, or comparing :class:`bytes` with + :class:`int`. If equal or greater to 2, raise a :exc:`BytesWarning` + exception. + + .. c:member:: wchar_t* check_hash_pycs_mode + + Control the validation behavior of hash-based ``.pyc`` files (see + :pep:`552`): :option:`--check-hash-based-pycs` command line option value. + + Valid values: ``always``, ``never`` and ``default``. + + The default value is: ``default``. + + .. c:member:: int configure_c_stdio + + If non-zero, configure C standard streams (``stdio``, ``stdout``, + ``stdout``). For example, set their mode to ``O_BINARY`` on Windows. + + .. c:member:: int dev_mode + + If non-zero, enable the :ref:`Python Development Mode `. + + .. c:member:: int dump_refs + + If non-zero, dump all objects which are still alive at exit. + + ``Py_TRACE_REFS`` macro must be defined in build. + + .. c:member:: wchar_t* exec_prefix + + :data:`sys.exec_prefix`. + + .. c:member:: wchar_t* executable + + :data:`sys.executable`. + + .. c:member:: int faulthandler + + If non-zero, call :func:`faulthandler.enable` at startup. + + .. c:member:: wchar_t* filesystem_encoding + + Filesystem encoding, :func:`sys.getfilesystemencoding`. + + .. c:member:: wchar_t* filesystem_errors + + Filesystem encoding errors, :func:`sys.getfilesystemencodeerrors`. + + .. c:member:: unsigned long hash_seed + .. c:member:: int use_hash_seed + + Randomized hash function seed. + + If :c:member:`~PyConfig.use_hash_seed` is zero, a seed is chosen randomly + at Pythonstartup, and :c:member:`~PyConfig.hash_seed` is ignored. + + .. c:member:: wchar_t* home + + Python home directory. + + Initialized from :envvar:`PYTHONHOME` environment variable value by + default. + + .. c:member:: int import_time + + If non-zero, profile import time. + + .. c:member:: int inspect + + Enter interactive mode after executing a script or a command. + + .. c:member:: int install_signal_handlers + + Install signal handlers? + + .. c:member:: int interactive + + Interactive mode. + + .. c:member:: int isolated + + If greater than 0, enable isolated mode: + + * :data:`sys.path` contains neither the script's directory (computed from + ``argv[0]`` or the current directory) nor the user's site-packages + directory. + * Python REPL doesn't import :mod:`readline` nor enable default readline + configuration on interactive prompts. + * Set :c:member:`~PyConfig.use_environment` and + :c:member:`~PyConfig.user_site_directory` to 0. + + .. c:member:: int legacy_windows_stdio + + If non-zero, use :class:`io.FileIO` instead of + :class:`io.WindowsConsoleIO` for :data:`sys.stdin`, :data:`sys.stdout` + and :data:`sys.stderr`. + + Only available on Windows. ``#ifdef MS_WINDOWS`` macro can be used for + Windows specific code. + + .. c:member:: int malloc_stats + + If non-zero, dump statistics on :ref:`Python pymalloc memory allocator + ` at exit. + + The option is ignored if Python is built using ``--without-pymalloc``. + + .. c:member:: wchar_t* pythonpath_env + + Module search paths as a string separated by ``DELIM`` + (:data:`os.path.pathsep`). + + Initialized from :envvar:`PYTHONPATH` environment variable value by + default. + + .. c:member:: PyWideStringList module_search_paths + .. c:member:: int module_search_paths_set + + :data:`sys.path`. If :c:member:`~PyConfig.module_search_paths_set` is + equal to 0, the :c:member:`~PyConfig.module_search_paths` is overridden + by the function calculating the :ref:`Path Configuration + `. + + .. c:member:: int optimization_level + + Compilation optimization level: + + * 0: Peephole optimizer (and ``__debug__`` is set to ``True``) + * 1: Remove assertions, set ``__debug__`` to ``False`` + * 2: Strip docstrings + + .. c:member:: int parse_argv + + If non-zero, parse :c:member:`~PyConfig.argv` the same way the regular + Python command line arguments, and strip Python arguments from + :c:member:`~PyConfig.argv`: see :ref:`Command Line Arguments + `. + + .. c:member:: int parser_debug + + If non-zero, turn on parser debugging output (for expert only, depending + on compilation options). + + .. c:member:: int pathconfig_warnings + + If equal to 0, suppress warnings when calculating the :ref:`Path + Configuration ` (Unix only, Windows does not log any + warning). Otherwise, warnings are written into ``stderr``. + + .. c:member:: wchar_t* prefix + + :data:`sys.prefix`. + + .. c:member:: wchar_t* program_name + + Program name. Used to initialize :c:member:`~PyConfig.executable`, and in + early error messages. + + .. c:member:: wchar_t* pycache_prefix + + :data:`sys.pycache_prefix`: ``.pyc`` cache prefix. + + If ``NULL``, :data:`sys.pycache_prefix` is set to ``None``. + + .. c:member:: int quiet + + Quiet mode. For example, don't display the copyright and version messages + in interactive mode. + + .. c:member:: wchar_t* run_command + + ``python3 -c COMMAND`` argument. Used by :c:func:`Py_RunMain`. + + .. c:member:: wchar_t* run_filename + + ``python3 FILENAME`` argument. Used by :c:func:`Py_RunMain`. + + .. c:member:: wchar_t* run_module + + ``python3 -m MODULE`` argument. Used by :c:func:`Py_RunMain`. + + .. c:member:: int show_ref_count + + Show total reference count at exit? + + Set to 1 by :option:`-X showrefcount <-X>` command line option. + + Need a debug build of Python (``Py_REF_DEBUG`` macro must be defined). + + .. c:member:: int site_import + + Import the :mod:`site` module at startup? + + .. c:member:: int skip_source_first_line + + Skip the first line of the source? + + .. c:member:: wchar_t* stdio_encoding + .. c:member:: wchar_t* stdio_errors + + Encoding and encoding errors of :data:`sys.stdin`, :data:`sys.stdout` and + :data:`sys.stderr`. + + .. c:member:: int tracemalloc + + If non-zero, call :func:`tracemalloc.start` at startup. + + .. c:member:: int use_environment + + If greater than 0, use :ref:`environment variables `. + + .. c:member:: int user_site_directory + + If non-zero, add user site directory to :data:`sys.path`. + + .. c:member:: int verbose + + If non-zero, enable verbose mode. + + .. c:member:: PyWideStringList warnoptions + + :data:`sys.warnoptions`: options of the :mod:`warnings` module to build + warnings filters: lowest to highest priority. + + The :mod:`warnings` module adds :data:`sys.warnoptions` in the reverse + order: the last :c:member:`PyConfig.warnoptions` item becomes the first + item of :data:`warnings.filters` which is checked first (highest + priority). + + .. c:member:: int write_bytecode + + If non-zero, write ``.pyc`` files. + + :data:`sys.dont_write_bytecode` is initialized to the inverted value of + :c:member:`~PyConfig.write_bytecode`. + + .. c:member:: PyWideStringList xoptions + + :data:`sys._xoptions`. + + .. c:member:: int _use_peg_parser + + Enable PEG parser? Default: 1. + + Set to 0 by :option:`-X oldparser <-X>` and :envvar:`PYTHONOLDPARSER`. + + See also :pep:`617`. + + .. deprecated-removed:: 3.9 3.10 + +If ``parse_argv`` is non-zero, ``argv`` arguments are parsed the same +way the regular Python parses command line arguments, and Python +arguments are stripped from ``argv``: see :ref:`Command Line Arguments +`. + +The ``xoptions`` options are parsed to set other options: see :option:`-X` +option. + +.. versionchanged:: 3.9 + + The ``show_alloc_count`` field has been removed. + + +Initialization with PyConfig +---------------------------- + +Function to initialize Python: + +.. c:function:: PyStatus Py_InitializeFromConfig(const PyConfig *config) + + Initialize Python from *config* configuration. + +The caller is responsible to handle exceptions (error or exit) using +:c:func:`PyStatus_Exception` and :c:func:`Py_ExitStatusException`. + +If ``PyImport_FrozenModules``, ``PyImport_AppendInittab()`` or +``PyImport_ExtendInittab()`` are used, they must be set or called after Python +preinitialization and before the Python initialization. + +Example setting the program name:: + + 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 fail; + } + + status = Py_InitializeFromConfig(&config); + if (PyStatus_Exception(status)) { + goto fail; + } + PyConfig_Clear(&config); + return; + + fail: + PyConfig_Clear(&config); + Py_ExitStatusException(status); + } + +More complete example modifying the default configuration, read the +configuration, and then override some parameters:: + + 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); + if (PyStatus_Exception(status)) { + goto done; + } + + /* Read all configuration at once */ + status = PyConfig_Read(&config); + if (PyStatus_Exception(status)) { + goto done; + } + + /* Append our custom search path to sys.path */ + 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; + } + + +.. _init-isolated-conf: + +Isolated Configuration +---------------------- + +:c:func:`PyPreConfig_InitIsolatedConfig` and +:c:func:`PyConfig_InitIsolatedConfig` functions create a configuration to +isolate Python from the system. For example, to embed Python into an +application. + +This configuration ignores global configuration variables, environments +variables, command line arguments (:c:member:`PyConfig.argv` is not parsed) +and user site directory. The C standard streams (ex: ``stdout``) and the +LC_CTYPE locale are left unchanged. Signal handlers are not installed. + +Configuration files are still used with this configuration. Set the +:ref:`Path Configuration ` ("output fields") to ignore these +configuration files and avoid the function computing the default path +configuration. + + +.. _init-python-config: + +Python Configuration +-------------------- + +:c:func:`PyPreConfig_InitPythonConfig` and :c:func:`PyConfig_InitPythonConfig` +functions create a configuration to build a customized Python which behaves as +the regular Python. + +Environments variables and command line arguments are used to configure +Python, whereas global configuration variables are ignored. + +This function enables C locale coercion (:pep:`538`) and UTF-8 Mode +(:pep:`540`) depending on the LC_CTYPE locale, :envvar:`PYTHONUTF8` and +:envvar:`PYTHONCOERCECLOCALE` environment variables. + +Example of customized Python always running in isolated mode:: + + 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 fail; + } + + status = Py_InitializeFromConfig(&config); + if (PyStatus_Exception(status)) { + goto fail; + } + PyConfig_Clear(&config); + + return Py_RunMain(); + + fail: + 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); + } + + +.. _init-path-config: + +Path Configuration +------------------ + +:c:type:`PyConfig` contains multiple fields for the path configuration: + +* Path configuration inputs: + + * :c:member:`PyConfig.home` + * :c:member:`PyConfig.pathconfig_warnings` + * :c:member:`PyConfig.program_name` + * :c:member:`PyConfig.pythonpath_env` + * current working directory: to get absolute paths + * ``PATH`` environment variable to get the program full path + (from :c:member:`PyConfig.program_name`) + * ``__PYVENV_LAUNCHER__`` environment variable + * (Windows only) Application paths in the registry under + "Software\Python\PythonCore\X.Y\PythonPath" of HKEY_CURRENT_USER and + HKEY_LOCAL_MACHINE (where X.Y is the Python version). + +* Path configuration output fields: + + * :c:member:`PyConfig.base_exec_prefix` + * :c:member:`PyConfig.base_executable` + * :c:member:`PyConfig.base_prefix` + * :c:member:`PyConfig.exec_prefix` + * :c:member:`PyConfig.executable` + * :c:member:`PyConfig.module_search_paths_set`, + :c:member:`PyConfig.module_search_paths` + * :c:member:`PyConfig.prefix` + +If at least one "output field" is not set, Python calculates the path +configuration to fill unset fields. If +:c:member:`~PyConfig.module_search_paths_set` is equal to 0, +:c:member:`~PyConfig.module_search_paths` is overridden and +:c:member:`~PyConfig.module_search_paths_set` is set to 1. + +It is possible to completely ignore the function calculating the default +path configuration by setting explicitly all path configuration output +fields listed above. A string is considered as set even if it is non-empty. +``module_search_paths`` is considered as set if +``module_search_paths_set`` is set to 1. In this case, path +configuration input fields are ignored as well. + +Set :c:member:`~PyConfig.pathconfig_warnings` to 0 to suppress warnings when +calculating the path configuration (Unix only, Windows does not log any warning). + +If :c:member:`~PyConfig.base_prefix` or :c:member:`~PyConfig.base_exec_prefix` +fields are not set, they inherit their value from :c:member:`~PyConfig.prefix` +and :c:member:`~PyConfig.exec_prefix` respectively. + +:c:func:`Py_RunMain` and :c:func:`Py_Main` modify :data:`sys.path`: + +* If :c:member:`~PyConfig.run_filename` is set and is a directory which contains a + ``__main__.py`` script, prepend :c:member:`~PyConfig.run_filename` to + :data:`sys.path`. +* If :c:member:`~PyConfig.isolated` is zero: + + * If :c:member:`~PyConfig.run_module` is set, prepend the current directory + to :data:`sys.path`. Do nothing if the current directory cannot be read. + * If :c:member:`~PyConfig.run_filename` is set, prepend the directory of the + filename to :data:`sys.path`. + * Otherwise, prepend an empty string to :data:`sys.path`. + +If :c:member:`~PyConfig.site_import` is non-zero, :data:`sys.path` can be +modified by the :mod:`site` module. If +:c:member:`~PyConfig.user_site_directory` is non-zero and the user's +site-package directory exists, the :mod:`site` module appends the user's +site-package directory to :data:`sys.path`. + +The following configuration files are used by the path configuration: + +* ``pyvenv.cfg`` +* ``python._pth`` (Windows only) +* ``pybuilddir.txt`` (Unix only) + +The ``__PYVENV_LAUNCHER__`` environment variable is used to set +:c:member:`PyConfig.base_executable` + + +Py_RunMain() +------------ + +.. c:function:: int Py_RunMain(void) + + Execute the command (:c:member:`PyConfig.run_command`), the script + (:c:member:`PyConfig.run_filename`) or the module + (:c:member:`PyConfig.run_module`) specified on the command line or in the + configuration. + + By default and when if :option:`-i` option is used, run the REPL. + + Finally, finalizes Python and returns an exit status that can be passed to + the ``exit()`` function. + +See :ref:`Python Configuration ` for an example of +customized Python always running in isolated mode using +:c:func:`Py_RunMain`. + + +Multi-Phase Initialization Private Provisional API +-------------------------------------------------- + +This section is a private provisional API introducing multi-phase +initialization, the core feature of the :pep:`432`: + +* "Core" initialization phase, "bare minimum Python": + + * Builtin types; + * Builtin exceptions; + * Builtin and frozen modules; + * The :mod:`sys` module is only partially initialized + (ex: :data:`sys.path` doesn't exist yet). + +* "Main" initialization phase, Python is fully initialized: + + * Install and configure :mod:`importlib`; + * Apply the :ref:`Path Configuration `; + * Install signal handlers; + * Finish :mod:`sys` module initialization (ex: create :data:`sys.stdout` + and :data:`sys.path`); + * Enable optional features like :mod:`faulthandler` and :mod:`tracemalloc`; + * Import the :mod:`site` module; + * etc. + +Private provisional API: + +* :c:member:`PyConfig._init_main`: if set to 0, + :c:func:`Py_InitializeFromConfig` stops at the "Core" initialization phase. +* :c:member:`PyConfig._isolated_interpreter`: if non-zero, + disallow threads, subprocesses and fork. + +.. c:function:: PyStatus _Py_InitializeMain(void) + + Move to the "Main" initialization phase, finish the Python initialization. + +No module is imported during the "Core" phase and the ``importlib`` module is +not configured: the :ref:`Path Configuration ` is only +applied during the "Main" phase. It may allow to customize Python in Python to +override or tune the :ref:`Path Configuration `, maybe +install a custom :data:`sys.meta_path` importer or an import hook, etc. + +It may become possible to calculatin the :ref:`Path Configuration +` in Python, after the Core phase and before the Main phase, +which is one of the :pep:`432` motivation. + +The "Core" phase is not properly defined: what should be and what should +not be available at this phase is not specified yet. The API is marked +as private and provisional: the API can be modified or even be removed +anytime until a proper public API is designed. + +Example running Python code between "Core" and "Main" initialization +phases:: + + 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( + "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); + } + } diff --git a/cpython_2/environment/repo/Doc/c-api/intro.rst b/cpython_2/environment/repo/Doc/c-api/intro.rst new file mode 100644 index 0000000000000000000000000000000000000000..e89a788de0d503e3fb14bd69e1e300b395f9fbd0 --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/intro.rst @@ -0,0 +1,785 @@ +.. highlight:: c + + +.. _api-intro: + +************ +Introduction +************ + +The Application Programmer's Interface to Python gives C and C++ programmers +access to the Python interpreter at a variety of levels. The API is equally +usable from C++, but for brevity it is generally referred to as the Python/C +API. There are two fundamentally different reasons for using the Python/C API. +The first reason is to write *extension modules* for specific purposes; these +are C modules that extend the Python interpreter. This is probably the most +common use. The second reason is to use Python as a component in a larger +application; this technique is generally referred to as :dfn:`embedding` Python +in an application. + +Writing an extension module is a relatively well-understood process, where a +"cookbook" approach works well. There are several tools that automate the +process to some extent. While people have embedded Python in other +applications since its early existence, the process of embedding Python is +less straightforward than writing an extension. + +Many API functions are useful independent of whether you're embedding or +extending Python; moreover, most applications that embed Python will need to +provide a custom extension as well, so it's probably a good idea to become +familiar with writing an extension before attempting to embed Python in a real +application. + + +Coding standards +================ + +If you're writing C code for inclusion in CPython, you **must** follow the +guidelines and standards defined in :PEP:`7`. These guidelines apply +regardless of the version of Python you are contributing to. Following these +conventions is not necessary for your own third party extension modules, +unless you eventually expect to contribute them to Python. + + +.. _api-includes: + +Include Files +============= + +All function, type and macro definitions needed to use the Python/C API are +included in your code by the following line:: + + #define PY_SSIZE_T_CLEAN + #include + +This implies inclusion of the following standard headers: ````, +````, ````, ````, ```` and ```` +(if available). + +.. note:: + + Since Python may define some pre-processor definitions which affect the standard + headers on some systems, you *must* include :file:`Python.h` before any standard + headers are included. + + It is recommended to always define ``PY_SSIZE_T_CLEAN`` before including + ``Python.h``. See :ref:`arg-parsing` for a description of this macro. + +All user visible names defined by Python.h (except those defined by the included +standard headers) have one of the prefixes ``Py`` or ``_Py``. Names beginning +with ``_Py`` are for internal use by the Python implementation and should not be +used by extension writers. Structure member names do not have a reserved prefix. + +.. note:: + + User code should never define names that begin with ``Py`` or ``_Py``. This + confuses the reader, and jeopardizes the portability of the user code to + future Python versions, which may define additional names beginning with one + of these prefixes. + +The header files are typically installed with Python. On Unix, these are +located in the directories :file:`{prefix}/include/pythonversion/` and +:file:`{exec_prefix}/include/pythonversion/`, where :envvar:`prefix` and +:envvar:`exec_prefix` are defined by the corresponding parameters to Python's +:program:`configure` script and *version* is +``'%d.%d' % sys.version_info[:2]``. On Windows, the headers are installed +in :file:`{prefix}/include`, where :envvar:`prefix` is the installation +directory specified to the installer. + +To include the headers, place both directories (if different) on your compiler's +search path for includes. Do *not* place the parent directories on the search +path and then use ``#include ``; this will break on +multi-platform builds since the platform independent headers under +:envvar:`prefix` include the platform specific headers from +:envvar:`exec_prefix`. + +C++ users should note that although the API is defined entirely using C, the +header files properly declare the entry points to be ``extern "C"``. As a result, +there is no need to do anything special to use the API from C++. + + +Useful macros +============= + +Several useful macros are defined in the Python header files. Many are +defined closer to where they are useful (e.g. :c:macro:`Py_RETURN_NONE`). +Others of a more general utility are defined here. This is not necessarily a +complete listing. + +.. c:macro:: Py_UNREACHABLE() + + Use this when you have a code path that cannot be reached by design. + For example, in the ``default:`` clause in a ``switch`` statement for which + all possible values are covered in ``case`` statements. Use this in places + where you might be tempted to put an ``assert(0)`` or ``abort()`` call. + + In release mode, the macro helps the compiler to optimize the code, and + avoids a warning about unreachable code. For example, the macro is + implemented with ``__builtin_unreachable()`` on GCC in release mode. + + A use for ``Py_UNREACHABLE()`` is following a call a function that + never returns but that is not declared :c:macro:`_Py_NO_RETURN`. + + If a code path is very unlikely code but can be reached under exceptional + case, this macro must not be used. For example, under low memory condition + or if a system call returns a value out of the expected range. In this + case, it's better to report the error to the caller. If the error cannot + be reported to caller, :c:func:`Py_FatalError` can be used. + + .. versionadded:: 3.7 + +.. c:macro:: Py_ABS(x) + + Return the absolute value of ``x``. + + .. versionadded:: 3.3 + +.. c:macro:: Py_MIN(x, y) + + Return the minimum value between ``x`` and ``y``. + + .. versionadded:: 3.3 + +.. c:macro:: Py_MAX(x, y) + + Return the maximum value between ``x`` and ``y``. + + .. versionadded:: 3.3 + +.. c:macro:: Py_STRINGIFY(x) + + Convert ``x`` to a C string. E.g. ``Py_STRINGIFY(123)`` returns + ``"123"``. + + .. versionadded:: 3.4 + +.. c:macro:: Py_MEMBER_SIZE(type, member) + + Return the size of a structure (``type``) ``member`` in bytes. + + .. versionadded:: 3.6 + +.. c:macro:: Py_CHARMASK(c) + + Argument must be a character or an integer in the range [-128, 127] or [0, + 255]. This macro returns ``c`` cast to an ``unsigned char``. + +.. c:macro:: Py_GETENV(s) + + Like ``getenv(s)``, but returns ``NULL`` if :option:`-E` was passed on the + command line (i.e. if ``Py_IgnoreEnvironmentFlag`` is set). + +.. c:macro:: Py_UNUSED(arg) + + Use this for unused arguments in a function definition to silence compiler + warnings. Example: ``int func(int a, int Py_UNUSED(b)) { return a; }``. + + .. versionadded:: 3.4 + +.. c:macro:: Py_DEPRECATED(version) + + Use this for deprecated declarations. The macro must be placed before the + symbol name. + + Example:: + + Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void); + + .. versionchanged:: 3.8 + MSVC support was added. + +.. c:macro:: PyDoc_STRVAR(name, str) + + Creates a variable with name ``name`` that can be used in docstrings. + If Python is built without docstrings, the value will be empty. + + Use :c:macro:`PyDoc_STRVAR` for docstrings to support building + Python without docstrings, as specified in :pep:`7`. + + Example:: + + PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element."); + + static PyMethodDef deque_methods[] = { + // ... + {"pop", (PyCFunction)deque_pop, METH_NOARGS, pop_doc}, + // ... + } + +.. c:macro:: PyDoc_STR(str) + + Creates a docstring for the given input string or an empty string + if docstrings are disabled. + + Use :c:macro:`PyDoc_STR` in specifying docstrings to support + building Python without docstrings, as specified in :pep:`7`. + + Example:: + + static PyMethodDef pysqlite_row_methods[] = { + {"keys", (PyCFunction)pysqlite_row_keys, METH_NOARGS, + PyDoc_STR("Returns the keys of the row.")}, + {NULL, NULL} + }; + +.. _api-objects: + +Objects, Types and Reference Counts +=================================== + +.. index:: object: type + +Most Python/C API functions have one or more arguments as well as a return value +of type :c:type:`PyObject\*`. This type is a pointer to an opaque data type +representing an arbitrary Python object. Since all Python object types are +treated the same way by the Python language in most situations (e.g., +assignments, scope rules, and argument passing), it is only fitting that they +should be represented by a single C type. Almost all Python objects live on the +heap: you never declare an automatic or static variable of type +:c:type:`PyObject`, only pointer variables of type :c:type:`PyObject\*` can be +declared. The sole exception are the type objects; since these must never be +deallocated, they are typically static :c:type:`PyTypeObject` objects. + +All Python objects (even Python integers) have a :dfn:`type` and a +:dfn:`reference count`. An object's type determines what kind of object it is +(e.g., an integer, a list, or a user-defined function; there are many more as +explained in :ref:`types`). For each of the well-known types there is a macro +to check whether an object is of that type; for instance, ``PyList_Check(a)`` is +true if (and only if) the object pointed to by *a* is a Python list. + + +.. _api-refcounts: + +Reference Counts +---------------- + +The reference count is important because today's computers have a finite (and +often severely limited) memory size; it counts how many different places there +are that have a reference to an object. Such a place could be another object, +or a global (or static) C variable, or a local variable in some C function. +When an object's reference count becomes zero, the object is deallocated. If +it contains references to other objects, their reference count is decremented. +Those other objects may be deallocated in turn, if this decrement makes their +reference count become zero, and so on. (There's an obvious problem with +objects that reference each other here; for now, the solution is "don't do +that.") + +.. index:: + single: Py_INCREF() + single: Py_DECREF() + +Reference counts are always manipulated explicitly. The normal way is to use +the macro :c:func:`Py_INCREF` to increment an object's reference count by one, +and :c:func:`Py_DECREF` to decrement it by one. The :c:func:`Py_DECREF` macro +is considerably more complex than the incref one, since it must check whether +the reference count becomes zero and then cause the object's deallocator to be +called. The deallocator is a function pointer contained in the object's type +structure. The type-specific deallocator takes care of decrementing the +reference counts for other objects contained in the object if this is a compound +object type, such as a list, as well as performing any additional finalization +that's needed. There's no chance that the reference count can overflow; at +least as many bits are used to hold the reference count as there are distinct +memory locations in virtual memory (assuming ``sizeof(Py_ssize_t) >= sizeof(void*)``). +Thus, the reference count increment is a simple operation. + +It is not necessary to increment an object's reference count for every local +variable that contains a pointer to an object. In theory, the object's +reference count goes up by one when the variable is made to point to it and it +goes down by one when the variable goes out of scope. However, these two +cancel each other out, so at the end the reference count hasn't changed. The +only real reason to use the reference count is to prevent the object from being +deallocated as long as our variable is pointing to it. If we know that there +is at least one other reference to the object that lives at least as long as +our variable, there is no need to increment the reference count temporarily. +An important situation where this arises is in objects that are passed as +arguments to C functions in an extension module that are called from Python; +the call mechanism guarantees to hold a reference to every argument for the +duration of the call. + +However, a common pitfall is to extract an object from a list and hold on to it +for a while without incrementing its reference count. Some other operation might +conceivably remove the object from the list, decrementing its reference count +and possibly deallocating it. The real danger is that innocent-looking +operations may invoke arbitrary Python code which could do this; there is a code +path which allows control to flow back to the user from a :c:func:`Py_DECREF`, so +almost any operation is potentially dangerous. + +A safe approach is to always use the generic operations (functions whose name +begins with ``PyObject_``, ``PyNumber_``, ``PySequence_`` or ``PyMapping_``). +These operations always increment the reference count of the object they return. +This leaves the caller with the responsibility to call :c:func:`Py_DECREF` when +they are done with the result; this soon becomes second nature. + + +.. _api-refcountdetails: + +Reference Count Details +^^^^^^^^^^^^^^^^^^^^^^^ + +The reference count behavior of functions in the Python/C API is best explained +in terms of *ownership of references*. Ownership pertains to references, never +to objects (objects are not owned: they are always shared). "Owning a +reference" means being responsible for calling Py_DECREF on it when the +reference is no longer needed. Ownership can also be transferred, meaning that +the code that receives ownership of the reference then becomes responsible for +eventually decref'ing it by calling :c:func:`Py_DECREF` or :c:func:`Py_XDECREF` +when it's no longer needed---or passing on this responsibility (usually to its +caller). When a function passes ownership of a reference on to its caller, the +caller is said to receive a *new* reference. When no ownership is transferred, +the caller is said to *borrow* the reference. Nothing needs to be done for a +borrowed reference. + +Conversely, when a calling function passes in a reference to an object, there +are two possibilities: the function *steals* a reference to the object, or it +does not. *Stealing a reference* means that when you pass a reference to a +function, that function assumes that it now owns that reference, and you are not +responsible for it any longer. + +.. index:: + single: PyList_SetItem() + single: PyTuple_SetItem() + +Few functions steal references; the two notable exceptions are +:c:func:`PyList_SetItem` and :c:func:`PyTuple_SetItem`, which steal a reference +to the item (but not to the tuple or list into which the item is put!). These +functions were designed to steal a reference because of a common idiom for +populating a tuple or list with newly created objects; for example, the code to +create the tuple ``(1, 2, "three")`` could look like this (forgetting about +error handling for the moment; a better way to code this is shown below):: + + 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")); + +Here, :c:func:`PyLong_FromLong` returns a new reference which is immediately +stolen by :c:func:`PyTuple_SetItem`. When you want to keep using an object +although the reference to it will be stolen, use :c:func:`Py_INCREF` to grab +another reference before calling the reference-stealing function. + +Incidentally, :c:func:`PyTuple_SetItem` is the *only* way to set tuple items; +:c:func:`PySequence_SetItem` and :c:func:`PyObject_SetItem` refuse to do this +since tuples are an immutable data type. You should only use +:c:func:`PyTuple_SetItem` for tuples that you are creating yourself. + +Equivalent code for populating a list can be written using :c:func:`PyList_New` +and :c:func:`PyList_SetItem`. + +However, in practice, you will rarely use these ways of creating and populating +a tuple or list. There's a generic function, :c:func:`Py_BuildValue`, that can +create most common objects from C values, directed by a :dfn:`format string`. +For example, the above two blocks of code could be replaced by the following +(which also takes care of the error checking):: + + PyObject *tuple, *list; + + tuple = Py_BuildValue("(iis)", 1, 2, "three"); + list = Py_BuildValue("[iis]", 1, 2, "three"); + +It is much more common to use :c:func:`PyObject_SetItem` and friends with items +whose references you are only borrowing, like arguments that were passed in to +the function you are writing. In that case, their behaviour regarding reference +counts is much saner, since you don't have to increment a reference count so you +can give a reference away ("have it be stolen"). For example, this function +sets all items of a list (actually, any mutable sequence) to a given item:: + + 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; + } + +.. index:: single: set_all() + +The situation is slightly different for function return values. While passing +a reference to most functions does not change your ownership responsibilities +for that reference, many functions that return a reference to an object give +you ownership of the reference. The reason is simple: in many cases, the +returned object is created on the fly, and the reference you get is the only +reference to the object. Therefore, the generic functions that return object +references, like :c:func:`PyObject_GetItem` and :c:func:`PySequence_GetItem`, +always return a new reference (the caller becomes the owner of the reference). + +It is important to realize that whether you own a reference returned by a +function depends on which function you call only --- *the plumage* (the type of +the object passed as an argument to the function) *doesn't enter into it!* +Thus, if you extract an item from a list using :c:func:`PyList_GetItem`, you +don't own the reference --- but if you obtain the same item from the same list +using :c:func:`PySequence_GetItem` (which happens to take exactly the same +arguments), you do own a reference to the returned object. + +.. index:: + single: PyList_GetItem() + single: PySequence_GetItem() + +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 +using :c:func:`PySequence_GetItem`. :: + + long + sum_list(PyObject *list) + { + Py_ssize_t i, n; + long total = 0, value; + PyObject *item; + + 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; + } + +.. index:: single: sum_list() + +:: + + 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; + } + +.. index:: single: sum_sequence() + + +.. _api-types: + +Types +----- + +There are few other data types that play a significant role in the Python/C +API; most are simple C types such as :c:type:`int`, :c:type:`long`, +:c:type:`double` and :c:type:`char\*`. A few structure types are used to +describe static tables used to list the functions exported by a module or the +data attributes of a new object type, and another is used to describe the value +of a complex number. These will be discussed together with the functions that +use them. + + +.. _api-exceptions: + +Exceptions +========== + +The Python programmer only needs to deal with exceptions if specific error +handling is required; unhandled exceptions are automatically propagated to the +caller, then to the caller's caller, and so on, until they reach the top-level +interpreter, where they are reported to the user accompanied by a stack +traceback. + +.. index:: single: PyErr_Occurred() + +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 +made otherwise in a function's documentation. In general, when a function +encounters an error, it sets an exception, discards any object references that +it owns, and returns an error indicator. If not documented otherwise, this +indicator is either ``NULL`` or ``-1``, depending on the function's return type. +A few functions return a Boolean true/false result, with false indicating an +error. Very few functions return no explicit error indicator or have an +ambiguous return value, and require explicit testing for errors with +:c:func:`PyErr_Occurred`. These exceptions are always explicitly documented. + +.. index:: + single: PyErr_SetString() + single: PyErr_Clear() + +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 +two states: an exception has occurred, or not. The function +:c:func:`PyErr_Occurred` can be used to check for this: it returns a borrowed +reference to the exception type object when an exception has occurred, and +``NULL`` otherwise. There are a number of functions to set the exception state: +:c:func:`PyErr_SetString` is the most common (though not the most general) +function to set the exception state, and :c:func:`PyErr_Clear` clears the +exception state. + +The full exception state consists of three objects (all of which can be +``NULL``): the exception type, the corresponding exception value, and the +traceback. These have the same meanings as the Python result of +``sys.exc_info()``; however, they are not the same: the Python objects represent +the last exception being handled by a Python :keyword:`try` ... +:keyword:`except` statement, while the C level exception state only exists while +an exception is being passed on between C functions until it reaches the Python +bytecode interpreter's main loop, which takes care of transferring it to +``sys.exc_info()`` and friends. + +.. 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`, +which returns the per-thread exception state for Python code. Also, the +semantics of both ways to access the exception state have changed so that a +function which catches an exception will save and restore its thread's exception +state so as to preserve the exception state of its caller. This prevents common +bugs in exception handling code caused by an innocent-looking function +overwriting the exception being handled; it also reduces the often unwanted +lifetime extension for objects that are referenced by the stack frames in the +traceback. + +As a general principle, a function that calls another function to perform some +task should check whether the called function raised an exception, and if so, +pass the exception state on to its caller. It should discard any object +references that it owns, and return an error indicator, but it should *not* set +another exception --- that would overwrite the exception that was just raised, +and lose important information about the exact cause of the error. + +.. index:: single: sum_sequence() + +A simple example of detecting exceptions and passing them on is shown in the +:c:func:`sum_sequence` example above. It so happens that this example doesn't +need to clean up any owned references when it detects an error. The following +example function shows some error cleanup. First, to remind you why you like +Python, we show the equivalent Python code:: + + def incr_item(dict, key): + try: + item = dict[key] + except KeyError: + item = 0 + dict[key] = item + 1 + +.. index:: single: incr_item() + +Here is the corresponding C code, in all its glory:: + + 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(); + 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 */ + } + +.. index:: single: incr_item() + +.. index:: + single: PyErr_ExceptionMatches() + single: PyErr_Clear() + single: Py_XDECREF() + +This example represents an endorsed use of the ``goto`` statement in C! +It illustrates the use of :c:func:`PyErr_ExceptionMatches` and +:c:func:`PyErr_Clear` to handle specific exceptions, and the use of +:c:func:`Py_XDECREF` to dispose of owned references that may be ``NULL`` (note the +``'X'`` in the name; :c:func:`Py_DECREF` would crash when confronted with a +``NULL`` reference). It is important that the variables used to hold owned +references are initialized to ``NULL`` for this to work; likewise, the proposed +return value is initialized to ``-1`` (failure) and only set to success after +the final call made is successful. + + +.. _api-embedding: + +Embedding Python +================ + +The one important task that only embedders (as opposed to extension writers) of +the Python interpreter have to worry about is the initialization, and possibly +the finalization, of the Python interpreter. Most functionality of the +interpreter can only be used after the interpreter has been initialized. + +.. index:: + single: Py_Initialize() + module: builtins + module: __main__ + module: sys + triple: module; search; path + single: path (in module sys) + +The basic initialization function is :c:func:`Py_Initialize`. This initializes +the table of loaded modules, and creates the fundamental modules +:mod:`builtins`, :mod:`__main__`, and :mod:`sys`. It also +initializes the module search path (``sys.path``). + +.. index:: single: PySys_SetArgvEx() + +:c:func:`Py_Initialize` does not set the "script argument list" (``sys.argv``). +If this variable is needed by Python code that will be executed later, it must +be set explicitly with a call to ``PySys_SetArgvEx(argc, argv, updatepath)`` +after the call to :c:func:`Py_Initialize`. + +On most systems (in particular, on Unix and Windows, although the details are +slightly different), :c:func:`Py_Initialize` calculates the module search path +based upon its best guess for the location of the standard Python interpreter +executable, assuming that the Python library is found in a fixed location +relative to the Python interpreter executable. In particular, it looks for a +directory named :file:`lib/python{X.Y}` relative to the parent directory +where the executable named :file:`python` is found on the shell command search +path (the environment variable :envvar:`PATH`). + +For instance, if the Python executable is found in +:file:`/usr/local/bin/python`, it will assume that the libraries are in +:file:`/usr/local/lib/python{X.Y}`. (In fact, this particular path is also +the "fallback" location, used when no executable file named :file:`python` is +found along :envvar:`PATH`.) The user can override this behavior by setting the +environment variable :envvar:`PYTHONHOME`, or insert additional directories in +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() + +The embedding application can steer the search by calling +``Py_SetProgramName(file)`` *before* calling :c:func:`Py_Initialize`. Note that +:envvar:`PYTHONHOME` still overrides this and :envvar:`PYTHONPATH` is still +inserted in front of the standard path. An application that requires total +control has to provide its own implementation of :c:func:`Py_GetPath`, +:c:func:`Py_GetPrefix`, :c:func:`Py_GetExecPrefix`, and +:c:func:`Py_GetProgramFullPath` (all defined in :file:`Modules/getpath.c`). + +.. index:: single: Py_IsInitialized() + +Sometimes, it is desirable to "uninitialize" Python. For instance, the +application may want to start over (make another call to +:c:func:`Py_Initialize`) or the application is simply done with its use of +Python and wants to free memory allocated by Python. This can be accomplished +by calling :c:func:`Py_FinalizeEx`. The function :c:func:`Py_IsInitialized` returns +true if Python is currently in the initialized state. More information about +these functions is given in a later chapter. Notice that :c:func:`Py_FinalizeEx` +does *not* free all memory allocated by the Python interpreter, e.g. memory +allocated by extension modules currently cannot be released. + + +.. _api-debugging: + +Debugging Builds +================ + +Python can be built with several macros to enable extra checks of the +interpreter and extension modules. These checks tend to add a large amount of +overhead to the runtime so they are not enabled by default. + +A full list of the various types of debugging builds is in the file +:file:`Misc/SpecialBuilds.txt` in the Python source distribution. Builds are +available that support tracing of reference counts, debugging the memory +allocator, or low-level profiling of the main interpreter loop. Only the most +frequently-used builds will be described in the remainder of this section. + +Compiling the interpreter with the :c:macro:`Py_DEBUG` macro defined produces +what is generally meant by "a debug build" of Python. :c:macro:`Py_DEBUG` is +enabled in the Unix build by adding ``--with-pydebug`` to the +:file:`./configure` command. It is also implied by the presence of the +not-Python-specific :c:macro:`_DEBUG` macro. When :c:macro:`Py_DEBUG` is enabled +in the Unix build, compiler optimization is disabled. + +In addition to the reference count debugging described below, the following +extra checks are performed: + +* Extra checks are added to the object allocator. + +* Extra checks are added to the parser and compiler. + +* Downcasts from wide types to narrow types are checked for loss of information. + +* A number of assertions are added to the dictionary and set implementations. + In addition, the set object acquires a :meth:`test_c_api` method. + +* Sanity checks of the input arguments are added to frame creation. + +* The storage for ints is initialized with a known invalid pattern to catch + reference to uninitialized digits. + +* Low-level tracing and extra exception checking are added to the runtime + virtual machine. + +* Extra checks are added to the memory arena implementation. + +* Extra debugging is added to the thread module. + +There may be additional checks not mentioned here. + +Defining :c:macro:`Py_TRACE_REFS` enables reference tracing. When defined, a +circular doubly linked list of active objects is maintained by adding two extra +fields to every :c:type:`PyObject`. Total allocations are tracked as well. Upon +exit, all existing references are printed. (In interactive mode this happens +after every statement run by the interpreter.) Implied by :c:macro:`Py_DEBUG`. + +Please refer to :file:`Misc/SpecialBuilds.txt` in the Python source distribution +for more detailed information. + diff --git a/cpython_2/environment/repo/Doc/c-api/iter.rst b/cpython_2/environment/repo/Doc/c-api/iter.rst new file mode 100644 index 0000000000000000000000000000000000000000..a2992b3452f91c3c1fb9d3fc9a5ebd4a75e3be3d --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/iter.rst @@ -0,0 +1,46 @@ +.. highlight:: c + +.. _iterator: + +Iterator Protocol +================= + +There are two functions specifically for working with iterators. + +.. c:function:: int PyIter_Check(PyObject *o) + + Return true if the object *o* supports the iterator protocol. + + +.. c:function:: PyObject* PyIter_Next(PyObject *o) + + Return the next value from the iteration *o*. The object must be an iterator + (it is up to the caller to check this). If there are no remaining values, + returns ``NULL`` with no exception set. If an error occurs while retrieving + the item, returns ``NULL`` and passes along the exception. + +To write a loop which iterates over an iterator, the C code should look +something like this:: + + 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 */ + } diff --git a/cpython_2/environment/repo/Doc/c-api/iterator.rst b/cpython_2/environment/repo/Doc/c-api/iterator.rst new file mode 100644 index 0000000000000000000000000000000000000000..4d91e4a224fe82c119a450fedba4c36d70d6eb7b --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/iterator.rst @@ -0,0 +1,50 @@ +.. highlight:: c + +.. _iterator-objects: + +Iterator Objects +---------------- + +Python provides two general-purpose iterator objects. The first, a sequence +iterator, works with an arbitrary sequence supporting the :meth:`__getitem__` +method. The second works with a callable object and a sentinel value, calling +the callable for each item in the sequence, and ending the iteration when the +sentinel value is returned. + + +.. c:var:: PyTypeObject PySeqIter_Type + + Type object for iterator objects returned by :c:func:`PySeqIter_New` and the + one-argument form of the :func:`iter` built-in function for built-in sequence + types. + + +.. c:function:: int PySeqIter_Check(op) + + Return true if the type of *op* is :c:data:`PySeqIter_Type`. + + +.. c:function:: PyObject* PySeqIter_New(PyObject *seq) + + Return an iterator that works with a general sequence object, *seq*. The + iteration ends when the sequence raises :exc:`IndexError` for the subscripting + operation. + + +.. c:var:: PyTypeObject PyCallIter_Type + + Type object for iterator objects returned by :c:func:`PyCallIter_New` and the + two-argument form of the :func:`iter` built-in function. + + +.. c:function:: int PyCallIter_Check(op) + + Return true if the type of *op* is :c:data:`PyCallIter_Type`. + + +.. c:function:: PyObject* PyCallIter_New(PyObject *callable, PyObject *sentinel) + + Return a new iterator. The first parameter, *callable*, can be any Python + callable object that can be called with no parameters; each call to it should + return the next item in the iteration. When *callable* returns a value equal to + *sentinel*, the iteration will be terminated. diff --git a/cpython_2/environment/repo/Doc/c-api/list.rst b/cpython_2/environment/repo/Doc/c-api/list.rst new file mode 100644 index 0000000000000000000000000000000000000000..0bc0785f200d4cf5f6e9c683f1b30a25e8a4f9fc --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/list.rst @@ -0,0 +1,144 @@ +.. highlight:: c + +.. _listobjects: + +List Objects +------------ + +.. index:: object: list + + +.. c:type:: PyListObject + + This subtype of :c:type:`PyObject` represents a Python list object. + + +.. c:var:: PyTypeObject PyList_Type + + This instance of :c:type:`PyTypeObject` represents the Python list type. + This is the same object as :class:`list` in the Python layer. + + +.. c:function:: int PyList_Check(PyObject *p) + + Return true if *p* is a list object or an instance of a subtype of the list + type. + + +.. c:function:: int PyList_CheckExact(PyObject *p) + + Return true if *p* is a list object, but not an instance of a subtype of + the list type. + + +.. c:function:: PyObject* PyList_New(Py_ssize_t len) + + Return a new list of length *len* on success, or ``NULL`` on failure. + + .. note:: + + If *len* is greater than zero, the returned list object's items are + set to ``NULL``. Thus you cannot use abstract API functions such as + :c:func:`PySequence_SetItem` or expose the object to Python code before + setting all items to a real object with :c:func:`PyList_SetItem`. + + +.. c:function:: Py_ssize_t PyList_Size(PyObject *list) + + .. index:: builtin: len + + Return the length of the list object in *list*; this is equivalent to + ``len(list)`` on a list object. + + +.. c:function:: Py_ssize_t PyList_GET_SIZE(PyObject *list) + + Macro form of :c:func:`PyList_Size` without error checking. + + +.. c:function:: PyObject* PyList_GetItem(PyObject *list, Py_ssize_t index) + + Return the object at position *index* in the list pointed to by *list*. The + position must be non-negative; indexing from the end of the list is not + supported. If *index* is out of bounds (<0 or >=len(list)), + return ``NULL`` and set an :exc:`IndexError` exception. + + +.. c:function:: PyObject* PyList_GET_ITEM(PyObject *list, Py_ssize_t i) + + Macro form of :c:func:`PyList_GetItem` without error checking. + + +.. c:function:: int PyList_SetItem(PyObject *list, Py_ssize_t index, PyObject *item) + + Set the item at index *index* in list to *item*. Return ``0`` on success. + If *index* is out of bounds, return ``-1`` and set an :exc:`IndexError` + exception. + + .. note:: + + This function "steals" a reference to *item* and discards a reference to + an item already in the list at the affected position. + + +.. c:function:: void PyList_SET_ITEM(PyObject *list, Py_ssize_t i, PyObject *o) + + Macro form of :c:func:`PyList_SetItem` without error checking. This is + normally only used to fill in new lists where there is no previous content. + + .. note:: + + This macro "steals" a reference to *item*, and, unlike + :c:func:`PyList_SetItem`, does *not* discard a reference to any item that + is being replaced; any reference in *list* at position *i* will be + leaked. + + +.. c:function:: int PyList_Insert(PyObject *list, Py_ssize_t index, PyObject *item) + + Insert the item *item* into list *list* in front of index *index*. Return + ``0`` if successful; return ``-1`` and set an exception if unsuccessful. + Analogous to ``list.insert(index, item)``. + + +.. c:function:: int PyList_Append(PyObject *list, PyObject *item) + + Append the object *item* at the end of list *list*. Return ``0`` if + successful; return ``-1`` and set an exception if unsuccessful. Analogous + to ``list.append(item)``. + + +.. c:function:: PyObject* PyList_GetSlice(PyObject *list, Py_ssize_t low, Py_ssize_t high) + + Return a list of the objects in *list* containing the objects *between* *low* + and *high*. Return ``NULL`` and set an exception if unsuccessful. Analogous + to ``list[low:high]``. Indexing from the end of the list is not supported. + + +.. c:function:: int PyList_SetSlice(PyObject *list, Py_ssize_t low, Py_ssize_t high, PyObject *itemlist) + + Set the slice of *list* between *low* and *high* to the contents of + *itemlist*. Analogous to ``list[low:high] = itemlist``. The *itemlist* may + be ``NULL``, indicating the assignment of an empty list (slice deletion). + Return ``0`` on success, ``-1`` on failure. Indexing from the end of the + list is not supported. + + +.. c:function:: int PyList_Sort(PyObject *list) + + Sort the items of *list* in place. Return ``0`` on success, ``-1`` on + failure. This is equivalent to ``list.sort()``. + + +.. c:function:: int PyList_Reverse(PyObject *list) + + Reverse the items of *list* in place. Return ``0`` on success, ``-1`` on + failure. This is the equivalent of ``list.reverse()``. + + +.. c:function:: PyObject* PyList_AsTuple(PyObject *list) + + .. index:: builtin: tuple + + Return a new tuple object containing the contents of *list*; equivalent to + ``tuple(list)``. diff --git a/cpython_2/environment/repo/Doc/c-api/long.rst b/cpython_2/environment/repo/Doc/c-api/long.rst new file mode 100644 index 0000000000000000000000000000000000000000..c5c2aa60dcc35c1d2baf98417fdf5dbc80d2ad24 --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/long.rst @@ -0,0 +1,337 @@ +.. highlight:: c + +.. _longobjects: + +Integer Objects +--------------- + +.. index:: object: long integer + object: integer + +All integers are implemented as "long" integer objects of arbitrary size. + +On error, most ``PyLong_As*`` APIs return ``(return type)-1`` which cannot be +distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate. + +.. c:type:: PyLongObject + + This subtype of :c:type:`PyObject` represents a Python integer object. + + +.. c:var:: PyTypeObject PyLong_Type + + This instance of :c:type:`PyTypeObject` represents the Python integer type. + This is the same object as :class:`int` in the Python layer. + + +.. c:function:: int PyLong_Check(PyObject *p) + + Return true if its argument is a :c:type:`PyLongObject` or a subtype of + :c:type:`PyLongObject`. + + +.. c:function:: int PyLong_CheckExact(PyObject *p) + + Return true if its argument is a :c:type:`PyLongObject`, but not a subtype of + :c:type:`PyLongObject`. + + +.. c:function:: PyObject* PyLong_FromLong(long v) + + Return a new :c:type:`PyLongObject` object from *v*, or ``NULL`` on failure. + + The current implementation keeps an array of integer objects for all integers + between ``-5`` and ``256``, when you create an int in that range you actually + just get back a reference to the existing object. + + +.. c:function:: PyObject* PyLong_FromUnsignedLong(unsigned long v) + + Return a new :c:type:`PyLongObject` object from a C :c:type:`unsigned long`, or + ``NULL`` on failure. + + +.. c:function:: PyObject* PyLong_FromSsize_t(Py_ssize_t v) + + Return a new :c:type:`PyLongObject` object from a C :c:type:`Py_ssize_t`, or + ``NULL`` on failure. + + +.. c:function:: PyObject* PyLong_FromSize_t(size_t v) + + Return a new :c:type:`PyLongObject` object from a C :c:type:`size_t`, or + ``NULL`` on failure. + + +.. c:function:: PyObject* PyLong_FromLongLong(long long v) + + Return a new :c:type:`PyLongObject` object from a C :c:type:`long long`, or ``NULL`` + on failure. + + +.. c:function:: PyObject* PyLong_FromUnsignedLongLong(unsigned long long v) + + Return a new :c:type:`PyLongObject` object from a C :c:type:`unsigned long long`, + or ``NULL`` on failure. + + +.. c:function:: PyObject* PyLong_FromDouble(double v) + + Return a new :c:type:`PyLongObject` object from the integer part of *v*, or + ``NULL`` on failure. + + +.. c:function:: PyObject* PyLong_FromString(const char *str, char **pend, int base) + + Return a new :c:type:`PyLongObject` based on the string value in *str*, which + is interpreted according to the radix in *base*. If *pend* is non-``NULL``, + *\*pend* will point to the first character in *str* which follows the + representation of the number. If *base* is ``0``, *str* is interpreted using + the :ref:`integers` definition; in this case, leading zeros in a + non-zero decimal number raises a :exc:`ValueError`. If *base* is not ``0``, + it must be between ``2`` and ``36``, inclusive. Leading spaces and single + underscores after a base specifier and between digits are ignored. If there + are no digits, :exc:`ValueError` will be raised. + + +.. c:function:: PyObject* PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base) + + Convert a sequence of Unicode digits to a Python integer value. The Unicode + string is first encoded to a byte string using :c:func:`PyUnicode_EncodeDecimal` + and then converted using :c:func:`PyLong_FromString`. + + .. deprecated-removed:: 3.3 4.0 + Part of the old-style :c:type:`Py_UNICODE` API; please migrate to using + :c:func:`PyLong_FromUnicodeObject`. + + +.. c:function:: PyObject* PyLong_FromUnicodeObject(PyObject *u, int base) + + Convert a sequence of Unicode digits in the string *u* to a Python integer + value. The Unicode string is first encoded to a byte string using + :c:func:`PyUnicode_EncodeDecimal` and then converted using + :c:func:`PyLong_FromString`. + + .. versionadded:: 3.3 + + +.. c:function:: PyObject* PyLong_FromVoidPtr(void *p) + + Create a Python integer from the pointer *p*. The pointer value can be + retrieved from the resulting value using :c:func:`PyLong_AsVoidPtr`. + + +.. XXX alias PyLong_AS_LONG (for now) +.. c:function:: long PyLong_AsLong(PyObject *obj) + + .. index:: + single: LONG_MAX + single: OverflowError (built-in exception) + + Return a C :c:type:`long` representation of *obj*. If *obj* is not an + instance of :c:type:`PyLongObject`, first call its :meth:`__index__` or + :meth:`__int__` method (if present) to convert it to a + :c:type:`PyLongObject`. + + Raise :exc:`OverflowError` if the value of *obj* is out of range for a + :c:type:`long`. + + Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. + + .. versionchanged:: 3.8 + Use :meth:`__index__` if available. + + .. deprecated:: 3.8 + Using :meth:`__int__` is deprecated. + + +.. c:function:: long PyLong_AsLongAndOverflow(PyObject *obj, int *overflow) + + Return a C :c:type:`long` representation of *obj*. If *obj* is not an + instance of :c:type:`PyLongObject`, first call its :meth:`__index__` or + :meth:`__int__` method (if present) to convert it to a + :c:type:`PyLongObject`. + + If the value of *obj* is greater than :const:`LONG_MAX` or less than + :const:`LONG_MIN`, set *\*overflow* to ``1`` or ``-1``, respectively, and + return ``-1``; otherwise, set *\*overflow* to ``0``. If any other exception + occurs set *\*overflow* to ``0`` and return ``-1`` as usual. + + Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. + + .. versionchanged:: 3.8 + Use :meth:`__index__` if available. + + .. deprecated:: 3.8 + Using :meth:`__int__` is deprecated. + + +.. c:function:: long long PyLong_AsLongLong(PyObject *obj) + + .. index:: + single: OverflowError (built-in exception) + + Return a C :c:type:`long long` representation of *obj*. If *obj* is not an + instance of :c:type:`PyLongObject`, first call its :meth:`__index__` or + :meth:`__int__` method (if present) to convert it to a + :c:type:`PyLongObject`. + + Raise :exc:`OverflowError` if the value of *obj* is out of range for a + :c:type:`long long`. + + Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. + + .. versionchanged:: 3.8 + Use :meth:`__index__` if available. + + .. deprecated:: 3.8 + Using :meth:`__int__` is deprecated. + + +.. c:function:: long long PyLong_AsLongLongAndOverflow(PyObject *obj, int *overflow) + + Return a C :c:type:`long long` representation of *obj*. If *obj* is not an + instance of :c:type:`PyLongObject`, first call its :meth:`__index__` or + :meth:`__int__` method (if present) to convert it to a + :c:type:`PyLongObject`. + + If the value of *obj* is greater than :const:`LLONG_MAX` or less than + :const:`LLONG_MIN`, set *\*overflow* to ``1`` or ``-1``, respectively, + and return ``-1``; otherwise, set *\*overflow* to ``0``. If any other + exception occurs set *\*overflow* to ``0`` and return ``-1`` as usual. + + Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. + + .. versionadded:: 3.2 + + .. versionchanged:: 3.8 + Use :meth:`__index__` if available. + + .. deprecated:: 3.8 + Using :meth:`__int__` is deprecated. + + +.. c:function:: Py_ssize_t PyLong_AsSsize_t(PyObject *pylong) + + .. index:: + single: PY_SSIZE_T_MAX + single: OverflowError (built-in exception) + + Return a C :c:type:`Py_ssize_t` representation of *pylong*. *pylong* must + be an instance of :c:type:`PyLongObject`. + + Raise :exc:`OverflowError` if the value of *pylong* is out of range for a + :c:type:`Py_ssize_t`. + + Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. + + +.. c:function:: unsigned long PyLong_AsUnsignedLong(PyObject *pylong) + + .. index:: + single: ULONG_MAX + single: OverflowError (built-in exception) + + Return a C :c:type:`unsigned long` representation of *pylong*. *pylong* + must be an instance of :c:type:`PyLongObject`. + + Raise :exc:`OverflowError` if the value of *pylong* is out of range for a + :c:type:`unsigned long`. + + Returns ``(unsigned long)-1`` on error. + Use :c:func:`PyErr_Occurred` to disambiguate. + + +.. c:function:: size_t PyLong_AsSize_t(PyObject *pylong) + + .. index:: + single: SIZE_MAX + single: OverflowError (built-in exception) + + Return a C :c:type:`size_t` representation of *pylong*. *pylong* must be + an instance of :c:type:`PyLongObject`. + + Raise :exc:`OverflowError` if the value of *pylong* is out of range for a + :c:type:`size_t`. + + Returns ``(size_t)-1`` on error. + Use :c:func:`PyErr_Occurred` to disambiguate. + + +.. c:function:: unsigned long long PyLong_AsUnsignedLongLong(PyObject *pylong) + + .. index:: + single: OverflowError (built-in exception) + + Return a C :c:type:`unsigned long long` representation of *pylong*. *pylong* + must be an instance of :c:type:`PyLongObject`. + + Raise :exc:`OverflowError` if the value of *pylong* is out of range for an + :c:type:`unsigned long long`. + + Returns ``(unsigned long long)-1`` on error. + Use :c:func:`PyErr_Occurred` to disambiguate. + + .. versionchanged:: 3.1 + A negative *pylong* now raises :exc:`OverflowError`, not :exc:`TypeError`. + + +.. c:function:: unsigned long PyLong_AsUnsignedLongMask(PyObject *obj) + + Return a C :c:type:`unsigned long` representation of *obj*. If *obj* + is not an instance of :c:type:`PyLongObject`, first call its + :meth:`__index__` or :meth:`__int__` method (if present) to convert + it to a :c:type:`PyLongObject`. + + If the value of *obj* is out of range for an :c:type:`unsigned long`, + return the reduction of that value modulo ``ULONG_MAX + 1``. + + Returns ``(unsigned long)-1`` on error. Use :c:func:`PyErr_Occurred` to + disambiguate. + + .. versionchanged:: 3.8 + Use :meth:`__index__` if available. + + .. deprecated:: 3.8 + Using :meth:`__int__` is deprecated. + + +.. c:function:: unsigned long long PyLong_AsUnsignedLongLongMask(PyObject *obj) + + Return a C :c:type:`unsigned long long` representation of *obj*. If *obj* + is not an instance of :c:type:`PyLongObject`, first call its + :meth:`__index__` or :meth:`__int__` method (if present) to convert + it to a :c:type:`PyLongObject`. + + If the value of *obj* is out of range for an :c:type:`unsigned long long`, + return the reduction of that value modulo ``ULLONG_MAX + 1``. + + Returns ``(unsigned long long)-1`` on error. Use :c:func:`PyErr_Occurred` + to disambiguate. + + .. versionchanged:: 3.8 + Use :meth:`__index__` if available. + + .. deprecated:: 3.8 + Using :meth:`__int__` is deprecated. + + +.. c:function:: double PyLong_AsDouble(PyObject *pylong) + + Return a C :c:type:`double` representation of *pylong*. *pylong* must be + an instance of :c:type:`PyLongObject`. + + Raise :exc:`OverflowError` if the value of *pylong* is out of range for a + :c:type:`double`. + + Returns ``-1.0`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. + + +.. c:function:: void* PyLong_AsVoidPtr(PyObject *pylong) + + Convert a Python integer *pylong* to a C :c:type:`void` pointer. + If *pylong* cannot be converted, an :exc:`OverflowError` will be raised. This + is only assured to produce a usable :c:type:`void` pointer for values created + with :c:func:`PyLong_FromVoidPtr`. + + Returns ``NULL`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. diff --git a/cpython_2/environment/repo/Doc/c-api/mapping.rst b/cpython_2/environment/repo/Doc/c-api/mapping.rst new file mode 100644 index 0000000000000000000000000000000000000000..682160d1475c1c4b9cfff1aa0b386dff9299ab9d --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/mapping.rst @@ -0,0 +1,103 @@ +.. highlight:: c + +.. _mapping: + +Mapping Protocol +================ + +See also :c:func:`PyObject_GetItem`, :c:func:`PyObject_SetItem` and +:c:func:`PyObject_DelItem`. + + +.. c:function:: int PyMapping_Check(PyObject *o) + + Return ``1`` if the object provides mapping protocol or supports slicing, + and ``0`` otherwise. Note that it returns ``1`` for Python classes with + a :meth:`__getitem__` method since in general case it is impossible to + determine what type of keys it supports. This function always succeeds. + + +.. c:function:: Py_ssize_t PyMapping_Size(PyObject *o) + Py_ssize_t PyMapping_Length(PyObject *o) + + .. index:: builtin: len + + Returns the number of keys in object *o* on success, and ``-1`` on failure. + This is equivalent to the Python expression ``len(o)``. + + +.. c:function:: PyObject* PyMapping_GetItemString(PyObject *o, const char *key) + + Return element of *o* corresponding to the string *key* or ``NULL`` on failure. + This is the equivalent of the Python expression ``o[key]``. + See also :c:func:`PyObject_GetItem`. + + +.. c:function:: int PyMapping_SetItemString(PyObject *o, const char *key, PyObject *v) + + Map the string *key* to the value *v* in object *o*. Returns ``-1`` on + failure. This is the equivalent of the Python statement ``o[key] = v``. + See also :c:func:`PyObject_SetItem`. This function *does not* steal a + reference to *v*. + + +.. c:function:: int PyMapping_DelItem(PyObject *o, PyObject *key) + + Remove the mapping for the object *key* from the object *o*. Return ``-1`` + on failure. This is equivalent to the Python statement ``del o[key]``. + This is an alias of :c:func:`PyObject_DelItem`. + + +.. c:function:: int PyMapping_DelItemString(PyObject *o, const char *key) + + Remove the mapping for the string *key* from the object *o*. Return ``-1`` + on failure. This is equivalent to the Python statement ``del o[key]``. + + +.. c:function:: int PyMapping_HasKey(PyObject *o, PyObject *key) + + Return ``1`` if the mapping object has the key *key* and ``0`` otherwise. + This is equivalent to the Python expression ``key in o``. + This function always succeeds. + + Note that exceptions which occur while calling the :meth:`__getitem__` + method will get suppressed. + To get error reporting use :c:func:`PyObject_GetItem()` instead. + + +.. c:function:: int PyMapping_HasKeyString(PyObject *o, const char *key) + + Return ``1`` if the mapping object has the key *key* and ``0`` otherwise. + This is equivalent to the Python expression ``key in o``. + This function always succeeds. + + Note that exceptions which occur while calling the :meth:`__getitem__` + method and creating a temporary string object will get suppressed. + To get error reporting use :c:func:`PyMapping_GetItemString()` instead. + + +.. c:function:: PyObject* PyMapping_Keys(PyObject *o) + + On success, return a list of the keys in object *o*. On failure, return + ``NULL``. + + .. versionchanged:: 3.7 + Previously, the function returned a list or a tuple. + + +.. c:function:: PyObject* PyMapping_Values(PyObject *o) + + On success, return a list of the values in object *o*. On failure, return + ``NULL``. + + .. versionchanged:: 3.7 + Previously, the function returned a list or a tuple. + + +.. c:function:: PyObject* PyMapping_Items(PyObject *o) + + On success, return a list of the items in object *o*, where each item is a + tuple containing a key-value pair. On failure, return ``NULL``. + + .. versionchanged:: 3.7 + Previously, the function returned a list or a tuple. diff --git a/cpython_2/environment/repo/Doc/c-api/marshal.rst b/cpython_2/environment/repo/Doc/c-api/marshal.rst new file mode 100644 index 0000000000000000000000000000000000000000..7b179e22e290e1ce727b9fe8e66aba55b1700879 --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/marshal.rst @@ -0,0 +1,94 @@ +.. highlight:: c + +.. _marshalling-utils: + +Data marshalling support +======================== + +These routines allow C code to work with serialized objects using the same +data format as the :mod:`marshal` module. There are functions to write data +into the serialization format, and additional functions that can be used to +read the data back. Files used to store marshalled data must be opened in +binary mode. + +Numeric values are stored with the least significant byte first. + +The module supports two versions of the data format: version 0 is the +historical version, version 1 shares interned strings in the file, and upon +unmarshalling. Version 2 uses a binary format for floating point numbers. +``Py_MARSHAL_VERSION`` indicates the current file format (currently 2). + + +.. c:function:: void PyMarshal_WriteLongToFile(long value, FILE *file, int version) + + Marshal a :c:type:`long` integer, *value*, to *file*. This will only write + the least-significant 32 bits of *value*; regardless of the size of the + native :c:type:`long` type. *version* indicates the file format. + + +.. c:function:: void PyMarshal_WriteObjectToFile(PyObject *value, FILE *file, int version) + + Marshal a Python object, *value*, to *file*. + *version* indicates the file format. + + +.. c:function:: PyObject* PyMarshal_WriteObjectToString(PyObject *value, int version) + + Return a bytes object containing the marshalled representation of *value*. + *version* indicates the file format. + + +The following functions allow marshalled values to be read back in. + + +.. c:function:: long PyMarshal_ReadLongFromFile(FILE *file) + + Return a C :c:type:`long` from the data stream in a :c:type:`FILE\*` opened + for reading. Only a 32-bit value can be read in using this function, + regardless of the native size of :c:type:`long`. + + On error, sets the appropriate exception (:exc:`EOFError`) and returns + ``-1``. + + +.. c:function:: int PyMarshal_ReadShortFromFile(FILE *file) + + Return a C :c:type:`short` from the data stream in a :c:type:`FILE\*` opened + for reading. Only a 16-bit value can be read in using this function, + regardless of the native size of :c:type:`short`. + + On error, sets the appropriate exception (:exc:`EOFError`) and returns + ``-1``. + + +.. c:function:: PyObject* PyMarshal_ReadObjectFromFile(FILE *file) + + Return a Python object from the data stream in a :c:type:`FILE\*` opened for + reading. + + On error, sets the appropriate exception (:exc:`EOFError`, :exc:`ValueError` + or :exc:`TypeError`) and returns ``NULL``. + + +.. c:function:: PyObject* PyMarshal_ReadLastObjectFromFile(FILE *file) + + Return a Python object from the data stream in a :c:type:`FILE\*` opened for + reading. Unlike :c:func:`PyMarshal_ReadObjectFromFile`, this function + assumes that no further objects will be read from the file, allowing it to + aggressively load file data into memory so that the de-serialization can + operate from data in memory rather than reading a byte at a time from the + file. Only use these variant if you are certain that you won't be reading + anything else from the file. + + On error, sets the appropriate exception (:exc:`EOFError`, :exc:`ValueError` + or :exc:`TypeError`) and returns ``NULL``. + + +.. c:function:: PyObject* PyMarshal_ReadObjectFromString(const char *data, Py_ssize_t len) + + Return a Python object from the data stream in a byte buffer + containing *len* bytes pointed to by *data*. + + On error, sets the appropriate exception (:exc:`EOFError`, :exc:`ValueError` + or :exc:`TypeError`) and returns ``NULL``. + diff --git a/cpython_2/environment/repo/Doc/c-api/memory.rst b/cpython_2/environment/repo/Doc/c-api/memory.rst new file mode 100644 index 0000000000000000000000000000000000000000..8a8542f0479ec595d08358f16c069ebbd7f80153 --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/memory.rst @@ -0,0 +1,604 @@ +.. highlight:: c + + +.. _memory: + +***************** +Memory Management +***************** + +.. sectionauthor:: Vladimir Marangozov + + + +.. _memoryoverview: + +Overview +======== + +Memory management in Python involves a private heap containing all Python +objects and data structures. The management of this private heap is ensured +internally by the *Python memory manager*. The Python memory manager has +different components which deal with various dynamic storage management aspects, +like sharing, segmentation, preallocation or caching. + +At the lowest level, a raw memory allocator ensures that there is enough room in +the private heap for storing all Python-related data by interacting with the +memory manager of the operating system. On top of the raw memory allocator, +several object-specific allocators operate on the same heap and implement +distinct memory management policies adapted to the peculiarities of every object +type. For example, integer objects are managed differently within the heap than +strings, tuples or dictionaries because integers imply different storage +requirements and speed/space tradeoffs. The Python memory manager thus delegates +some of the work to the object-specific allocators, but ensures that the latter +operate within the bounds of the private heap. + +It is important to understand that the management of the Python heap is +performed by the interpreter itself and that the user has no control over it, +even if they regularly manipulate object pointers to memory blocks inside that +heap. The allocation of heap space for Python objects and other internal +buffers is performed on demand by the Python memory manager through the Python/C +API functions listed in this document. + +.. index:: + single: malloc() + single: calloc() + single: realloc() + single: free() + +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:func:`calloc`, :c:func:`realloc` and :c:func:`free`. This will result in mixed +calls between the C allocator and the Python memory manager with fatal +consequences, because they implement different algorithms and operate on +different heaps. However, one may safely allocate and release memory blocks +with the C library allocator for individual purposes, as shown in the following +example:: + + 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; + +In this example, the memory request for the I/O buffer is handled by the C +library allocator. The Python memory manager is involved only in the allocation +of the bytes object returned as a result. + +In most situations, however, it is recommended to allocate memory from the +Python heap specifically because the latter is under control of the Python +memory manager. For example, this is required when the interpreter is extended +with new object types written in C. Another reason for using the Python heap is +the desire to *inform* the Python memory manager about the memory needs of the +extension module. Even when the requested memory is used exclusively for +internal, highly-specific purposes, delegating all memory requests to the Python +memory manager causes the interpreter to have a more accurate image of its +memory footprint as a whole. Consequently, under certain circumstances, the +Python memory manager may or may not trigger appropriate actions, like garbage +collection, memory compaction or other preventive procedures. Note that by using +the C library allocator as shown in the previous example, the allocated memory +for the I/O buffer escapes completely the Python memory manager. + +.. seealso:: + + The :envvar:`PYTHONMALLOC` environment variable can be used to configure + the memory allocators used by Python. + + The :envvar:`PYTHONMALLOCSTATS` environment variable can be used to print + statistics of the :ref:`pymalloc memory allocator ` every time a + new pymalloc object arena is created, and on shutdown. + + +Raw Memory Interface +==================== + +The following function sets are wrappers to the system allocator. These +functions are thread-safe, the :term:`GIL ` does not +need to be held. + +The :ref:`default raw memory allocator ` uses +the following functions: :c:func:`malloc`, :c:func:`calloc`, :c:func:`realloc` +and :c:func:`free`; call ``malloc(1)`` (or ``calloc(1, 1)``) when requesting +zero bytes. + +.. versionadded:: 3.4 + +.. c:function:: void* PyMem_RawMalloc(size_t n) + + Allocates *n* bytes and returns a pointer of type :c:type:`void\*` to the + allocated memory, or ``NULL`` if the request fails. + + Requesting zero bytes returns a distinct non-``NULL`` pointer if possible, as + if ``PyMem_RawMalloc(1)`` had been called instead. The memory will not have + been initialized in any way. + + +.. c:function:: void* PyMem_RawCalloc(size_t nelem, size_t elsize) + + Allocates *nelem* elements each whose size in bytes is *elsize* and returns + a pointer of type :c:type:`void\*` to the allocated memory, or ``NULL`` if the + request fails. The memory is initialized to zeros. + + Requesting zero elements or elements of size zero bytes returns a distinct + non-``NULL`` pointer if possible, as if ``PyMem_RawCalloc(1, 1)`` had been + called instead. + + .. versionadded:: 3.5 + + +.. c:function:: void* PyMem_RawRealloc(void *p, size_t n) + + Resizes the memory block pointed to by *p* to *n* bytes. The contents will + be unchanged to the minimum of the old and the new sizes. + + If *p* is ``NULL``, the call is equivalent to ``PyMem_RawMalloc(n)``; else if + *n* is equal to zero, the memory block is resized but is not freed, and the + returned pointer is non-``NULL``. + + Unless *p* is ``NULL``, it must have been returned by a previous call to + :c:func:`PyMem_RawMalloc`, :c:func:`PyMem_RawRealloc` or + :c:func:`PyMem_RawCalloc`. + + If the request fails, :c:func:`PyMem_RawRealloc` returns ``NULL`` and *p* + remains a valid pointer to the previous memory area. + + +.. c:function:: void PyMem_RawFree(void *p) + + Frees the memory block pointed to by *p*, which must have been returned by a + previous call to :c:func:`PyMem_RawMalloc`, :c:func:`PyMem_RawRealloc` or + :c:func:`PyMem_RawCalloc`. Otherwise, or if ``PyMem_RawFree(p)`` has been + called before, undefined behavior occurs. + + If *p* is ``NULL``, no operation is performed. + + +.. _memoryinterface: + +Memory Interface +================ + +The following function sets, modeled after the ANSI C standard, but specifying +behavior when requesting zero bytes, are available for allocating and releasing +memory from the Python heap. + +The :ref:`default memory allocator ` uses the +:ref:`pymalloc memory allocator `. + +.. warning:: + + The :term:`GIL ` must be held when using these + functions. + +.. versionchanged:: 3.6 + + The default allocator is now pymalloc instead of system :c:func:`malloc`. + +.. c:function:: void* PyMem_Malloc(size_t n) + + Allocates *n* bytes and returns a pointer of type :c:type:`void\*` to the + allocated memory, or ``NULL`` if the request fails. + + Requesting zero bytes returns a distinct non-``NULL`` pointer if possible, as + if ``PyMem_Malloc(1)`` had been called instead. The memory will not have + been initialized in any way. + + +.. c:function:: void* PyMem_Calloc(size_t nelem, size_t elsize) + + Allocates *nelem* elements each whose size in bytes is *elsize* and returns + a pointer of type :c:type:`void\*` to the allocated memory, or ``NULL`` if the + request fails. The memory is initialized to zeros. + + Requesting zero elements or elements of size zero bytes returns a distinct + non-``NULL`` pointer if possible, as if ``PyMem_Calloc(1, 1)`` had been called + instead. + + .. versionadded:: 3.5 + + +.. c:function:: void* PyMem_Realloc(void *p, size_t n) + + Resizes the memory block pointed to by *p* to *n* bytes. The contents will be + unchanged to the minimum of the old and the new sizes. + + If *p* is ``NULL``, the call is equivalent to ``PyMem_Malloc(n)``; else if *n* + is equal to zero, the memory block is resized but is not freed, and the + returned pointer is non-``NULL``. + + Unless *p* is ``NULL``, it must have been returned by a previous call to + :c:func:`PyMem_Malloc`, :c:func:`PyMem_Realloc` or :c:func:`PyMem_Calloc`. + + If the request fails, :c:func:`PyMem_Realloc` returns ``NULL`` and *p* remains + a valid pointer to the previous memory area. + + +.. c:function:: void PyMem_Free(void *p) + + Frees the memory block pointed to by *p*, which must have been returned by a + previous call to :c:func:`PyMem_Malloc`, :c:func:`PyMem_Realloc` or + :c:func:`PyMem_Calloc`. Otherwise, or if ``PyMem_Free(p)`` has been called + before, undefined behavior occurs. + + If *p* is ``NULL``, no operation is performed. + +The following type-oriented macros are provided for convenience. Note that +*TYPE* refers to any C type. + + +.. c:function:: TYPE* PyMem_New(TYPE, size_t n) + + Same as :c:func:`PyMem_Malloc`, but allocates ``(n * sizeof(TYPE))`` bytes of + memory. Returns a pointer cast to :c:type:`TYPE\*`. The memory will not have + been initialized in any way. + + +.. c:function:: TYPE* PyMem_Resize(void *p, TYPE, size_t n) + + Same as :c:func:`PyMem_Realloc`, but the memory block is resized to ``(n * + sizeof(TYPE))`` bytes. Returns a pointer cast to :c:type:`TYPE\*`. On return, + *p* will be a pointer to the new memory area, or ``NULL`` in the event of + failure. + + This is a C preprocessor macro; *p* is always reassigned. Save the original + value of *p* to avoid losing memory when handling errors. + + +.. c:function:: void PyMem_Del(void *p) + + Same as :c:func:`PyMem_Free`. + +In addition, the following macro sets are provided for calling the Python memory +allocator directly, without involving the C API functions listed above. However, +note that their use does not preserve binary compatibility across Python +versions and is therefore deprecated in extension modules. + +* ``PyMem_MALLOC(size)`` +* ``PyMem_NEW(type, size)`` +* ``PyMem_REALLOC(ptr, size)`` +* ``PyMem_RESIZE(ptr, type, size)`` +* ``PyMem_FREE(ptr)`` +* ``PyMem_DEL(ptr)`` + + +Object allocators +================= + +The following function sets, modeled after the ANSI C standard, but specifying +behavior when requesting zero bytes, are available for allocating and releasing +memory from the Python heap. + +The :ref:`default object allocator ` uses the +:ref:`pymalloc memory allocator `. + +.. warning:: + + The :term:`GIL ` must be held when using these + functions. + +.. c:function:: void* PyObject_Malloc(size_t n) + + Allocates *n* bytes and returns a pointer of type :c:type:`void\*` to the + allocated memory, or ``NULL`` if the request fails. + + Requesting zero bytes returns a distinct non-``NULL`` pointer if possible, as + if ``PyObject_Malloc(1)`` had been called instead. The memory will not have + been initialized in any way. + + +.. c:function:: void* PyObject_Calloc(size_t nelem, size_t elsize) + + Allocates *nelem* elements each whose size in bytes is *elsize* and returns + a pointer of type :c:type:`void\*` to the allocated memory, or ``NULL`` if the + request fails. The memory is initialized to zeros. + + Requesting zero elements or elements of size zero bytes returns a distinct + non-``NULL`` pointer if possible, as if ``PyObject_Calloc(1, 1)`` had been called + instead. + + .. versionadded:: 3.5 + + +.. c:function:: void* PyObject_Realloc(void *p, size_t n) + + Resizes the memory block pointed to by *p* to *n* bytes. The contents will be + unchanged to the minimum of the old and the new sizes. + + If *p* is ``NULL``, the call is equivalent to ``PyObject_Malloc(n)``; else if *n* + is equal to zero, the memory block is resized but is not freed, and the + returned pointer is non-``NULL``. + + Unless *p* is ``NULL``, it must have been returned by a previous call to + :c:func:`PyObject_Malloc`, :c:func:`PyObject_Realloc` or :c:func:`PyObject_Calloc`. + + If the request fails, :c:func:`PyObject_Realloc` returns ``NULL`` and *p* remains + a valid pointer to the previous memory area. + + +.. c:function:: void PyObject_Free(void *p) + + Frees the memory block pointed to by *p*, which must have been returned by a + previous call to :c:func:`PyObject_Malloc`, :c:func:`PyObject_Realloc` or + :c:func:`PyObject_Calloc`. Otherwise, or if ``PyObject_Free(p)`` has been called + before, undefined behavior occurs. + + If *p* is ``NULL``, no operation is performed. + + +.. _default-memory-allocators: + +Default Memory Allocators +========================= + +Default memory allocators: + +=============================== ==================== ================== ===================== ==================== +Configuration Name PyMem_RawMalloc PyMem_Malloc PyObject_Malloc +=============================== ==================== ================== ===================== ==================== +Release build ``"pymalloc"`` ``malloc`` ``pymalloc`` ``pymalloc`` +Debug build ``"pymalloc_debug"`` ``malloc`` + debug ``pymalloc`` + debug ``pymalloc`` + debug +Release build, without pymalloc ``"malloc"`` ``malloc`` ``malloc`` ``malloc`` +Debug build, without pymalloc ``"malloc_debug"`` ``malloc`` + debug ``malloc`` + debug ``malloc`` + debug +=============================== ==================== ================== ===================== ==================== + +Legend: + +* Name: value for :envvar:`PYTHONMALLOC` environment variable +* ``malloc``: system allocators from the standard C library, C functions: + :c:func:`malloc`, :c:func:`calloc`, :c:func:`realloc` and :c:func:`free` +* ``pymalloc``: :ref:`pymalloc memory allocator ` +* "+ debug": with debug hooks installed by :c:func:`PyMem_SetupDebugHooks` + + +Customize Memory Allocators +=========================== + +.. versionadded:: 3.4 + +.. c:type:: PyMemAllocatorEx + + Structure used to describe a memory block allocator. The structure has + four fields: + + +----------------------------------------------------------+---------------------------------------+ + | Field | Meaning | + +==========================================================+=======================================+ + | ``void *ctx`` | user context passed as first argument | + +----------------------------------------------------------+---------------------------------------+ + | ``void* malloc(void *ctx, size_t size)`` | allocate a memory block | + +----------------------------------------------------------+---------------------------------------+ + | ``void* calloc(void *ctx, size_t nelem, size_t elsize)`` | allocate a memory block initialized | + | | with zeros | + +----------------------------------------------------------+---------------------------------------+ + | ``void* realloc(void *ctx, void *ptr, size_t new_size)`` | allocate or resize a memory block | + +----------------------------------------------------------+---------------------------------------+ + | ``void free(void *ctx, void *ptr)`` | free a memory block | + +----------------------------------------------------------+---------------------------------------+ + + .. versionchanged:: 3.5 + The :c:type:`PyMemAllocator` structure was renamed to + :c:type:`PyMemAllocatorEx` and a new ``calloc`` field was added. + + +.. c:type:: PyMemAllocatorDomain + + Enum used to identify an allocator domain. Domains: + + .. c:var:: PYMEM_DOMAIN_RAW + + Functions: + + * :c:func:`PyMem_RawMalloc` + * :c:func:`PyMem_RawRealloc` + * :c:func:`PyMem_RawCalloc` + * :c:func:`PyMem_RawFree` + + .. c:var:: PYMEM_DOMAIN_MEM + + Functions: + + * :c:func:`PyMem_Malloc`, + * :c:func:`PyMem_Realloc` + * :c:func:`PyMem_Calloc` + * :c:func:`PyMem_Free` + + .. c:var:: PYMEM_DOMAIN_OBJ + + Functions: + + * :c:func:`PyObject_Malloc` + * :c:func:`PyObject_Realloc` + * :c:func:`PyObject_Calloc` + * :c:func:`PyObject_Free` + +.. c:function:: void PyMem_GetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator) + + Get the memory block allocator of the specified domain. + + +.. c:function:: void PyMem_SetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator) + + Set the memory block allocator of the specified domain. + + The new allocator must return a distinct non-``NULL`` pointer when requesting + zero bytes. + + For the :c:data:`PYMEM_DOMAIN_RAW` domain, the allocator must be + thread-safe: the :term:`GIL ` is not held when the + allocator is called. + + If the new allocator is not a hook (does not call the previous allocator), + the :c:func:`PyMem_SetupDebugHooks` function must be called to reinstall the + debug hooks on top on the new allocator. + + +.. c:function:: void PyMem_SetupDebugHooks(void) + + Setup hooks to detect bugs in the Python memory allocator functions. + + Newly allocated memory is filled with the byte ``0xCD`` (``CLEANBYTE``), + freed memory is filled with the byte ``0xDD`` (``DEADBYTE``). Memory blocks + are surrounded by "forbidden bytes" (``FORBIDDENBYTE``: byte ``0xFD``). + + Runtime checks: + + - Detect API violations, ex: :c:func:`PyObject_Free` called on a buffer + allocated by :c:func:`PyMem_Malloc` + - Detect write before the start of the buffer (buffer underflow) + - Detect write after the end of the buffer (buffer overflow) + - Check that the :term:`GIL ` is held when + allocator functions of :c:data:`PYMEM_DOMAIN_OBJ` (ex: + :c:func:`PyObject_Malloc`) and :c:data:`PYMEM_DOMAIN_MEM` (ex: + :c:func:`PyMem_Malloc`) domains are called + + On error, the debug hooks use the :mod:`tracemalloc` module to get the + traceback where a memory block was allocated. The traceback is only + displayed if :mod:`tracemalloc` is tracing Python memory allocations and the + memory block was traced. + + These hooks are :ref:`installed by default ` if + Python is compiled in debug + mode. The :envvar:`PYTHONMALLOC` environment variable can be used to install + debug hooks on a Python compiled in release mode. + + .. versionchanged:: 3.6 + This function now also works on Python compiled in release mode. + On error, the debug hooks now use :mod:`tracemalloc` to get the traceback + where a memory block was allocated. The debug hooks now also check + if the GIL is held when functions of :c:data:`PYMEM_DOMAIN_OBJ` and + :c:data:`PYMEM_DOMAIN_MEM` domains are called. + + .. versionchanged:: 3.8 + Byte patterns ``0xCB`` (``CLEANBYTE``), ``0xDB`` (``DEADBYTE``) and + ``0xFB`` (``FORBIDDENBYTE``) have been replaced with ``0xCD``, ``0xDD`` + and ``0xFD`` to use the same values than Windows CRT debug ``malloc()`` + and ``free()``. + + +.. _pymalloc: + +The pymalloc allocator +====================== + +Python has a *pymalloc* allocator optimized for small objects (smaller or equal +to 512 bytes) with a short lifetime. It uses memory mappings called "arenas" +with a fixed size of 256 KiB. It falls back to :c:func:`PyMem_RawMalloc` and +:c:func:`PyMem_RawRealloc` for allocations larger than 512 bytes. + +*pymalloc* is the :ref:`default allocator ` of the +:c:data:`PYMEM_DOMAIN_MEM` (ex: :c:func:`PyMem_Malloc`) and +:c:data:`PYMEM_DOMAIN_OBJ` (ex: :c:func:`PyObject_Malloc`) domains. + +The arena allocator uses the following functions: + +* :c:func:`VirtualAlloc` and :c:func:`VirtualFree` on Windows, +* :c:func:`mmap` and :c:func:`munmap` if available, +* :c:func:`malloc` and :c:func:`free` otherwise. + +Customize pymalloc Arena Allocator +---------------------------------- + +.. versionadded:: 3.4 + +.. c:type:: PyObjectArenaAllocator + + Structure used to describe an arena allocator. The structure has + three fields: + + +--------------------------------------------------+---------------------------------------+ + | Field | Meaning | + +==================================================+=======================================+ + | ``void *ctx`` | user context passed as first argument | + +--------------------------------------------------+---------------------------------------+ + | ``void* alloc(void *ctx, size_t size)`` | allocate an arena of size bytes | + +--------------------------------------------------+---------------------------------------+ + | ``void free(void *ctx, size_t size, void *ptr)`` | free an arena | + +--------------------------------------------------+---------------------------------------+ + +.. c:function:: PyObject_GetArenaAllocator(PyObjectArenaAllocator *allocator) + + Get the arena allocator. + +.. c:function:: PyObject_SetArenaAllocator(PyObjectArenaAllocator *allocator) + + Set the arena allocator. + + +tracemalloc C API +================= + +.. versionadded:: 3.7 + +.. c:function:: int PyTraceMalloc_Track(unsigned int domain, uintptr_t ptr, size_t size) + + Track an allocated memory block in the :mod:`tracemalloc` module. + + Return ``0`` on success, return ``-1`` on error (failed to allocate memory to + store the trace). Return ``-2`` if tracemalloc is disabled. + + If memory block is already tracked, update the existing trace. + +.. c:function:: int PyTraceMalloc_Untrack(unsigned int domain, uintptr_t ptr) + + Untrack an allocated memory block in the :mod:`tracemalloc` module. + Do nothing if the block was not tracked. + + Return ``-2`` if tracemalloc is disabled, otherwise return ``0``. + + +.. _memoryexamples: + +Examples +======== + +Here is the example from section :ref:`memoryoverview`, rewritten so that the +I/O buffer is allocated from the Python heap by using the first function set:: + + 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; + +The same code using the type-oriented function set:: + + 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; + +Note that in the two examples above, the buffer is always manipulated via +functions belonging to the same set. Indeed, it is required to use the same +memory API family for a given memory block, so that the risk of mixing different +allocators is reduced to a minimum. The following code sequence contains two +errors, one of which is labeled as *fatal* because it mixes two different +allocators operating on different heaps. :: + + 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() */ + +In addition to the functions aimed at handling raw memory blocks from the Python +heap, objects in Python are allocated and released with :c:func:`PyObject_New`, +:c:func:`PyObject_NewVar` and :c:func:`PyObject_Del`. + +These will be explained in the next chapter on defining and implementing new +object types in C. + diff --git a/cpython_2/environment/repo/Doc/c-api/memoryview.rst b/cpython_2/environment/repo/Doc/c-api/memoryview.rst new file mode 100644 index 0000000000000000000000000000000000000000..de429e5c11dc76252061da135e97ef3122f44e72 --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/memoryview.rst @@ -0,0 +1,63 @@ +.. highlight:: c + +.. _memoryview-objects: + +.. index:: + object: memoryview + +MemoryView objects +------------------ + +A :class:`memoryview` object exposes the C level :ref:`buffer interface +` as a Python object which can then be passed around like +any other object. + + +.. c:function:: PyObject *PyMemoryView_FromObject(PyObject *obj) + + Create a memoryview object from an object that provides the buffer interface. + If *obj* supports writable buffer exports, the memoryview object will be + read/write, otherwise it may be either read-only or read/write at the + discretion of the exporter. + +.. c:function:: PyObject *PyMemoryView_FromMemory(char *mem, Py_ssize_t size, int flags) + + Create a memoryview object using *mem* as the underlying buffer. + *flags* can be one of :c:macro:`PyBUF_READ` or :c:macro:`PyBUF_WRITE`. + + .. versionadded:: 3.3 + +.. c:function:: PyObject *PyMemoryView_FromBuffer(Py_buffer *view) + + Create a memoryview object wrapping the given buffer structure *view*. + For simple byte buffers, :c:func:`PyMemoryView_FromMemory` is the preferred + function. + +.. c:function:: PyObject *PyMemoryView_GetContiguous(PyObject *obj, int buffertype, char order) + + Create a memoryview object to a :term:`contiguous` chunk of memory (in either + 'C' or 'F'ortran *order*) from an object that defines the buffer + interface. If memory is contiguous, the memoryview object points to the + original memory. Otherwise, a copy is made and the memoryview points to a + new bytes object. + + +.. c:function:: int PyMemoryView_Check(PyObject *obj) + + Return true if the object *obj* is a memoryview object. It is not + currently allowed to create subclasses of :class:`memoryview`. + + +.. c:function:: Py_buffer *PyMemoryView_GET_BUFFER(PyObject *mview) + + Return a pointer to the memoryview's private copy of the exporter's buffer. + *mview* **must** be a memoryview instance; this macro doesn't check its type, + you must do it yourself or you will risk crashes. + +.. c:function:: Py_buffer *PyMemoryView_GET_BASE(PyObject *mview) + + Return either a pointer to the exporting object that the memoryview is based + on or ``NULL`` if the memoryview has been created by one of the functions + :c:func:`PyMemoryView_FromMemory` or :c:func:`PyMemoryView_FromBuffer`. + *mview* **must** be a memoryview instance. + diff --git a/cpython_2/environment/repo/Doc/c-api/method.rst b/cpython_2/environment/repo/Doc/c-api/method.rst new file mode 100644 index 0000000000000000000000000000000000000000..0a5341cbbdf15293c83d57b5b0219a853fed12a7 --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/method.rst @@ -0,0 +1,94 @@ +.. highlight:: c + +.. _instancemethod-objects: + +Instance Method Objects +----------------------- + +.. index:: object: instancemethod + +An instance method is a wrapper for a :c:data:`PyCFunction` and the new way +to bind a :c:data:`PyCFunction` to a class object. It replaces the former call +``PyMethod_New(func, NULL, class)``. + + +.. c:var:: PyTypeObject PyInstanceMethod_Type + + This instance of :c:type:`PyTypeObject` represents the Python instance + method type. It is not exposed to Python programs. + + +.. c:function:: int PyInstanceMethod_Check(PyObject *o) + + Return true if *o* is an instance method object (has type + :c:data:`PyInstanceMethod_Type`). The parameter must not be ``NULL``. + + +.. c:function:: PyObject* PyInstanceMethod_New(PyObject *func) + + Return a new instance method object, with *func* being any callable object + *func* is the function that will be called when the instance method is + called. + + +.. c:function:: PyObject* PyInstanceMethod_Function(PyObject *im) + + Return the function object associated with the instance method *im*. + + +.. c:function:: PyObject* PyInstanceMethod_GET_FUNCTION(PyObject *im) + + Macro version of :c:func:`PyInstanceMethod_Function` which avoids error checking. + + +.. _method-objects: + +Method Objects +-------------- + +.. index:: object: method + +Methods are bound function objects. Methods are always bound to an instance of +a user-defined class. Unbound methods (methods bound to a class object) are +no longer available. + + +.. c:var:: PyTypeObject PyMethod_Type + + .. index:: single: MethodType (in module types) + + This instance of :c:type:`PyTypeObject` represents the Python method type. This + is exposed to Python programs as ``types.MethodType``. + + +.. c:function:: int PyMethod_Check(PyObject *o) + + Return true if *o* is a method object (has type :c:data:`PyMethod_Type`). The + parameter must not be ``NULL``. + + +.. c:function:: PyObject* PyMethod_New(PyObject *func, PyObject *self) + + Return a new method object, with *func* being any callable object and *self* + the instance the method should be bound. *func* is the function that will + be called when the method is called. *self* must not be ``NULL``. + + +.. c:function:: PyObject* PyMethod_Function(PyObject *meth) + + Return the function object associated with the method *meth*. + + +.. c:function:: PyObject* PyMethod_GET_FUNCTION(PyObject *meth) + + Macro version of :c:func:`PyMethod_Function` which avoids error checking. + + +.. c:function:: PyObject* PyMethod_Self(PyObject *meth) + + Return the instance associated with the method *meth*. + + +.. c:function:: PyObject* PyMethod_GET_SELF(PyObject *meth) + + Macro version of :c:func:`PyMethod_Self` which avoids error checking. diff --git a/cpython_2/environment/repo/Doc/c-api/module.rst b/cpython_2/environment/repo/Doc/c-api/module.rst new file mode 100644 index 0000000000000000000000000000000000000000..8a415dfa30a35e05b548cc8ba208d1ef0ca2901f --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/module.rst @@ -0,0 +1,543 @@ +.. highlight:: c + +.. _moduleobjects: + +Module Objects +-------------- + +.. index:: object: module + + +.. c:var:: PyTypeObject PyModule_Type + + .. index:: single: ModuleType (in module types) + + This instance of :c:type:`PyTypeObject` represents the Python module type. This + is exposed to Python programs as ``types.ModuleType``. + + +.. c:function:: int PyModule_Check(PyObject *p) + + Return true if *p* is a module object, or a subtype of a module object. + + +.. c:function:: int PyModule_CheckExact(PyObject *p) + + Return true if *p* is a module object, but not a subtype of + :c:data:`PyModule_Type`. + + +.. c:function:: PyObject* PyModule_NewObject(PyObject *name) + + .. index:: + single: __name__ (module attribute) + single: __doc__ (module attribute) + single: __file__ (module attribute) + single: __package__ (module attribute) + single: __loader__ (module attribute) + + Return a new module object with the :attr:`__name__` attribute set to *name*. + The module's :attr:`__name__`, :attr:`__doc__`, :attr:`__package__`, and + :attr:`__loader__` attributes are filled in (all but :attr:`__name__` are set + to ``None``); the caller is responsible for providing a :attr:`__file__` + attribute. + + .. versionadded:: 3.3 + + .. versionchanged:: 3.4 + :attr:`__package__` and :attr:`__loader__` are set to ``None``. + + +.. c:function:: PyObject* PyModule_New(const char *name) + + Similar to :c:func:`PyModule_NewObject`, but the name is a UTF-8 encoded + string instead of a Unicode object. + + +.. c:function:: PyObject* PyModule_GetDict(PyObject *module) + + .. index:: single: __dict__ (module attribute) + + Return the dictionary object that implements *module*'s namespace; this object + is the same as the :attr:`~object.__dict__` attribute of the module object. + If *module* is not a module object (or a subtype of a module object), + :exc:`SystemError` is raised and ``NULL`` is returned. + + It is recommended extensions use other :c:func:`PyModule_\*` and + :c:func:`PyObject_\*` functions rather than directly manipulate a module's + :attr:`~object.__dict__`. + + +.. c:function:: PyObject* PyModule_GetNameObject(PyObject *module) + + .. index:: + single: __name__ (module attribute) + single: SystemError (built-in exception) + + Return *module*'s :attr:`__name__` value. If the module does not provide one, + or if it is not a string, :exc:`SystemError` is raised and ``NULL`` is returned. + + .. versionadded:: 3.3 + + +.. c:function:: const char* PyModule_GetName(PyObject *module) + + Similar to :c:func:`PyModule_GetNameObject` but return the name encoded to + ``'utf-8'``. + +.. c:function:: void* PyModule_GetState(PyObject *module) + + Return the "state" of the module, that is, a pointer to the block of memory + allocated at module creation time, or ``NULL``. See + :c:member:`PyModuleDef.m_size`. + + +.. c:function:: PyModuleDef* PyModule_GetDef(PyObject *module) + + Return a pointer to the :c:type:`PyModuleDef` struct from which the module was + created, or ``NULL`` if the module wasn't created from a definition. + + +.. c:function:: PyObject* PyModule_GetFilenameObject(PyObject *module) + + .. index:: + single: __file__ (module attribute) + single: SystemError (built-in exception) + + Return the name of the file from which *module* was loaded using *module*'s + :attr:`__file__` attribute. If this is not defined, or if it is not a + unicode string, raise :exc:`SystemError` and return ``NULL``; otherwise return + a reference to a Unicode object. + + .. versionadded:: 3.2 + + +.. c:function:: const char* PyModule_GetFilename(PyObject *module) + + Similar to :c:func:`PyModule_GetFilenameObject` but return the filename + encoded to 'utf-8'. + + .. deprecated:: 3.2 + :c:func:`PyModule_GetFilename` raises :c:type:`UnicodeEncodeError` on + unencodable filenames, use :c:func:`PyModule_GetFilenameObject` instead. + + +.. _initializing-modules: + +Initializing C modules +^^^^^^^^^^^^^^^^^^^^^^ + +Modules objects are usually created from extension modules (shared libraries +which export an initialization function), or compiled-in modules +(where the initialization function is added using :c:func:`PyImport_AppendInittab`). +See :ref:`building` or :ref:`extending-with-embedding` for details. + +The initialization function can either pass a module definition instance +to :c:func:`PyModule_Create`, and return the resulting module object, +or request "multi-phase initialization" by returning the definition struct itself. + +.. c:type:: PyModuleDef + + The module definition struct, which holds all information needed to create + a module object. There is usually only one statically initialized variable + of this type for each module. + + .. c:member:: PyModuleDef_Base m_base + + Always initialize this member to :const:`PyModuleDef_HEAD_INIT`. + + .. c:member:: const char *m_name + + Name for the new module. + + .. c:member:: const char *m_doc + + Docstring for the module; usually a docstring variable created with + :c:macro:`PyDoc_STRVAR` is used. + + .. c:member:: Py_ssize_t m_size + + Module state may be kept in a per-module memory area that can be + retrieved with :c:func:`PyModule_GetState`, rather than in static globals. + This makes modules safe for use in multiple sub-interpreters. + + This memory area is allocated based on *m_size* on module creation, + and freed when the module object is deallocated, after the + :c:member:`m_free` function has been called, if present. + + Setting ``m_size`` to ``-1`` means that the module does not support + sub-interpreters, because it has global state. + + Setting it to a non-negative value means that the module can be + re-initialized and specifies the additional amount of memory it requires + for its state. Non-negative ``m_size`` is required for multi-phase + initialization. + + See :PEP:`3121` for more details. + + .. c:member:: PyMethodDef* m_methods + + A pointer to a table of module-level functions, described by + :c:type:`PyMethodDef` values. Can be ``NULL`` if no functions are present. + + .. c:member:: PyModuleDef_Slot* m_slots + + An array of slot definitions for multi-phase initialization, terminated by + a ``{0, NULL}`` entry. + When using single-phase initialization, *m_slots* must be ``NULL``. + + .. versionchanged:: 3.5 + + Prior to version 3.5, this member was always set to ``NULL``, + and was defined as: + + .. c:member:: inquiry m_reload + + .. c:member:: traverseproc m_traverse + + A traversal function to call during GC traversal of the module object, or + ``NULL`` if not needed. + + This function is not called if the module state was requested but is not + allocated yet. This is the case immediately after the module is created + and before the module is executed (:c:data:`Py_mod_exec` function). More + precisely, this function is not called if :c:member:`m_size` is greater + than 0 and the module state (as returned by :c:func:`PyModule_GetState`) + is ``NULL``. + + .. versionchanged:: 3.9 + No longer called before the module state is allocated. + + .. c:member:: inquiry m_clear + + A clear function to call during GC clearing of the module object, or + ``NULL`` if not needed. + + This function is not called if the module state was requested but is not + allocated yet. This is the case immediately after the module is created + and before the module is executed (:c:data:`Py_mod_exec` function). More + precisely, this function is not called if :c:member:`m_size` is greater + than 0 and the module state (as returned by :c:func:`PyModule_GetState`) + is ``NULL``. + + .. versionchanged:: 3.9 + No longer called before the module state is allocated. + + .. c:member:: freefunc m_free + + A function to call during deallocation of the module object, or ``NULL`` + if not needed. + + This function is not called if the module state was requested but is not + allocated yet. This is the case immediately after the module is created + and before the module is executed (:c:data:`Py_mod_exec` function). More + precisely, this function is not called if :c:member:`m_size` is greater + than 0 and the module state (as returned by :c:func:`PyModule_GetState`) + is ``NULL``. + + .. versionchanged:: 3.9 + No longer called before the module state is allocated. + +Single-phase initialization +........................... + +The module initialization function may create and return the module object +directly. This is referred to as "single-phase initialization", and uses one +of the following two module creation functions: + +.. c:function:: PyObject* PyModule_Create(PyModuleDef *def) + + Create a new module object, given the definition in *def*. This behaves + like :c:func:`PyModule_Create2` with *module_api_version* set to + :const:`PYTHON_API_VERSION`. + + +.. c:function:: PyObject* PyModule_Create2(PyModuleDef *def, int module_api_version) + + Create a new module object, given the definition in *def*, assuming the + API version *module_api_version*. If that version does not match the version + of the running interpreter, a :exc:`RuntimeWarning` is emitted. + + .. note:: + + Most uses of this function should be using :c:func:`PyModule_Create` + instead; only use this if you are sure you need it. + +Before it is returned from in the initialization function, the resulting module +object is typically populated using functions like :c:func:`PyModule_AddObject`. + +.. _multi-phase-initialization: + +Multi-phase initialization +.......................... + +An alternate way to specify extensions is to request "multi-phase initialization". +Extension modules created this way behave more like Python modules: the +initialization is split between the *creation phase*, when the module object +is created, and the *execution phase*, when it is populated. +The distinction is similar to the :py:meth:`__new__` and :py:meth:`__init__` methods +of classes. + +Unlike modules created using single-phase initialization, these modules are not +singletons: if the *sys.modules* entry is removed and the module is re-imported, +a new module object is created, and the old module is subject to normal garbage +collection -- as with Python modules. +By default, multiple modules created from the same definition should be +independent: changes to one should not affect the others. +This means that all state should be specific to the module object (using e.g. +using :c:func:`PyModule_GetState`), or its contents (such as the module's +:attr:`__dict__` or individual classes created with :c:func:`PyType_FromSpec`). + +All modules created using multi-phase initialization are expected to support +:ref:`sub-interpreters `. Making sure multiple modules +are independent is typically enough to achieve this. + +To request multi-phase initialization, the initialization function +(PyInit_modulename) returns a :c:type:`PyModuleDef` instance with non-empty +:c:member:`~PyModuleDef.m_slots`. Before it is returned, the ``PyModuleDef`` +instance must be initialized with the following function: + +.. c:function:: PyObject* PyModuleDef_Init(PyModuleDef *def) + + Ensures a module definition is a properly initialized Python object that + correctly reports its type and reference count. + + Returns *def* cast to ``PyObject*``, or ``NULL`` if an error occurred. + + .. versionadded:: 3.5 + +The *m_slots* member of the module definition must point to an array of +``PyModuleDef_Slot`` structures: + +.. c:type:: PyModuleDef_Slot + + .. c:member:: int slot + + A slot ID, chosen from the available values explained below. + + .. c:member:: void* value + + Value of the slot, whose meaning depends on the slot ID. + + .. versionadded:: 3.5 + +The *m_slots* array must be terminated by a slot with id 0. + +The available slot types are: + +.. c:var:: Py_mod_create + + Specifies a function that is called to create the module object itself. + The *value* pointer of this slot must point to a function of the signature: + + .. c:function:: PyObject* create_module(PyObject *spec, PyModuleDef *def) + + The function receives a :py:class:`~importlib.machinery.ModuleSpec` + instance, as defined in :PEP:`451`, and the module definition. + It should return a new module object, or set an error + and return ``NULL``. + + This function should be kept minimal. In particular, it should not + call arbitrary Python code, as trying to import the same module again may + result in an infinite loop. + + Multiple ``Py_mod_create`` slots may not be specified in one module + definition. + + If ``Py_mod_create`` is not specified, the import machinery will create + a normal module object using :c:func:`PyModule_New`. The name is taken from + *spec*, not the definition, to allow extension modules to dynamically adjust + to their place in the module hierarchy and be imported under different + names through symlinks, all while sharing a single module definition. + + There is no requirement for the returned object to be an instance of + :c:type:`PyModule_Type`. Any type can be used, as long as it supports + setting and getting import-related attributes. + However, only ``PyModule_Type`` instances may be returned if the + ``PyModuleDef`` has non-``NULL`` ``m_traverse``, ``m_clear``, + ``m_free``; non-zero ``m_size``; or slots other than ``Py_mod_create``. + +.. c:var:: Py_mod_exec + + Specifies a function that is called to *execute* the module. + This is equivalent to executing the code of a Python module: typically, + this function adds classes and constants to the module. + The signature of the function is: + + .. c:function:: int exec_module(PyObject* module) + + If multiple ``Py_mod_exec`` slots are specified, they are processed in the + order they appear in the *m_slots* array. + +See :PEP:`489` for more details on multi-phase initialization. + +Low-level module creation functions +................................... + +The following functions are called under the hood when using multi-phase +initialization. They can be used directly, for example when creating module +objects dynamically. Note that both ``PyModule_FromDefAndSpec`` and +``PyModule_ExecDef`` must be called to fully initialize a module. + +.. c:function:: PyObject * PyModule_FromDefAndSpec(PyModuleDef *def, PyObject *spec) + + Create a new module object, given the definition in *module* and the + ModuleSpec *spec*. This behaves like :c:func:`PyModule_FromDefAndSpec2` + with *module_api_version* set to :const:`PYTHON_API_VERSION`. + + .. versionadded:: 3.5 + +.. c:function:: PyObject * PyModule_FromDefAndSpec2(PyModuleDef *def, PyObject *spec, int module_api_version) + + Create a new module object, given the definition in *module* and the + ModuleSpec *spec*, assuming the API version *module_api_version*. + If that version does not match the version of the running interpreter, + a :exc:`RuntimeWarning` is emitted. + + .. note:: + + Most uses of this function should be using :c:func:`PyModule_FromDefAndSpec` + instead; only use this if you are sure you need it. + + .. versionadded:: 3.5 + +.. c:function:: int PyModule_ExecDef(PyObject *module, PyModuleDef *def) + + Process any execution slots (:c:data:`Py_mod_exec`) given in *def*. + + .. versionadded:: 3.5 + +.. c:function:: int PyModule_SetDocString(PyObject *module, const char *docstring) + + Set the docstring for *module* to *docstring*. + This function is called automatically when creating a module from + ``PyModuleDef``, using either ``PyModule_Create`` or + ``PyModule_FromDefAndSpec``. + + .. versionadded:: 3.5 + +.. c:function:: int PyModule_AddFunctions(PyObject *module, PyMethodDef *functions) + + Add the functions from the ``NULL`` terminated *functions* array to *module*. + Refer to the :c:type:`PyMethodDef` documentation for details on individual + entries (due to the lack of a shared module namespace, module level + "functions" implemented in C typically receive the module as their first + parameter, making them similar to instance methods on Python classes). + This function is called automatically when creating a module from + ``PyModuleDef``, using either ``PyModule_Create`` or + ``PyModule_FromDefAndSpec``. + + .. versionadded:: 3.5 + +Support functions +................. + +The module initialization function (if using single phase initialization) or +a function called from a module execution slot (if using multi-phase +initialization), can use the following functions to help initialize the module +state: + +.. c:function:: int PyModule_AddObject(PyObject *module, const char *name, PyObject *value) + + Add an object to *module* as *name*. This is a convenience function which can + be used from the module's initialization function. This steals a reference to + *value* on success. Return ``-1`` on error, ``0`` on success. + + .. note:: + + Unlike other functions that steal references, ``PyModule_AddObject()`` only + decrements the reference count of *value* **on success**. + + This means that its return value must be checked, and calling code must + :c:func:`Py_DECREF` *value* manually on error. Example usage:: + + Py_INCREF(spam); + if (PyModule_AddObject(module, "spam", spam) < 0) { + Py_DECREF(module); + Py_DECREF(spam); + return NULL; + } + +.. c:function:: int PyModule_AddIntConstant(PyObject *module, const char *name, long value) + + Add an integer constant to *module* as *name*. This convenience function can be + used from the module's initialization function. Return ``-1`` on error, ``0`` on + success. + + +.. c:function:: int PyModule_AddStringConstant(PyObject *module, const char *name, const char *value) + + Add a string constant to *module* as *name*. This convenience function can be + used from the module's initialization function. The string *value* must be + ``NULL``-terminated. Return ``-1`` on error, ``0`` on success. + + +.. c:function:: int PyModule_AddIntMacro(PyObject *module, macro) + + Add an int constant to *module*. The name and the value are taken from + *macro*. For example ``PyModule_AddIntMacro(module, AF_INET)`` adds the int + constant *AF_INET* with the value of *AF_INET* to *module*. + Return ``-1`` on error, ``0`` on success. + + +.. c:function:: int PyModule_AddStringMacro(PyObject *module, macro) + + Add a string constant to *module*. + +.. c:function:: int PyModule_AddType(PyObject *module, PyTypeObject *type) + + Add a type object to *module*. + The type object is finalized by calling internally :c:func:`PyType_Ready`. + The name of the type object is taken from the last component of + :c:member:`~PyTypeObject.tp_name` after dot. + Return ``-1`` on error, ``0`` on success. + + .. versionadded:: 3.9 + + +Module lookup +^^^^^^^^^^^^^ + +Single-phase initialization creates singleton modules that can be looked up +in the context of the current interpreter. This allows the module object to be +retrieved later with only a reference to the module definition. + +These functions will not work on modules created using multi-phase initialization, +since multiple such modules can be created from a single definition. + +.. c:function:: PyObject* PyState_FindModule(PyModuleDef *def) + + Returns the module object that was created from *def* for the current interpreter. + This method requires that the module object has been attached to the interpreter state with + :c:func:`PyState_AddModule` beforehand. In case the corresponding module object is not + found or has not been attached to the interpreter state yet, it returns ``NULL``. + +.. c:function:: int PyState_AddModule(PyObject *module, PyModuleDef *def) + + Attaches the module object passed to the function to the interpreter state. This allows + the module object to be accessible via :c:func:`PyState_FindModule`. + + Only effective on modules created using single-phase initialization. + + Python calls ``PyState_AddModule`` automatically after importing a module, + so it is unnecessary (but harmless) to call it from module initialization + code. An explicit call is needed only if the module's own init code + subsequently calls ``PyState_FindModule``. + The function is mainly intended for implementing alternative import + mechanisms (either by calling it directly, or by referring to its + implementation for details of the required state updates). + + The caller must hold the GIL. + + Return 0 on success or -1 on failure. + + .. versionadded:: 3.3 + +.. c:function:: int PyState_RemoveModule(PyModuleDef *def) + + Removes the module object created from *def* from the interpreter state. + Return 0 on success or -1 on failure. + + The caller must hold the GIL. + + .. versionadded:: 3.3 diff --git a/cpython_2/environment/repo/Doc/c-api/none.rst b/cpython_2/environment/repo/Doc/c-api/none.rst new file mode 100644 index 0000000000000000000000000000000000000000..26d2b7aab201baf61c0a85a000b817130d009764 --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/none.rst @@ -0,0 +1,26 @@ +.. highlight:: c + +.. _noneobject: + +The ``None`` Object +------------------- + +.. index:: object: None + +Note that the :c:type:`PyTypeObject` for ``None`` is not directly exposed in the +Python/C API. Since ``None`` is a singleton, testing for object identity (using +``==`` in C) is sufficient. There is no :c:func:`PyNone_Check` function for the +same reason. + + +.. c:var:: PyObject* Py_None + + The Python ``None`` object, denoting lack of value. This object has no methods. + It needs to be treated just like any other object with respect to reference + counts. + + +.. c:macro:: Py_RETURN_NONE + + Properly handle returning :c:data:`Py_None` from within a C function (that is, + increment the reference count of ``None`` and return it.) diff --git a/cpython_2/environment/repo/Doc/c-api/number.rst b/cpython_2/environment/repo/Doc/c-api/number.rst new file mode 100644 index 0000000000000000000000000000000000000000..620204ca8e2295ec7f7cc4f4252fa67afc01aa73 --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/number.rst @@ -0,0 +1,286 @@ +.. highlight:: c + +.. _number: + +Number Protocol +=============== + + +.. c:function:: int PyNumber_Check(PyObject *o) + + Returns ``1`` if the object *o* provides numeric protocols, and false otherwise. + This function always succeeds. + + .. versionchanged:: 3.8 + Returns ``1`` if *o* is an index integer. + + +.. c:function:: PyObject* PyNumber_Add(PyObject *o1, PyObject *o2) + + Returns the result of adding *o1* and *o2*, or ``NULL`` on failure. This is the + equivalent of the Python expression ``o1 + o2``. + + +.. c:function:: PyObject* PyNumber_Subtract(PyObject *o1, PyObject *o2) + + Returns the result of subtracting *o2* from *o1*, or ``NULL`` on failure. This is + the equivalent of the Python expression ``o1 - o2``. + + +.. c:function:: PyObject* PyNumber_Multiply(PyObject *o1, PyObject *o2) + + Returns the result of multiplying *o1* and *o2*, or ``NULL`` on failure. This is + the equivalent of the Python expression ``o1 * o2``. + + +.. c:function:: PyObject* PyNumber_MatrixMultiply(PyObject *o1, PyObject *o2) + + Returns the result of matrix multiplication on *o1* and *o2*, or ``NULL`` on + failure. This is the equivalent of the Python expression ``o1 @ o2``. + + .. versionadded:: 3.5 + + +.. c:function:: PyObject* PyNumber_FloorDivide(PyObject *o1, PyObject *o2) + + Return the floor of *o1* divided by *o2*, or ``NULL`` on failure. This is + equivalent to the "classic" division of integers. + + +.. c:function:: PyObject* PyNumber_TrueDivide(PyObject *o1, PyObject *o2) + + Return a reasonable approximation for the mathematical value of *o1* divided by + *o2*, or ``NULL`` on failure. The return value is "approximate" because binary + floating point numbers are approximate; it is not possible to represent all real + numbers in base two. This function can return a floating point value when + passed two integers. + + +.. c:function:: PyObject* PyNumber_Remainder(PyObject *o1, PyObject *o2) + + Returns the remainder of dividing *o1* by *o2*, or ``NULL`` on failure. This is + the equivalent of the Python expression ``o1 % o2``. + + +.. c:function:: PyObject* PyNumber_Divmod(PyObject *o1, PyObject *o2) + + .. index:: builtin: divmod + + See the built-in function :func:`divmod`. Returns ``NULL`` on failure. This is + the equivalent of the Python expression ``divmod(o1, o2)``. + + +.. c:function:: PyObject* PyNumber_Power(PyObject *o1, PyObject *o2, PyObject *o3) + + .. index:: builtin: pow + + See the built-in function :func:`pow`. Returns ``NULL`` on failure. This is the + equivalent of the Python expression ``pow(o1, o2, o3)``, where *o3* is optional. + If *o3* is to be ignored, pass :c:data:`Py_None` in its place (passing ``NULL`` for + *o3* would cause an illegal memory access). + + +.. c:function:: PyObject* PyNumber_Negative(PyObject *o) + + Returns the negation of *o* on success, or ``NULL`` on failure. This is the + equivalent of the Python expression ``-o``. + + +.. c:function:: PyObject* PyNumber_Positive(PyObject *o) + + Returns *o* on success, or ``NULL`` on failure. This is the equivalent of the + Python expression ``+o``. + + +.. c:function:: PyObject* PyNumber_Absolute(PyObject *o) + + .. index:: builtin: abs + + Returns the absolute value of *o*, or ``NULL`` on failure. This is the equivalent + of the Python expression ``abs(o)``. + + +.. c:function:: PyObject* PyNumber_Invert(PyObject *o) + + Returns the bitwise negation of *o* on success, or ``NULL`` on failure. This is + the equivalent of the Python expression ``~o``. + + +.. c:function:: PyObject* PyNumber_Lshift(PyObject *o1, PyObject *o2) + + Returns the result of left shifting *o1* by *o2* on success, or ``NULL`` on + failure. This is the equivalent of the Python expression ``o1 << o2``. + + +.. c:function:: PyObject* PyNumber_Rshift(PyObject *o1, PyObject *o2) + + Returns the result of right shifting *o1* by *o2* on success, or ``NULL`` on + failure. This is the equivalent of the Python expression ``o1 >> o2``. + + +.. c:function:: PyObject* PyNumber_And(PyObject *o1, PyObject *o2) + + Returns the "bitwise and" of *o1* and *o2* on success and ``NULL`` on failure. + This is the equivalent of the Python expression ``o1 & o2``. + + +.. c:function:: PyObject* PyNumber_Xor(PyObject *o1, PyObject *o2) + + Returns the "bitwise exclusive or" of *o1* by *o2* on success, or ``NULL`` on + failure. This is the equivalent of the Python expression ``o1 ^ o2``. + + +.. c:function:: PyObject* PyNumber_Or(PyObject *o1, PyObject *o2) + + Returns the "bitwise or" of *o1* and *o2* on success, or ``NULL`` on failure. + This is the equivalent of the Python expression ``o1 | o2``. + + +.. c:function:: PyObject* PyNumber_InPlaceAdd(PyObject *o1, PyObject *o2) + + Returns the result of adding *o1* and *o2*, or ``NULL`` on failure. The operation + is done *in-place* when *o1* supports it. This is the equivalent of the Python + statement ``o1 += o2``. + + +.. c:function:: PyObject* PyNumber_InPlaceSubtract(PyObject *o1, PyObject *o2) + + Returns the result of subtracting *o2* from *o1*, or ``NULL`` on failure. The + operation is done *in-place* when *o1* supports it. This is the equivalent of + the Python statement ``o1 -= o2``. + + +.. c:function:: PyObject* PyNumber_InPlaceMultiply(PyObject *o1, PyObject *o2) + + Returns the result of multiplying *o1* and *o2*, or ``NULL`` on failure. The + operation is done *in-place* when *o1* supports it. This is the equivalent of + the Python statement ``o1 *= o2``. + + +.. c:function:: PyObject* PyNumber_InPlaceMatrixMultiply(PyObject *o1, PyObject *o2) + + Returns the result of matrix multiplication on *o1* and *o2*, or ``NULL`` on + failure. The operation is done *in-place* when *o1* supports it. This is + the equivalent of the Python statement ``o1 @= o2``. + + .. versionadded:: 3.5 + + +.. c:function:: PyObject* PyNumber_InPlaceFloorDivide(PyObject *o1, PyObject *o2) + + Returns the mathematical floor of dividing *o1* by *o2*, or ``NULL`` on failure. + The operation is done *in-place* when *o1* supports it. This is the equivalent + of the Python statement ``o1 //= o2``. + + +.. c:function:: PyObject* PyNumber_InPlaceTrueDivide(PyObject *o1, PyObject *o2) + + Return a reasonable approximation for the mathematical value of *o1* divided by + *o2*, or ``NULL`` on failure. The return value is "approximate" because binary + floating point numbers are approximate; it is not possible to represent all real + numbers in base two. This function can return a floating point value when + passed two integers. The operation is done *in-place* when *o1* supports it. + + +.. c:function:: PyObject* PyNumber_InPlaceRemainder(PyObject *o1, PyObject *o2) + + Returns the remainder of dividing *o1* by *o2*, or ``NULL`` on failure. The + operation is done *in-place* when *o1* supports it. This is the equivalent of + the Python statement ``o1 %= o2``. + + +.. c:function:: PyObject* PyNumber_InPlacePower(PyObject *o1, PyObject *o2, PyObject *o3) + + .. index:: builtin: pow + + See the built-in function :func:`pow`. Returns ``NULL`` on failure. The operation + is done *in-place* when *o1* supports it. This is the equivalent of the Python + statement ``o1 **= o2`` when o3 is :c:data:`Py_None`, or an in-place variant of + ``pow(o1, o2, o3)`` otherwise. If *o3* is to be ignored, pass :c:data:`Py_None` + in its place (passing ``NULL`` for *o3* would cause an illegal memory access). + + +.. c:function:: PyObject* PyNumber_InPlaceLshift(PyObject *o1, PyObject *o2) + + Returns the result of left shifting *o1* by *o2* on success, or ``NULL`` on + failure. The operation is done *in-place* when *o1* supports it. This is the + equivalent of the Python statement ``o1 <<= o2``. + + +.. c:function:: PyObject* PyNumber_InPlaceRshift(PyObject *o1, PyObject *o2) + + Returns the result of right shifting *o1* by *o2* on success, or ``NULL`` on + failure. The operation is done *in-place* when *o1* supports it. This is the + equivalent of the Python statement ``o1 >>= o2``. + + +.. c:function:: PyObject* PyNumber_InPlaceAnd(PyObject *o1, PyObject *o2) + + Returns the "bitwise and" of *o1* and *o2* on success and ``NULL`` on failure. The + operation is done *in-place* when *o1* supports it. This is the equivalent of + the Python statement ``o1 &= o2``. + + +.. c:function:: PyObject* PyNumber_InPlaceXor(PyObject *o1, PyObject *o2) + + Returns the "bitwise exclusive or" of *o1* by *o2* on success, or ``NULL`` on + failure. The operation is done *in-place* when *o1* supports it. This is the + equivalent of the Python statement ``o1 ^= o2``. + + +.. c:function:: PyObject* PyNumber_InPlaceOr(PyObject *o1, PyObject *o2) + + Returns the "bitwise or" of *o1* and *o2* on success, or ``NULL`` on failure. The + operation is done *in-place* when *o1* supports it. This is the equivalent of + the Python statement ``o1 |= o2``. + + +.. c:function:: PyObject* PyNumber_Long(PyObject *o) + + .. index:: builtin: int + + Returns the *o* converted to an integer object on success, or ``NULL`` on + failure. This is the equivalent of the Python expression ``int(o)``. + + +.. c:function:: PyObject* PyNumber_Float(PyObject *o) + + .. index:: builtin: float + + Returns the *o* converted to a float object on success, or ``NULL`` on failure. + This is the equivalent of the Python expression ``float(o)``. + + +.. c:function:: PyObject* PyNumber_Index(PyObject *o) + + Returns the *o* converted to a Python int on success or ``NULL`` with a + :exc:`TypeError` exception raised on failure. + + +.. c:function:: PyObject* PyNumber_ToBase(PyObject *n, int base) + + Returns the integer *n* converted to base *base* as a string. The *base* + argument must be one of 2, 8, 10, or 16. For base 2, 8, or 16, the + returned string is prefixed with a base marker of ``'0b'``, ``'0o'``, or + ``'0x'``, respectively. If *n* is not a Python int, it is converted with + :c:func:`PyNumber_Index` first. + + +.. c:function:: Py_ssize_t PyNumber_AsSsize_t(PyObject *o, PyObject *exc) + + Returns *o* converted to a Py_ssize_t value if *o* can be interpreted as an + integer. If the call fails, an exception is raised and ``-1`` is returned. + + If *o* can be converted to a Python int but the attempt to + convert to a Py_ssize_t value would raise an :exc:`OverflowError`, then the + *exc* argument is the type of exception that will be raised (usually + :exc:`IndexError` or :exc:`OverflowError`). If *exc* is ``NULL``, then the + exception is cleared and the value is clipped to ``PY_SSIZE_T_MIN`` for a negative + integer or ``PY_SSIZE_T_MAX`` for a positive integer. + + +.. c:function:: int PyIndex_Check(PyObject *o) + + Returns ``1`` if *o* is an index integer (has the nb_index slot of the + tp_as_number structure filled in), and ``0`` otherwise. + This function always succeeds. diff --git a/cpython_2/environment/repo/Doc/c-api/objbuffer.rst b/cpython_2/environment/repo/Doc/c-api/objbuffer.rst new file mode 100644 index 0000000000000000000000000000000000000000..6b82a642d7ee42715b6aea488723f07582301e5d --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/objbuffer.rst @@ -0,0 +1,55 @@ +.. highlight:: c + +Old Buffer Protocol +------------------- + +.. deprecated:: 3.0 + +These functions were part of the "old buffer protocol" API in Python 2. +In Python 3, this protocol doesn't exist anymore but the functions are still +exposed to ease porting 2.x code. They act as a compatibility wrapper +around the :ref:`new buffer protocol `, but they don't give +you control over the lifetime of the resources acquired when a buffer is +exported. + +Therefore, it is recommended that you call :c:func:`PyObject_GetBuffer` +(or the ``y*`` or ``w*`` :ref:`format codes ` with the +:c:func:`PyArg_ParseTuple` family of functions) to get a buffer view over +an object, and :c:func:`PyBuffer_Release` when the buffer view can be released. + + +.. c:function:: int PyObject_AsCharBuffer(PyObject *obj, const char **buffer, Py_ssize_t *buffer_len) + + Returns a pointer to a read-only memory location usable as character-based + input. The *obj* argument must support the single-segment character buffer + interface. On success, returns ``0``, sets *buffer* to the memory location + and *buffer_len* to the buffer length. Returns ``-1`` and sets a + :exc:`TypeError` on error. + + +.. c:function:: int PyObject_AsReadBuffer(PyObject *obj, const void **buffer, Py_ssize_t *buffer_len) + + Returns a pointer to a read-only memory location containing arbitrary data. + The *obj* argument must support the single-segment readable buffer + interface. On success, returns ``0``, sets *buffer* to the memory location + and *buffer_len* to the buffer length. Returns ``-1`` and sets a + :exc:`TypeError` on error. + + +.. c:function:: int PyObject_CheckReadBuffer(PyObject *o) + + Returns ``1`` if *o* supports the single-segment readable buffer interface. + Otherwise returns ``0``. This function always succeeds. + + Note that this function tries to get and release a buffer, and exceptions + which occur while calling corresponding functions will get suppressed. + To get error reporting use :c:func:`PyObject_GetBuffer()` instead. + + +.. c:function:: int PyObject_AsWriteBuffer(PyObject *obj, void **buffer, Py_ssize_t *buffer_len) + + Returns a pointer to a writable memory location. The *obj* argument must + support the single-segment, character buffer interface. On success, + returns ``0``, sets *buffer* to the memory location and *buffer_len* to the + buffer length. Returns ``-1`` and sets a :exc:`TypeError` on error. + diff --git a/cpython_2/environment/repo/Doc/c-api/object.rst b/cpython_2/environment/repo/Doc/c-api/object.rst new file mode 100644 index 0000000000000000000000000000000000000000..b9c137ea352e78e5c21b5a280d0b1217a3cbed38 --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/object.rst @@ -0,0 +1,358 @@ +.. highlight:: c + +.. _object: + +Object Protocol +=============== + + +.. c:var:: PyObject* Py_NotImplemented + + The ``NotImplemented`` singleton, used to signal that an operation is + not implemented for the given type combination. + + +.. c:macro:: Py_RETURN_NOTIMPLEMENTED + + Properly handle returning :c:data:`Py_NotImplemented` from within a C + function (that is, increment the reference count of NotImplemented and + return it). + + +.. c:function:: int PyObject_Print(PyObject *o, FILE *fp, int flags) + + Print an object *o*, on file *fp*. Returns ``-1`` on error. The flags argument + is used to enable certain printing options. The only option currently supported + is :const:`Py_PRINT_RAW`; if given, the :func:`str` of the object is written + instead of the :func:`repr`. + + +.. c:function:: int PyObject_HasAttr(PyObject *o, PyObject *attr_name) + + Returns ``1`` if *o* has the attribute *attr_name*, and ``0`` otherwise. This + is equivalent to the Python expression ``hasattr(o, attr_name)``. This function + always succeeds. + + Note that exceptions which occur while calling :meth:`__getattr__` and + :meth:`__getattribute__` methods will get suppressed. + To get error reporting use :c:func:`PyObject_GetAttr()` instead. + + +.. c:function:: int PyObject_HasAttrString(PyObject *o, const char *attr_name) + + Returns ``1`` if *o* has the attribute *attr_name*, and ``0`` otherwise. This + is equivalent to the Python expression ``hasattr(o, attr_name)``. This function + always succeeds. + + Note that exceptions which occur while calling :meth:`__getattr__` and + :meth:`__getattribute__` methods and creating a temporary string object + will get suppressed. + To get error reporting use :c:func:`PyObject_GetAttrString()` instead. + + +.. c:function:: PyObject* PyObject_GetAttr(PyObject *o, PyObject *attr_name) + + Retrieve an attribute named *attr_name* from object *o*. Returns the attribute + value on success, or ``NULL`` on failure. This is the equivalent of the Python + expression ``o.attr_name``. + + +.. c:function:: PyObject* PyObject_GetAttrString(PyObject *o, const char *attr_name) + + Retrieve an attribute named *attr_name* from object *o*. Returns the attribute + value on success, or ``NULL`` on failure. This is the equivalent of the Python + expression ``o.attr_name``. + + +.. c:function:: PyObject* PyObject_GenericGetAttr(PyObject *o, PyObject *name) + + Generic attribute getter function that is meant to be put into a type + object's ``tp_getattro`` slot. It looks for a descriptor in the dictionary + of classes in the object's MRO as well as an attribute in the object's + :attr:`~object.__dict__` (if present). As outlined in :ref:`descriptors`, + data descriptors take preference over instance attributes, while non-data + descriptors don't. Otherwise, an :exc:`AttributeError` is raised. + + +.. c:function:: int PyObject_SetAttr(PyObject *o, PyObject *attr_name, PyObject *v) + + Set the value of the attribute named *attr_name*, for object *o*, to the value + *v*. Raise an exception and return ``-1`` on failure; + return ``0`` on success. This is the equivalent of the Python statement + ``o.attr_name = v``. + + If *v* is ``NULL``, the attribute is deleted, however this feature is + deprecated in favour of using :c:func:`PyObject_DelAttr`. + + +.. c:function:: int PyObject_SetAttrString(PyObject *o, const char *attr_name, PyObject *v) + + Set the value of the attribute named *attr_name*, for object *o*, to the value + *v*. Raise an exception and return ``-1`` on failure; + return ``0`` on success. This is the equivalent of the Python statement + ``o.attr_name = v``. + + If *v* is ``NULL``, the attribute is deleted, however this feature is + deprecated in favour of using :c:func:`PyObject_DelAttrString`. + + +.. c:function:: int PyObject_GenericSetAttr(PyObject *o, PyObject *name, PyObject *value) + + Generic attribute setter and deleter function that is meant + to be put into a type object's :c:member:`~PyTypeObject.tp_setattro` + slot. It looks for a data descriptor in the + dictionary of classes in the object's MRO, and if found it takes preference + over setting or deleting the attribute in the instance dictionary. Otherwise, the + attribute is set or deleted in the object's :attr:`~object.__dict__` (if present). + On success, ``0`` is returned, otherwise an :exc:`AttributeError` + is raised and ``-1`` is returned. + + +.. c:function:: int PyObject_DelAttr(PyObject *o, PyObject *attr_name) + + Delete attribute named *attr_name*, for object *o*. Returns ``-1`` on failure. + This is the equivalent of the Python statement ``del o.attr_name``. + + +.. c:function:: int PyObject_DelAttrString(PyObject *o, const char *attr_name) + + Delete attribute named *attr_name*, for object *o*. Returns ``-1`` on failure. + This is the equivalent of the Python statement ``del o.attr_name``. + + +.. c:function:: PyObject* PyObject_GenericGetDict(PyObject *o, void *context) + + A generic implementation for the getter of a ``__dict__`` descriptor. It + creates the dictionary if necessary. + + .. versionadded:: 3.3 + + +.. c:function:: int PyObject_GenericSetDict(PyObject *o, PyObject *value, void *context) + + A generic implementation for the setter of a ``__dict__`` descriptor. This + implementation does not allow the dictionary to be deleted. + + .. versionadded:: 3.3 + + +.. c:function:: PyObject* PyObject_RichCompare(PyObject *o1, PyObject *o2, int opid) + + Compare the values of *o1* and *o2* using the operation specified by *opid*, + which must be one of :const:`Py_LT`, :const:`Py_LE`, :const:`Py_EQ`, + :const:`Py_NE`, :const:`Py_GT`, or :const:`Py_GE`, corresponding to ``<``, + ``<=``, ``==``, ``!=``, ``>``, or ``>=`` respectively. This is the equivalent of + the Python expression ``o1 op o2``, where ``op`` is the operator corresponding + to *opid*. Returns the value of the comparison on success, or ``NULL`` on failure. + + +.. c:function:: int PyObject_RichCompareBool(PyObject *o1, PyObject *o2, int opid) + + Compare the values of *o1* and *o2* using the operation specified by *opid*, + which must be one of :const:`Py_LT`, :const:`Py_LE`, :const:`Py_EQ`, + :const:`Py_NE`, :const:`Py_GT`, or :const:`Py_GE`, corresponding to ``<``, + ``<=``, ``==``, ``!=``, ``>``, or ``>=`` respectively. Returns ``-1`` on error, + ``0`` if the result is false, ``1`` otherwise. This is the equivalent of the + Python expression ``o1 op o2``, where ``op`` is the operator corresponding to + *opid*. + +.. note:: + If *o1* and *o2* are the same object, :c:func:`PyObject_RichCompareBool` + will always return ``1`` for :const:`Py_EQ` and ``0`` for :const:`Py_NE`. + +.. c:function:: PyObject* PyObject_Repr(PyObject *o) + + .. index:: builtin: repr + + Compute a string representation of object *o*. Returns the string + representation on success, ``NULL`` on failure. This is the equivalent of the + Python expression ``repr(o)``. Called by the :func:`repr` built-in function. + + .. versionchanged:: 3.4 + This function now includes a debug assertion to help ensure that it + does not silently discard an active exception. + +.. c:function:: PyObject* PyObject_ASCII(PyObject *o) + + .. index:: builtin: ascii + + As :c:func:`PyObject_Repr`, compute a string representation of object *o*, but + escape the non-ASCII characters in the string returned by + :c:func:`PyObject_Repr` with ``\x``, ``\u`` or ``\U`` escapes. This generates + a string similar to that returned by :c:func:`PyObject_Repr` in Python 2. + Called by the :func:`ascii` built-in function. + + .. index:: string; PyObject_Str (C function) + + +.. c:function:: PyObject* PyObject_Str(PyObject *o) + + Compute a string representation of object *o*. Returns the string + representation on success, ``NULL`` on failure. This is the equivalent of the + Python expression ``str(o)``. Called by the :func:`str` built-in function + and, therefore, by the :func:`print` function. + + .. versionchanged:: 3.4 + This function now includes a debug assertion to help ensure that it + does not silently discard an active exception. + + +.. c:function:: PyObject* PyObject_Bytes(PyObject *o) + + .. index:: builtin: bytes + + Compute a bytes representation of object *o*. ``NULL`` is returned on + failure and a bytes object on success. This is equivalent to the Python + expression ``bytes(o)``, when *o* is not an integer. Unlike ``bytes(o)``, + a TypeError is raised when *o* is an integer instead of a zero-initialized + bytes object. + + +.. c:function:: int PyObject_IsSubclass(PyObject *derived, PyObject *cls) + + Return ``1`` if the class *derived* is identical to or derived from the class + *cls*, otherwise return ``0``. In case of an error, return ``-1``. + + If *cls* is a tuple, the check will be done against every entry in *cls*. + The result will be ``1`` when at least one of the checks returns ``1``, + otherwise it will be ``0``. + + If *cls* has a :meth:`~class.__subclasscheck__` method, it will be called to + determine the subclass status as described in :pep:`3119`. Otherwise, + *derived* is a subclass of *cls* if it is a direct or indirect subclass, + i.e. contained in ``cls.__mro__``. + + Normally only class objects, i.e. instances of :class:`type` or a derived + class, are considered classes. However, objects can override this by having + a :attr:`__bases__` attribute (which must be a tuple of base classes). + + +.. c:function:: int PyObject_IsInstance(PyObject *inst, PyObject *cls) + + Return ``1`` if *inst* is an instance of the class *cls* or a subclass of + *cls*, or ``0`` if not. On error, returns ``-1`` and sets an exception. + + If *cls* is a tuple, the check will be done against every entry in *cls*. + The result will be ``1`` when at least one of the checks returns ``1``, + otherwise it will be ``0``. + + If *cls* has a :meth:`~class.__instancecheck__` method, it will be called to + determine the subclass status as described in :pep:`3119`. Otherwise, *inst* + is an instance of *cls* if its class is a subclass of *cls*. + + An instance *inst* can override what is considered its class by having a + :attr:`__class__` attribute. + + An object *cls* can override if it is considered a class, and what its base + classes are, by having a :attr:`__bases__` attribute (which must be a tuple + of base classes). + + +.. c:function:: Py_hash_t PyObject_Hash(PyObject *o) + + .. index:: builtin: hash + + Compute and return the hash value of an object *o*. On failure, return ``-1``. + This is the equivalent of the Python expression ``hash(o)``. + + .. versionchanged:: 3.2 + The return type is now Py_hash_t. This is a signed integer the same size + as Py_ssize_t. + + +.. c:function:: Py_hash_t PyObject_HashNotImplemented(PyObject *o) + + Set a :exc:`TypeError` indicating that ``type(o)`` is not hashable and return ``-1``. + This function receives special treatment when stored in a ``tp_hash`` slot, + allowing a type to explicitly indicate to the interpreter that it is not + hashable. + + +.. c:function:: int PyObject_IsTrue(PyObject *o) + + Returns ``1`` if the object *o* is considered to be true, and ``0`` otherwise. + This is equivalent to the Python expression ``not not o``. On failure, return + ``-1``. + + +.. c:function:: int PyObject_Not(PyObject *o) + + Returns ``0`` if the object *o* is considered to be true, and ``1`` otherwise. + This is equivalent to the Python expression ``not o``. On failure, return + ``-1``. + + +.. c:function:: PyObject* PyObject_Type(PyObject *o) + + .. index:: builtin: type + + When *o* is non-``NULL``, returns a type object corresponding to the object type + of object *o*. On failure, raises :exc:`SystemError` and returns ``NULL``. This + is equivalent to the Python expression ``type(o)``. This function increments the + reference count of the return value. There's really no reason to use this + function instead of the common expression ``o->ob_type``, which returns a + pointer of type :c:type:`PyTypeObject\*`, except when the incremented reference + count is needed. + + +.. c:function:: int PyObject_TypeCheck(PyObject *o, PyTypeObject *type) + + Return true if the object *o* is of type *type* or a subtype of *type*. Both + parameters must be non-``NULL``. + + +.. c:function:: Py_ssize_t PyObject_Size(PyObject *o) + Py_ssize_t PyObject_Length(PyObject *o) + + .. index:: builtin: len + + Return the length of object *o*. If the object *o* provides either the sequence + and mapping protocols, the sequence length is returned. On error, ``-1`` is + returned. This is the equivalent to the Python expression ``len(o)``. + + +.. c:function:: Py_ssize_t PyObject_LengthHint(PyObject *o, Py_ssize_t default) + + Return an estimated length for the object *o*. First try to return its + actual length, then an estimate using :meth:`~object.__length_hint__`, and + finally return the default value. On error return ``-1``. This is the + equivalent to the Python expression ``operator.length_hint(o, default)``. + + .. versionadded:: 3.4 + + +.. c:function:: PyObject* PyObject_GetItem(PyObject *o, PyObject *key) + + Return element of *o* corresponding to the object *key* or ``NULL`` on failure. + This is the equivalent of the Python expression ``o[key]``. + + +.. c:function:: int PyObject_SetItem(PyObject *o, PyObject *key, PyObject *v) + + Map the object *key* to the value *v*. Raise an exception and + return ``-1`` on failure; return ``0`` on success. This is the + equivalent of the Python statement ``o[key] = v``. This function *does + not* steal a reference to *v*. + + +.. c:function:: int PyObject_DelItem(PyObject *o, PyObject *key) + + Remove the mapping for the object *key* from the object *o*. Return ``-1`` + on failure. This is equivalent to the Python statement ``del o[key]``. + + +.. c:function:: PyObject* PyObject_Dir(PyObject *o) + + This is equivalent to the Python expression ``dir(o)``, returning a (possibly + empty) list of strings appropriate for the object argument, or ``NULL`` if there + was an error. If the argument is ``NULL``, this is like the Python ``dir()``, + returning the names of the current locals; in this case, if no execution frame + is active then ``NULL`` is returned but :c:func:`PyErr_Occurred` will return false. + + +.. c:function:: PyObject* PyObject_GetIter(PyObject *o) + + This is equivalent to the Python expression ``iter(o)``. It returns a new + iterator for the object argument, or the object itself if the object is already + an iterator. Raises :exc:`TypeError` and returns ``NULL`` if the object cannot be + iterated. diff --git a/cpython_2/environment/repo/Doc/c-api/objimpl.rst b/cpython_2/environment/repo/Doc/c-api/objimpl.rst new file mode 100644 index 0000000000000000000000000000000000000000..8bd8c107c98bdfc67b389b5ba1420aa8768fd9f4 --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/objimpl.rst @@ -0,0 +1,17 @@ +.. highlight:: c + +.. _newtypes: + +***************************** +Object Implementation Support +***************************** + +This chapter describes the functions, types, and macros used when defining new +object types. + +.. toctree:: + + allocation.rst + structures.rst + typeobj.rst + gcsupport.rst diff --git a/cpython_2/environment/repo/Doc/c-api/refcounting.rst b/cpython_2/environment/repo/Doc/c-api/refcounting.rst new file mode 100644 index 0000000000000000000000000000000000000000..0df12c67f40bc3f8b3749bc6556753b2388af29d --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/refcounting.rst @@ -0,0 +1,73 @@ +.. highlight:: c + + +.. _countingrefs: + +****************** +Reference Counting +****************** + +The macros in this section are used for managing reference counts of Python +objects. + + +.. c:function:: void Py_INCREF(PyObject *o) + + Increment the reference count for object *o*. The object must not be ``NULL``; if + you aren't sure that it isn't ``NULL``, use :c:func:`Py_XINCREF`. + + +.. c:function:: void Py_XINCREF(PyObject *o) + + Increment the reference count for object *o*. The object may be ``NULL``, in + which case the macro has no effect. + + +.. c:function:: void Py_DECREF(PyObject *o) + + Decrement the reference count for object *o*. The object must not be ``NULL``; if + you aren't sure that it isn't ``NULL``, use :c:func:`Py_XDECREF`. If the reference + count reaches zero, the object's type's deallocation function (which must not be + ``NULL``) is invoked. + + .. warning:: + + The deallocation function can cause arbitrary Python code to be invoked (e.g. + when a class instance with a :meth:`__del__` method is deallocated). While + exceptions in such code are not propagated, the executed code has free access to + all Python global variables. This means that any object that is reachable from + a global variable should be in a consistent state before :c:func:`Py_DECREF` is + invoked. For example, code to delete an object from a list should copy a + reference to the deleted object in a temporary variable, update the list data + structure, and then call :c:func:`Py_DECREF` for the temporary variable. + + +.. c:function:: void Py_XDECREF(PyObject *o) + + Decrement the reference count for object *o*. The object may be ``NULL``, in + which case the macro has no effect; otherwise the effect is the same as for + :c:func:`Py_DECREF`, and the same warning applies. + + +.. c:function:: void Py_CLEAR(PyObject *o) + + Decrement the reference count for object *o*. The object may be ``NULL``, in + which case the macro has no effect; otherwise the effect is the same as for + :c:func:`Py_DECREF`, except that the argument is also set to ``NULL``. The warning + for :c:func:`Py_DECREF` does not apply with respect to the object passed because + the macro carefully uses a temporary variable and sets the argument to ``NULL`` + before decrementing its reference count. + + It is a good idea to use this macro whenever decrementing the reference + count of an object that might be traversed during garbage collection. + + +The following functions are for runtime dynamic embedding of Python: +``Py_IncRef(PyObject *o)``, ``Py_DecRef(PyObject *o)``. They are +simply exported function versions of :c:func:`Py_XINCREF` and +:c:func:`Py_XDECREF`, respectively. + +The following functions or macros are only for use within the interpreter core: +:c:func:`_Py_Dealloc`, :c:func:`_Py_ForgetReference`, :c:func:`_Py_NewReference`, +as well as the global variable :c:data:`_Py_RefTotal`. + diff --git a/cpython_2/environment/repo/Doc/c-api/reflection.rst b/cpython_2/environment/repo/Doc/c-api/reflection.rst new file mode 100644 index 0000000000000000000000000000000000000000..9207d86012c8b338175ba72b849510b7d8edb8c4 --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/reflection.rst @@ -0,0 +1,75 @@ +.. highlight:: c + +.. _reflection: + +Reflection +========== + +.. c:function:: PyObject* PyEval_GetBuiltins(void) + + Return a dictionary of the builtins in the current execution frame, + or the interpreter of the thread state if no frame is currently executing. + + +.. c:function:: PyObject* PyEval_GetLocals(void) + + Return a dictionary of the local variables in the current execution frame, + or ``NULL`` if no frame is currently executing. + + +.. c:function:: PyObject* PyEval_GetGlobals(void) + + Return a dictionary of the global variables in the current execution frame, + or ``NULL`` if no frame is currently executing. + + +.. c:function:: PyFrameObject* PyEval_GetFrame(void) + + Return the current thread state's frame, which is ``NULL`` if no frame is + currently executing. + + See also :c:func:`PyThreadState_GetFrame`. + + +.. c:function:: int PyFrame_GetBack(PyFrameObject *frame) + + Get the *frame* next outer frame. + + Return a strong reference, or ``NULL`` if *frame* has no outer frame. + + *frame* must not be ``NULL``. + + .. versionadded:: 3.9 + + +.. c:function:: int PyFrame_GetCode(PyFrameObject *frame) + + Get the *frame* code. + + Return a strong reference. + + *frame* must not be ``NULL``. The result (frame code) cannot be ``NULL``. + + .. versionadded:: 3.9 + + +.. c:function:: int PyFrame_GetLineNumber(PyFrameObject *frame) + + Return the line number that *frame* is currently executing. + + *frame* must not be ``NULL``. + + +.. c:function:: const char* PyEval_GetFuncName(PyObject *func) + + Return the name of *func* if it is a function, class or instance object, else the + name of *func*\s type. + + +.. c:function:: const char* PyEval_GetFuncDesc(PyObject *func) + + Return a description string, depending on the type of *func*. + Return values include "()" for functions and methods, " constructor", + " instance", and " object". Concatenated with the result of + :c:func:`PyEval_GetFuncName`, the result will be a description of + *func*. diff --git a/cpython_2/environment/repo/Doc/c-api/sequence.rst b/cpython_2/environment/repo/Doc/c-api/sequence.rst new file mode 100644 index 0000000000000000000000000000000000000000..65818859041179059d6495cedcc9c67029783447 --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/sequence.rst @@ -0,0 +1,176 @@ +.. highlight:: c + +.. _sequence: + +Sequence Protocol +================= + + +.. c:function:: int PySequence_Check(PyObject *o) + + Return ``1`` if the object provides sequence protocol, and ``0`` otherwise. + Note that it returns ``1`` for Python classes with a :meth:`__getitem__` + method unless they are :class:`dict` subclasses since in general case it + is impossible to determine what the type of keys it supports. This + function always succeeds. + + +.. c:function:: Py_ssize_t PySequence_Size(PyObject *o) + Py_ssize_t PySequence_Length(PyObject *o) + + .. index:: builtin: len + + Returns the number of objects in sequence *o* on success, and ``-1`` on + failure. This is equivalent to the Python expression ``len(o)``. + + +.. c:function:: PyObject* PySequence_Concat(PyObject *o1, PyObject *o2) + + Return the concatenation of *o1* and *o2* on success, and ``NULL`` on failure. + This is the equivalent of the Python expression ``o1 + o2``. + + +.. c:function:: PyObject* PySequence_Repeat(PyObject *o, Py_ssize_t count) + + Return the result of repeating sequence object *o* *count* times, or ``NULL`` on + failure. This is the equivalent of the Python expression ``o * count``. + + +.. c:function:: PyObject* PySequence_InPlaceConcat(PyObject *o1, PyObject *o2) + + Return the concatenation of *o1* and *o2* on success, and ``NULL`` on failure. + The operation is done *in-place* when *o1* supports it. This is the equivalent + of the Python expression ``o1 += o2``. + + +.. c:function:: PyObject* PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count) + + Return the result of repeating sequence object *o* *count* times, or ``NULL`` on + failure. The operation is done *in-place* when *o* supports it. This is the + equivalent of the Python expression ``o *= count``. + + +.. c:function:: PyObject* PySequence_GetItem(PyObject *o, Py_ssize_t i) + + Return the *i*\ th element of *o*, or ``NULL`` on failure. This is the equivalent of + the Python expression ``o[i]``. + + +.. c:function:: PyObject* PySequence_GetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2) + + Return the slice of sequence object *o* between *i1* and *i2*, or ``NULL`` on + failure. This is the equivalent of the Python expression ``o[i1:i2]``. + + +.. c:function:: int PySequence_SetItem(PyObject *o, Py_ssize_t i, PyObject *v) + + Assign object *v* to the *i*\ th element of *o*. Raise an exception + and return ``-1`` on failure; return ``0`` on success. This + is the equivalent of the Python statement ``o[i] = v``. This function *does + not* steal a reference to *v*. + + If *v* is ``NULL``, the element is deleted, however this feature is + deprecated in favour of using :c:func:`PySequence_DelItem`. + + +.. c:function:: int PySequence_DelItem(PyObject *o, Py_ssize_t i) + + Delete the *i*\ th element of object *o*. Returns ``-1`` on failure. This is the + equivalent of the Python statement ``del o[i]``. + + +.. c:function:: int PySequence_SetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2, PyObject *v) + + Assign the sequence object *v* to the slice in sequence object *o* from *i1* to + *i2*. This is the equivalent of the Python statement ``o[i1:i2] = v``. + + +.. c:function:: int PySequence_DelSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2) + + Delete the slice in sequence object *o* from *i1* to *i2*. Returns ``-1`` on + failure. This is the equivalent of the Python statement ``del o[i1:i2]``. + + +.. c:function:: Py_ssize_t PySequence_Count(PyObject *o, PyObject *value) + + Return the number of occurrences of *value* in *o*, that is, return the number + of keys for which ``o[key] == value``. On failure, return ``-1``. This is + equivalent to the Python expression ``o.count(value)``. + + +.. c:function:: int PySequence_Contains(PyObject *o, PyObject *value) + + Determine if *o* contains *value*. If an item in *o* is equal to *value*, + return ``1``, otherwise return ``0``. On error, return ``-1``. This is + equivalent to the Python expression ``value in o``. + + +.. c:function:: Py_ssize_t PySequence_Index(PyObject *o, PyObject *value) + + Return the first index *i* for which ``o[i] == value``. On error, return + ``-1``. This is equivalent to the Python expression ``o.index(value)``. + + +.. c:function:: PyObject* PySequence_List(PyObject *o) + + Return a list object with the same contents as the sequence or iterable *o*, + or ``NULL`` on failure. The returned list is guaranteed to be new. This is + equivalent to the Python expression ``list(o)``. + + +.. c:function:: PyObject* PySequence_Tuple(PyObject *o) + + .. index:: builtin: tuple + + Return a tuple object with the same contents as the sequence or iterable *o*, + or ``NULL`` on failure. If *o* is a tuple, a new reference will be returned, + otherwise a tuple will be constructed with the appropriate contents. This is + equivalent to the Python expression ``tuple(o)``. + + +.. c:function:: PyObject* PySequence_Fast(PyObject *o, const char *m) + + Return the sequence or iterable *o* as an object usable by the other + ``PySequence_Fast*`` family of functions. If the object is not a sequence or + iterable, raises :exc:`TypeError` with *m* as the message text. Returns + ``NULL`` on failure. + + The ``PySequence_Fast*`` functions are thus named because they assume + *o* is a :c:type:`PyTupleObject` or a :c:type:`PyListObject` and access + the data fields of *o* directly. + + As a CPython implementation detail, if *o* is already a sequence or list, it + will be returned. + + +.. c:function:: Py_ssize_t PySequence_Fast_GET_SIZE(PyObject *o) + + Returns the length of *o*, assuming that *o* was returned by + :c:func:`PySequence_Fast` and that *o* is not ``NULL``. The size can also be + gotten by calling :c:func:`PySequence_Size` on *o*, but + :c:func:`PySequence_Fast_GET_SIZE` is faster because it can assume *o* is a + list or tuple. + + +.. c:function:: PyObject* PySequence_Fast_GET_ITEM(PyObject *o, Py_ssize_t i) + + Return the *i*\ th element of *o*, assuming that *o* was returned by + :c:func:`PySequence_Fast`, *o* is not ``NULL``, and that *i* is within bounds. + + +.. c:function:: PyObject** PySequence_Fast_ITEMS(PyObject *o) + + Return the underlying array of PyObject pointers. Assumes that *o* was returned + by :c:func:`PySequence_Fast` and *o* is not ``NULL``. + + Note, if a list gets resized, the reallocation may relocate the items array. + So, only use the underlying array pointer in contexts where the sequence + cannot change. + + +.. c:function:: PyObject* PySequence_ITEM(PyObject *o, Py_ssize_t i) + + Return the *i*\ th element of *o* or ``NULL`` on failure. Faster form of + :c:func:`PySequence_GetItem` but without checking that + :c:func:`PySequence_Check` on *o* is true and without adjustment for negative + indices. diff --git a/cpython_2/environment/repo/Doc/c-api/set.rst b/cpython_2/environment/repo/Doc/c-api/set.rst new file mode 100644 index 0000000000000000000000000000000000000000..879f394d966cd07461c253e08bd8b5165cf0254a --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/set.rst @@ -0,0 +1,159 @@ +.. highlight:: c + +.. _setobjects: + +Set Objects +----------- + +.. sectionauthor:: Raymond D. Hettinger + + +.. index:: + object: set + object: frozenset + +This section details the public API for :class:`set` and :class:`frozenset` +objects. Any functionality not listed below is best accessed using the either +the abstract object protocol (including :c:func:`PyObject_CallMethod`, +:c:func:`PyObject_RichCompareBool`, :c:func:`PyObject_Hash`, +:c:func:`PyObject_Repr`, :c:func:`PyObject_IsTrue`, :c:func:`PyObject_Print`, and +:c:func:`PyObject_GetIter`) or the abstract number protocol (including +:c:func:`PyNumber_And`, :c:func:`PyNumber_Subtract`, :c:func:`PyNumber_Or`, +:c:func:`PyNumber_Xor`, :c:func:`PyNumber_InPlaceAnd`, +:c:func:`PyNumber_InPlaceSubtract`, :c:func:`PyNumber_InPlaceOr`, and +:c:func:`PyNumber_InPlaceXor`). + + +.. c:type:: PySetObject + + This subtype of :c:type:`PyObject` is used to hold the internal data for both + :class:`set` and :class:`frozenset` objects. It is like a :c:type:`PyDictObject` + in that it is a fixed size for small sets (much like tuple storage) and will + point to a separate, variable sized block of memory for medium and large sized + sets (much like list storage). None of the fields of this structure should be + considered public and are subject to change. All access should be done through + the documented API rather than by manipulating the values in the structure. + + +.. c:var:: PyTypeObject PySet_Type + + This is an instance of :c:type:`PyTypeObject` representing the Python + :class:`set` type. + + +.. c:var:: PyTypeObject PyFrozenSet_Type + + This is an instance of :c:type:`PyTypeObject` representing the Python + :class:`frozenset` type. + +The following type check macros work on pointers to any Python object. Likewise, +the constructor functions work with any iterable Python object. + + +.. c:function:: int PySet_Check(PyObject *p) + + Return true if *p* is a :class:`set` object or an instance of a subtype. + +.. c:function:: int PyFrozenSet_Check(PyObject *p) + + Return true if *p* is a :class:`frozenset` object or an instance of a + subtype. + +.. c:function:: int PyAnySet_Check(PyObject *p) + + Return true if *p* is a :class:`set` object, a :class:`frozenset` object, or an + instance of a subtype. + + +.. c:function:: int PyAnySet_CheckExact(PyObject *p) + + Return true if *p* is a :class:`set` object or a :class:`frozenset` object but + not an instance of a subtype. + + +.. c:function:: int PyFrozenSet_CheckExact(PyObject *p) + + Return true if *p* is a :class:`frozenset` object but not an instance of a + subtype. + + +.. c:function:: PyObject* PySet_New(PyObject *iterable) + + Return a new :class:`set` containing objects returned by the *iterable*. The + *iterable* may be ``NULL`` to create a new empty set. Return the new set on + success or ``NULL`` on failure. Raise :exc:`TypeError` if *iterable* is not + actually iterable. The constructor is also useful for copying a set + (``c=set(s)``). + + +.. c:function:: PyObject* PyFrozenSet_New(PyObject *iterable) + + Return a new :class:`frozenset` containing objects returned by the *iterable*. + The *iterable* may be ``NULL`` to create a new empty frozenset. Return the new + set on success or ``NULL`` on failure. Raise :exc:`TypeError` if *iterable* is + not actually iterable. + + +The following functions and macros are available for instances of :class:`set` +or :class:`frozenset` or instances of their subtypes. + + +.. c:function:: Py_ssize_t PySet_Size(PyObject *anyset) + + .. index:: builtin: len + + Return the length of a :class:`set` or :class:`frozenset` object. Equivalent to + ``len(anyset)``. Raises a :exc:`PyExc_SystemError` if *anyset* is not a + :class:`set`, :class:`frozenset`, or an instance of a subtype. + + +.. c:function:: Py_ssize_t PySet_GET_SIZE(PyObject *anyset) + + Macro form of :c:func:`PySet_Size` without error checking. + + +.. c:function:: int PySet_Contains(PyObject *anyset, PyObject *key) + + Return ``1`` if found, ``0`` if not found, and ``-1`` if an error is encountered. Unlike + the Python :meth:`__contains__` method, this function does not automatically + convert unhashable sets into temporary frozensets. Raise a :exc:`TypeError` if + the *key* is unhashable. Raise :exc:`PyExc_SystemError` if *anyset* is not a + :class:`set`, :class:`frozenset`, or an instance of a subtype. + + +.. c:function:: int PySet_Add(PyObject *set, PyObject *key) + + Add *key* to a :class:`set` instance. Also works with :class:`frozenset` + instances (like :c:func:`PyTuple_SetItem` it can be used to fill-in the values + of brand new frozensets before they are exposed to other code). Return ``0`` on + success or ``-1`` on failure. Raise a :exc:`TypeError` if the *key* is + unhashable. Raise a :exc:`MemoryError` if there is no room to grow. Raise a + :exc:`SystemError` if *set* is not an instance of :class:`set` or its + subtype. + + +The following functions are available for instances of :class:`set` or its +subtypes but not for instances of :class:`frozenset` or its subtypes. + + +.. c:function:: int PySet_Discard(PyObject *set, PyObject *key) + + Return ``1`` if found and removed, ``0`` if not found (no action taken), and ``-1`` if an + error is encountered. Does not raise :exc:`KeyError` for missing keys. Raise a + :exc:`TypeError` if the *key* is unhashable. Unlike the Python :meth:`~set.discard` + method, this function does not automatically convert unhashable sets into + temporary frozensets. Raise :exc:`PyExc_SystemError` if *set* is not an + instance of :class:`set` or its subtype. + + +.. c:function:: PyObject* PySet_Pop(PyObject *set) + + Return a new reference to an arbitrary object in the *set*, and removes the + object from the *set*. Return ``NULL`` on failure. Raise :exc:`KeyError` if the + set is empty. Raise a :exc:`SystemError` if *set* is not an instance of + :class:`set` or its subtype. + + +.. c:function:: int PySet_Clear(PyObject *set) + + Empty an existing set of all elements. diff --git a/cpython_2/environment/repo/Doc/c-api/slice.rst b/cpython_2/environment/repo/Doc/c-api/slice.rst new file mode 100644 index 0000000000000000000000000000000000000000..48a58c6c6f7e3652fe38ded7a9d4cac18e36cff1 --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/slice.rst @@ -0,0 +1,122 @@ +.. highlight:: c + +.. _slice-objects: + +Slice Objects +------------- + + +.. c:var:: PyTypeObject PySlice_Type + + The type object for slice objects. This is the same as :class:`slice` in the + Python layer. + + +.. c:function:: int PySlice_Check(PyObject *ob) + + Return true if *ob* is a slice object; *ob* must not be ``NULL``. + + +.. c:function:: PyObject* PySlice_New(PyObject *start, PyObject *stop, PyObject *step) + + Return a new slice object with the given values. The *start*, *stop*, and + *step* parameters are used as the values of the slice object attributes of + the same names. Any of the values may be ``NULL``, in which case the + ``None`` will be used for the corresponding attribute. Return ``NULL`` if + the new object could not be allocated. + + +.. c:function:: int PySlice_GetIndices(PyObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step) + + Retrieve the start, stop and step indices from the slice object *slice*, + assuming a sequence of length *length*. Treats indices greater than + *length* as errors. + + Returns ``0`` on success and ``-1`` on error with no exception set (unless one of + the indices was not :const:`None` and failed to be converted to an integer, + in which case ``-1`` is returned with an exception set). + + You probably do not want to use this function. + + .. versionchanged:: 3.2 + The parameter type for the *slice* parameter was ``PySliceObject*`` + before. + + +.. c:function:: 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) + + Usable replacement for :c:func:`PySlice_GetIndices`. Retrieve the start, + stop, and step indices from the slice object *slice* assuming a sequence of + length *length*, and store the length of the slice in *slicelength*. Out + of bounds indices are clipped in a manner consistent with the handling of + normal slices. + + Returns ``0`` on success and ``-1`` on error with exception set. + + .. note:: + This function is considered not safe for resizable sequences. + Its invocation should be replaced by a combination of + :c:func:`PySlice_Unpack` and :c:func:`PySlice_AdjustIndices` where :: + + if (PySlice_GetIndicesEx(slice, length, &start, &stop, &step, &slicelength) < 0) { + // return error + } + + is replaced by :: + + if (PySlice_Unpack(slice, &start, &stop, &step) < 0) { + // return error + } + slicelength = PySlice_AdjustIndices(length, &start, &stop, step); + + .. versionchanged:: 3.2 + The parameter type for the *slice* parameter was ``PySliceObject*`` + before. + + .. versionchanged:: 3.6.1 + If ``Py_LIMITED_API`` is not set or set to the value between ``0x03050400`` + and ``0x03060000`` (not including) or ``0x03060100`` or higher + :c:func:`!PySlice_GetIndicesEx` is implemented as a macro using + :c:func:`!PySlice_Unpack` and :c:func:`!PySlice_AdjustIndices`. + Arguments *start*, *stop* and *step* are evaluated more than once. + + .. deprecated:: 3.6.1 + If ``Py_LIMITED_API`` is set to the value less than ``0x03050400`` or + between ``0x03060000`` and ``0x03060100`` (not including) + :c:func:`!PySlice_GetIndicesEx` is a deprecated function. + + +.. c:function:: int PySlice_Unpack(PyObject *slice, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step) + + Extract the start, stop and step data members from a slice object as + C integers. Silently reduce values larger than ``PY_SSIZE_T_MAX`` to + ``PY_SSIZE_T_MAX``, silently boost the start and stop values less than + ``PY_SSIZE_T_MIN`` to ``PY_SSIZE_T_MIN``, and silently boost the step + values less than ``-PY_SSIZE_T_MAX`` to ``-PY_SSIZE_T_MAX``. + + Return ``-1`` on error, ``0`` on success. + + .. versionadded:: 3.6.1 + + +.. c:function:: Py_ssize_t PySlice_AdjustIndices(Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t step) + + Adjust start/end slice indices assuming a sequence of the specified length. + Out of bounds indices are clipped in a manner consistent with the handling + of normal slices. + + Return the length of the slice. Always successful. Doesn't call Python + code. + + .. versionadded:: 3.6.1 + + +Ellipsis Object +--------------- + + +.. c:var:: PyObject *Py_Ellipsis + + The Python ``Ellipsis`` object. This object has no methods. It needs to be + treated just like any other object with respect to reference counts. Like + :c:data:`Py_None` it is a singleton object. diff --git a/cpython_2/environment/repo/Doc/c-api/stable.rst b/cpython_2/environment/repo/Doc/c-api/stable.rst new file mode 100644 index 0000000000000000000000000000000000000000..9c05cb3c82dfbe8cc2f2bba24156100b8713aa09 --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/stable.rst @@ -0,0 +1,38 @@ +.. highlight:: c + +.. _stable: + +*********************************** +Stable Application Binary Interface +*********************************** + +Traditionally, the C API of Python will change with every release. Most changes +will be source-compatible, typically by only adding API, rather than changing +existing API or removing API (although some interfaces do get removed after +being deprecated first). + +Unfortunately, the API compatibility does not extend to binary compatibility +(the ABI). The reason is primarily the evolution of struct definitions, where +addition of a new field, or changing the type of a field, might not break the +API, but can break the ABI. As a consequence, extension modules need to be +recompiled for every Python release (although an exception is possible on Unix +when none of the affected interfaces are used). In addition, on Windows, +extension modules link with a specific pythonXY.dll and need to be recompiled to +link with a newer one. + +Since Python 3.2, a subset of the API has been declared to guarantee a stable +ABI. Extension modules wishing to use this API (called "limited API") need to +define ``Py_LIMITED_API``. A number of interpreter details then become hidden +from the extension module; in return, a module is built that works on any 3.x +version (x>=2) without recompilation. + +In some cases, the stable ABI needs to be extended with new functions. +Extension modules wishing to use these new APIs need to set ``Py_LIMITED_API`` +to the ``PY_VERSION_HEX`` value (see :ref:`apiabiversion`) of the minimum Python +version they want to support (e.g. ``0x03030000`` for Python 3.3). Such modules +will work on all subsequent Python releases, but fail to load (because of +missing symbols) on the older releases. + +As of Python 3.2, the set of functions available to the limited API is +documented in :pep:`384`. In the C API documentation, API elements that are not +part of the limited API are marked as "Not part of the limited API." diff --git a/cpython_2/environment/repo/Doc/c-api/structures.rst b/cpython_2/environment/repo/Doc/c-api/structures.rst new file mode 100644 index 0000000000000000000000000000000000000000..634e971952e8eb4e99f2b5b0be410ac35089eb98 --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/structures.rst @@ -0,0 +1,476 @@ +.. highlight:: c + +.. _common-structs: + +Common Object Structures +======================== + +There are a large number of structures which are used in the definition of +object types for Python. This section describes these structures and how they +are used. + + +Base object types and macros +---------------------------- + +All Python objects ultimately share a small number of fields at the beginning +of the object's representation in memory. These are represented by the +:c:type:`PyObject` and :c:type:`PyVarObject` types, which are defined, in turn, +by the expansions of some macros also used, whether directly or indirectly, in +the definition of all other Python objects. + + +.. c:type:: PyObject + + All object types are extensions of this type. This is a type which + contains the information Python needs to treat a pointer to an object as an + object. In a normal "release" build, it contains only the object's + reference count and a pointer to the corresponding type object. + Nothing is actually declared to be a :c:type:`PyObject`, but every pointer + to a Python object can be cast to a :c:type:`PyObject*`. Access to the + members must be done by using the macros :c:macro:`Py_REFCNT` and + :c:macro:`Py_TYPE`. + + +.. c:type:: PyVarObject + + This is an extension of :c:type:`PyObject` that adds the :attr:`ob_size` + field. This is only used for objects that have some notion of *length*. + This type does not often appear in the Python/C API. + Access to the members must be done by using the macros + :c:macro:`Py_REFCNT`, :c:macro:`Py_TYPE`, and :c:macro:`Py_SIZE`. + + +.. c:macro:: PyObject_HEAD + + This is a macro used when declaring new types which represent objects + without a varying length. The PyObject_HEAD macro expands to:: + + PyObject ob_base; + + See documentation of :c:type:`PyObject` above. + + +.. c:macro:: PyObject_VAR_HEAD + + This is a macro used when declaring new types which represent objects + with a length that varies from instance to instance. + The PyObject_VAR_HEAD macro expands to:: + + PyVarObject ob_base; + + See documentation of :c:type:`PyVarObject` above. + + +.. c:macro:: Py_TYPE(o) + + This macro is used to access the :attr:`ob_type` member of a Python object. + It expands to:: + + (((PyObject*)(o))->ob_type) + + +.. c:function:: int Py_IS_TYPE(PyObject *o, PyTypeObject *type) + + Return non-zero if the object *o* type is *type*. Return zero otherwise. + Equivalent to: ``Py_TYPE(o) == type``. + + .. versionadded:: 3.9 + + +.. c:function:: void Py_SET_TYPE(PyObject *o, PyTypeObject *type) + + Set the object *o* type to *type*. + + .. versionadded:: 3.9 + + +.. c:macro:: Py_REFCNT(o) + + This macro is used to access the :attr:`ob_refcnt` member of a Python + object. + It expands to:: + + (((PyObject*)(o))->ob_refcnt) + + +.. c:function:: void Py_SET_REFCNT(PyObject *o, Py_ssize_t refcnt) + + Set the object *o* reference counter to *refcnt*. + + .. versionadded:: 3.9 + + +.. c:macro:: Py_SIZE(o) + + This macro is used to access the :attr:`ob_size` member of a Python object. + It expands to:: + + (((PyVarObject*)(o))->ob_size) + + +.. c:function:: void Py_SET_SIZE(PyVarObject *o, Py_ssize_t size) + + Set the object *o* size to *size*. + + .. versionadded:: 3.9 + + +.. c:macro:: PyObject_HEAD_INIT(type) + + This is a macro which expands to initialization values for a new + :c:type:`PyObject` type. This macro expands to:: + + _PyObject_EXTRA_INIT + 1, type, + + +.. c:macro:: PyVarObject_HEAD_INIT(type, size) + + This is a macro which expands to initialization values for a new + :c:type:`PyVarObject` type, including the :attr:`ob_size` field. + This macro expands to:: + + _PyObject_EXTRA_INIT + 1, type, size, + + +Implementing functions and methods +---------------------------------- + +.. c:type:: PyCFunction + + Type of the functions used to implement most Python callables in C. + Functions of this type take two :c:type:`PyObject\*` parameters and return + one such value. If the return value is ``NULL``, an exception shall have + been set. If not ``NULL``, the return value is interpreted as the return + value of the function as exposed in Python. The function must return a new + reference. + + The function signature is:: + + PyObject *PyCFunction(PyObject *self, + PyObject *args); + +.. c:type:: PyCFunctionWithKeywords + + Type of the functions used to implement Python callables in C + with signature :const:`METH_VARARGS | METH_KEYWORDS`. + The function signature is:: + + PyObject *PyCFunctionWithKeywords(PyObject *self, + PyObject *args, + PyObject *kwargs); + + +.. c:type:: _PyCFunctionFast + + Type of the functions used to implement Python callables in C + with signature :const:`METH_FASTCALL`. + The function signature is:: + + PyObject *_PyCFunctionFast(PyObject *self, + PyObject *const *args, + Py_ssize_t nargs); + +.. c:type:: _PyCFunctionFastWithKeywords + + Type of the functions used to implement Python callables in C + with signature :const:`METH_FASTCALL | METH_KEYWORDS`. + The function signature is:: + + PyObject *_PyCFunctionFastWithKeywords(PyObject *self, + PyObject *const *args, + Py_ssize_t nargs, + PyObject *kwnames); + +.. c:type:: PyCMethod + + Type of the functions used to implement Python callables in C + with signature :const:`METH_METHOD | METH_FASTCALL | METH_KEYWORDS`. + The function signature is:: + + PyObject *PyCMethod(PyObject *self, + PyTypeObject *defining_class, + PyObject *const *args, + Py_ssize_t nargs, + PyObject *kwnames) + + .. versionadded:: 3.9 + + +.. c:type:: PyMethodDef + + Structure used to describe a method of an extension type. This structure has + four fields: + + +------------------+---------------+-------------------------------+ + | Field | C Type | Meaning | + +==================+===============+===============================+ + | :attr:`ml_name` | const char \* | name of the method | + +------------------+---------------+-------------------------------+ + | :attr:`ml_meth` | PyCFunction | pointer to the C | + | | | implementation | + +------------------+---------------+-------------------------------+ + | :attr:`ml_flags` | int | flag bits indicating how the | + | | | call should be constructed | + +------------------+---------------+-------------------------------+ + | :attr:`ml_doc` | const char \* | points to the contents of the | + | | | docstring | + +------------------+---------------+-------------------------------+ + +The :attr:`ml_meth` is a C function pointer. The functions may be of different +types, but they always return :c:type:`PyObject\*`. If the function is not of +the :c:type:`PyCFunction`, the compiler will require a cast in the method table. +Even though :c:type:`PyCFunction` defines the first parameter as +:c:type:`PyObject\*`, it is common that the method implementation uses the +specific C type of the *self* object. + +The :attr:`ml_flags` field is a bitfield which can include the following flags. +The individual flags indicate either a calling convention or a binding +convention. + +There are these calling conventions: + +.. data:: METH_VARARGS + + This is the typical calling convention, where the methods have the type + :c:type:`PyCFunction`. The function expects two :c:type:`PyObject\*` values. + The first one is the *self* object for methods; for module functions, it is + the module object. The second parameter (often called *args*) is a tuple + object representing all arguments. This parameter is typically processed + using :c:func:`PyArg_ParseTuple` or :c:func:`PyArg_UnpackTuple`. + + +.. data:: METH_VARARGS | METH_KEYWORDS + + Methods with these flags must be of type :c:type:`PyCFunctionWithKeywords`. + The function expects three parameters: *self*, *args*, *kwargs* where + *kwargs* is a dictionary of all the keyword arguments or possibly ``NULL`` + if there are no keyword arguments. The parameters are typically processed + using :c:func:`PyArg_ParseTupleAndKeywords`. + + +.. data:: METH_FASTCALL + + Fast calling convention supporting only positional arguments. + The methods have the type :c:type:`_PyCFunctionFast`. + The first parameter is *self*, the second parameter is a C array + of :c:type:`PyObject\*` values indicating the arguments and the third + parameter is the number of arguments (the length of the array). + + This is not part of the :ref:`limited API `. + + .. versionadded:: 3.7 + + +.. data:: METH_FASTCALL | METH_KEYWORDS + + Extension of :const:`METH_FASTCALL` supporting also keyword arguments, + with methods of type :c:type:`_PyCFunctionFastWithKeywords`. + Keyword arguments are passed the same way as in the + :ref:`vectorcall protocol `: + there is an additional fourth :c:type:`PyObject\*` parameter + which is a tuple representing the names of the keyword arguments + (which are guaranteed to be strings) + or possibly ``NULL`` if there are no keywords. The values of the keyword + arguments are stored in the *args* array, after the positional arguments. + + This is not part of the :ref:`limited API `. + + .. versionadded:: 3.7 + + +.. data:: METH_METHOD | METH_FASTCALL | METH_KEYWORDS + + Extension of :const:`METH_FASTCALL | METH_KEYWORDS` supporting the *defining + class*, that is, the class that contains the method in question. + The defining class might be a superclass of ``Py_TYPE(self)``. + + The method needs to be of type :c:type:`PyCMethod`, the same as for + ``METH_FASTCALL | METH_KEYWORDS`` with ``defining_class`` argument added after + ``self``. + + .. versionadded:: 3.9 + + +.. data:: METH_NOARGS + + Methods without parameters don't need to check whether arguments are given if + they are listed with the :const:`METH_NOARGS` flag. They need to be of type + :c:type:`PyCFunction`. The first parameter is typically named *self* and will + hold a reference to the module or object instance. In all cases the second + parameter will be ``NULL``. + + +.. data:: METH_O + + Methods with a single object argument can be listed with the :const:`METH_O` + flag, instead of invoking :c:func:`PyArg_ParseTuple` with a ``"O"`` argument. + They have the type :c:type:`PyCFunction`, with the *self* parameter, and a + :c:type:`PyObject\*` parameter representing the single argument. + + +These two constants are not used to indicate the calling convention but the +binding when use with methods of classes. These may not be used for functions +defined for modules. At most one of these flags may be set for any given +method. + + +.. data:: METH_CLASS + + .. index:: builtin: classmethod + + The method will be passed the type object as the first parameter rather + than an instance of the type. This is used to create *class methods*, + similar to what is created when using the :func:`classmethod` built-in + function. + + +.. data:: METH_STATIC + + .. index:: builtin: staticmethod + + The method will be passed ``NULL`` as the first parameter rather than an + instance of the type. This is used to create *static methods*, similar to + what is created when using the :func:`staticmethod` built-in function. + +One other constant controls whether a method is loaded in place of another +definition with the same method name. + + +.. data:: METH_COEXIST + + The method will be loaded in place of existing definitions. Without + *METH_COEXIST*, the default is to skip repeated definitions. Since slot + wrappers are loaded before the method table, the existence of a + *sq_contains* slot, for example, would generate a wrapped method named + :meth:`__contains__` and preclude the loading of a corresponding + PyCFunction with the same name. With the flag defined, the PyCFunction + will be loaded in place of the wrapper object and will co-exist with the + slot. This is helpful because calls to PyCFunctions are optimized more + than wrapper object calls. + + +Accessing attributes of extension types +--------------------------------------- + +.. c:type:: PyMemberDef + + Structure which describes an attribute of a type which corresponds to a C + struct member. Its fields are: + + +------------------+---------------+-------------------------------+ + | Field | C Type | Meaning | + +==================+===============+===============================+ + | :attr:`name` | const char \* | name of the member | + +------------------+---------------+-------------------------------+ + | :attr:`!type` | int | the type of the member in the | + | | | C struct | + +------------------+---------------+-------------------------------+ + | :attr:`offset` | Py_ssize_t | the offset in bytes that the | + | | | member is located on the | + | | | type's object struct | + +------------------+---------------+-------------------------------+ + | :attr:`flags` | int | flag bits indicating if the | + | | | field should be read-only or | + | | | writable | + +------------------+---------------+-------------------------------+ + | :attr:`doc` | const char \* | points to the contents of the | + | | | docstring | + +------------------+---------------+-------------------------------+ + + :attr:`!type` can be one of many ``T_`` macros corresponding to various C + types. When the member is accessed in Python, it will be converted to the + equivalent Python type. + + =============== ================== + Macro name C type + =============== ================== + T_SHORT short + T_INT int + T_LONG long + T_FLOAT float + T_DOUBLE double + T_STRING const char \* + T_OBJECT PyObject \* + T_OBJECT_EX PyObject \* + T_CHAR char + T_BYTE char + T_UBYTE unsigned char + T_UINT unsigned int + T_USHORT unsigned short + T_ULONG unsigned long + T_BOOL char + T_LONGLONG long long + T_ULONGLONG unsigned long long + T_PYSSIZET Py_ssize_t + =============== ================== + + :c:macro:`T_OBJECT` and :c:macro:`T_OBJECT_EX` differ in that + :c:macro:`T_OBJECT` returns ``None`` if the member is ``NULL`` and + :c:macro:`T_OBJECT_EX` raises an :exc:`AttributeError`. Try to use + :c:macro:`T_OBJECT_EX` over :c:macro:`T_OBJECT` because :c:macro:`T_OBJECT_EX` + handles use of the :keyword:`del` statement on that attribute more correctly + than :c:macro:`T_OBJECT`. + + :attr:`flags` can be ``0`` for write and read access or :c:macro:`READONLY` for + read-only access. Using :c:macro:`T_STRING` for :attr:`type` implies + :c:macro:`READONLY`. :c:macro:`T_STRING` data is interpreted as UTF-8. + Only :c:macro:`T_OBJECT` and :c:macro:`T_OBJECT_EX` + members can be deleted. (They are set to ``NULL``). + + .. _pymemberdef-offsets: + + Heap allocated types (created using :c:func:`PyType_FromSpec` or similar), + ``PyMemberDef`` may contain definitions for the special members + ``__dictoffset__``, ``__weaklistoffset__`` and ``__vectorcalloffset__``, + corresponding to + :c:member:`~PyTypeObject.tp_dictoffset`, + :c:member:`~PyTypeObject.tp_weaklistoffset` and + :c:member:`~PyTypeObject.tp_vectorcall_offset` in type objects. + These must be defined with ``T_PYSSIZET`` and ``READONLY``, for example:: + + static PyMemberDef spam_type_members[] = { + {"__dictoffset__", T_PYSSIZET, offsetof(Spam_object, dict), READONLY}, + {NULL} /* Sentinel */ + }; + +.. c:type:: PyGetSetDef + + Structure to define property-like access for a type. See also description of + the :c:member:`PyTypeObject.tp_getset` slot. + + +-------------+------------------+-----------------------------------+ + | Field | C Type | Meaning | + +=============+==================+===================================+ + | name | const char \* | attribute name | + +-------------+------------------+-----------------------------------+ + | get | getter | C Function to get the attribute | + +-------------+------------------+-----------------------------------+ + | set | setter | optional C function to set or | + | | | delete the attribute, if omitted | + | | | the attribute is readonly | + +-------------+------------------+-----------------------------------+ + | doc | const char \* | optional docstring | + +-------------+------------------+-----------------------------------+ + | closure | void \* | optional function pointer, | + | | | providing additional data for | + | | | getter and setter | + +-------------+------------------+-----------------------------------+ + + The ``get`` function takes one :c:type:`PyObject\*` parameter (the + instance) and a function pointer (the associated ``closure``):: + + typedef PyObject *(*getter)(PyObject *, void *); + + It should return a new reference on success or ``NULL`` with a set exception + on failure. + + ``set`` functions take two :c:type:`PyObject\*` parameters (the instance and + the value to be set) and a function pointer (the associated ``closure``):: + + typedef int (*setter)(PyObject *, PyObject *, void *); + + In case the attribute should be deleted the second parameter is ``NULL``. + Should return ``0`` on success or ``-1`` with a set exception on failure. diff --git a/cpython_2/environment/repo/Doc/c-api/sys.rst b/cpython_2/environment/repo/Doc/c-api/sys.rst new file mode 100644 index 0000000000000000000000000000000000000000..9ac91790978926478b1740919473443d40eb7c77 --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/sys.rst @@ -0,0 +1,425 @@ +.. highlight:: c + +.. _os: + +Operating System Utilities +========================== + +.. c:function:: PyObject* PyOS_FSPath(PyObject *path) + + Return the file system representation for *path*. If the object is a + :class:`str` or :class:`bytes` object, then its reference count is + incremented. If the object implements the :class:`os.PathLike` interface, + then :meth:`~os.PathLike.__fspath__` is returned as long as it is a + :class:`str` or :class:`bytes` object. Otherwise :exc:`TypeError` is raised + and ``NULL`` is returned. + + .. versionadded:: 3.6 + + +.. c:function:: int Py_FdIsInteractive(FILE *fp, const char *filename) + + Return true (nonzero) if the standard I/O file *fp* with name *filename* is + deemed interactive. This is the case for files for which ``isatty(fileno(fp))`` + is true. If the global flag :c:data:`Py_InteractiveFlag` is true, this function + also returns true if the *filename* pointer is ``NULL`` or if the name is equal to + one of the strings ``''`` or ``'???'``. + + +.. c:function:: void PyOS_BeforeFork() + + Function to prepare some internal state before a process fork. This + should be called before calling :c:func:`fork` or any similar function + that clones the current process. + Only available on systems where :c:func:`fork` is defined. + + .. warning:: + The C :c:func:`fork` call should only be made from the + :ref:`"main" thread ` (of the + :ref:`"main" interpreter `). The same is + true for ``PyOS_BeforeFork()``. + + .. versionadded:: 3.7 + + +.. c:function:: void PyOS_AfterFork_Parent() + + Function to update some internal state after a process fork. This + should be called from the parent process after calling :c:func:`fork` + or any similar function that clones the current process, regardless + of whether process cloning was successful. + Only available on systems where :c:func:`fork` is defined. + + .. warning:: + The C :c:func:`fork` call should only be made from the + :ref:`"main" thread ` (of the + :ref:`"main" interpreter `). The same is + true for ``PyOS_AfterFork_Parent()``. + + .. versionadded:: 3.7 + + +.. c:function:: void PyOS_AfterFork_Child() + + Function to update internal interpreter state after a process fork. + This must be called from the child process after calling :c:func:`fork`, + or any similar function that clones the current process, if there is + any chance the process will call back into the Python interpreter. + Only available on systems where :c:func:`fork` is defined. + + .. warning:: + The C :c:func:`fork` call should only be made from the + :ref:`"main" thread ` (of the + :ref:`"main" interpreter `). The same is + true for ``PyOS_AfterFork_Child()``. + + .. versionadded:: 3.7 + + .. seealso:: + :func:`os.register_at_fork` allows registering custom Python functions + to be called by :c:func:`PyOS_BeforeFork()`, + :c:func:`PyOS_AfterFork_Parent` and :c:func:`PyOS_AfterFork_Child`. + + +.. c:function:: void PyOS_AfterFork() + + Function to update some internal state after a process fork; this should be + called in the new process if the Python interpreter will continue to be used. + If a new executable is loaded into the new process, this function does not need + to be called. + + .. deprecated:: 3.7 + This function is superseded by :c:func:`PyOS_AfterFork_Child()`. + + +.. c:function:: int PyOS_CheckStack() + + Return true when the interpreter runs out of stack space. This is a reliable + check, but is only available when :const:`USE_STACKCHECK` is defined (currently + on Windows using the Microsoft Visual C++ compiler). :const:`USE_STACKCHECK` + will be defined automatically; you should never change the definition in your + own code. + + +.. c:function:: PyOS_sighandler_t PyOS_getsig(int i) + + Return the current signal handler for signal *i*. This is a thin wrapper around + either :c:func:`sigaction` or :c:func:`signal`. Do not call those functions + directly! :c:type:`PyOS_sighandler_t` is a typedef alias for :c:type:`void + (\*)(int)`. + + +.. c:function:: PyOS_sighandler_t PyOS_setsig(int i, PyOS_sighandler_t h) + + Set the signal handler for signal *i* to be *h*; return the old signal handler. + This is a thin wrapper around either :c:func:`sigaction` or :c:func:`signal`. Do + not call those functions directly! :c:type:`PyOS_sighandler_t` is a typedef + alias for :c:type:`void (\*)(int)`. + +.. c:function:: wchar_t* Py_DecodeLocale(const char* arg, size_t *size) + + Decode a byte string from the locale encoding with the :ref:`surrogateescape + error handler `: undecodable bytes are decoded as + characters in range U+DC80..U+DCFF. If a byte sequence can be decoded as a + surrogate character, escape the bytes using the surrogateescape error + handler instead of decoding them. + + Encoding, highest priority to lowest priority: + + * ``UTF-8`` on macOS, Android, and VxWorks; + * ``UTF-8`` on Windows if :c:data:`Py_LegacyWindowsFSEncodingFlag` is zero; + * ``UTF-8`` if the Python UTF-8 mode is enabled; + * ``ASCII`` if the ``LC_CTYPE`` locale is ``"C"``, + ``nl_langinfo(CODESET)`` returns the ``ASCII`` encoding (or an alias), + and :c:func:`mbstowcs` and :c:func:`wcstombs` functions uses the + ``ISO-8859-1`` encoding. + * the current locale encoding. + + Return a pointer to a newly allocated wide character string, use + :c:func:`PyMem_RawFree` to free the memory. If size is not ``NULL``, write + the number of wide characters excluding the null character into ``*size`` + + Return ``NULL`` on decoding error or memory allocation error. If *size* is + not ``NULL``, ``*size`` is set to ``(size_t)-1`` on memory error or set to + ``(size_t)-2`` on decoding error. + + Decoding errors should never happen, unless there is a bug in the C + library. + + Use the :c:func:`Py_EncodeLocale` function to encode the character string + back to a byte string. + + .. seealso:: + + The :c:func:`PyUnicode_DecodeFSDefaultAndSize` and + :c:func:`PyUnicode_DecodeLocaleAndSize` functions. + + .. versionadded:: 3.5 + + .. versionchanged:: 3.7 + The function now uses the UTF-8 encoding in the UTF-8 mode. + + .. versionchanged:: 3.8 + The function now uses the UTF-8 encoding on Windows if + :c:data:`Py_LegacyWindowsFSEncodingFlag` is zero; + + +.. c:function:: char* Py_EncodeLocale(const wchar_t *text, size_t *error_pos) + + Encode a wide character string to the locale encoding with the + :ref:`surrogateescape error handler `: surrogate characters + in the range U+DC80..U+DCFF are converted to bytes 0x80..0xFF. + + Encoding, highest priority to lowest priority: + + * ``UTF-8`` on macOS, Android, and VxWorks; + * ``UTF-8`` on Windows if :c:data:`Py_LegacyWindowsFSEncodingFlag` is zero; + * ``UTF-8`` if the Python UTF-8 mode is enabled; + * ``ASCII`` if the ``LC_CTYPE`` locale is ``"C"``, + ``nl_langinfo(CODESET)`` returns the ``ASCII`` encoding (or an alias), + and :c:func:`mbstowcs` and :c:func:`wcstombs` functions uses the + ``ISO-8859-1`` encoding. + * the current locale encoding. + + The function uses the UTF-8 encoding in the Python UTF-8 mode. + + Return a pointer to a newly allocated byte string, use :c:func:`PyMem_Free` + to free the memory. Return ``NULL`` on encoding error or memory allocation + error + + If error_pos is not ``NULL``, ``*error_pos`` is set to ``(size_t)-1`` on + success, or set to the index of the invalid character on encoding error. + + Use the :c:func:`Py_DecodeLocale` function to decode the bytes string back + to a wide character string. + + .. seealso:: + + The :c:func:`PyUnicode_EncodeFSDefault` and + :c:func:`PyUnicode_EncodeLocale` functions. + + .. versionadded:: 3.5 + + .. versionchanged:: 3.7 + The function now uses the UTF-8 encoding in the UTF-8 mode. + + .. versionchanged:: 3.8 + The function now uses the UTF-8 encoding on Windows if + :c:data:`Py_LegacyWindowsFSEncodingFlag` is zero; + + +.. _systemfunctions: + +System Functions +================ + +These are utility functions that make functionality from the :mod:`sys` module +accessible to C code. They all work with the current interpreter thread's +:mod:`sys` module's dict, which is contained in the internal thread state structure. + +.. c:function:: PyObject *PySys_GetObject(const char *name) + + Return the object *name* from the :mod:`sys` module or ``NULL`` if it does + not exist, without setting an exception. + +.. c:function:: int PySys_SetObject(const char *name, PyObject *v) + + Set *name* in the :mod:`sys` module to *v* unless *v* is ``NULL``, in which + case *name* is deleted from the sys module. Returns ``0`` on success, ``-1`` + on error. + +.. c:function:: void PySys_ResetWarnOptions() + + Reset :data:`sys.warnoptions` to an empty list. This function may be + called prior to :c:func:`Py_Initialize`. + +.. c:function:: void PySys_AddWarnOption(const wchar_t *s) + + Append *s* to :data:`sys.warnoptions`. This function must be called prior + to :c:func:`Py_Initialize` in order to affect the warnings filter list. + +.. c:function:: void PySys_AddWarnOptionUnicode(PyObject *unicode) + + Append *unicode* to :data:`sys.warnoptions`. + + Note: this function is not currently usable from outside the CPython + implementation, as it must be called prior to the implicit import of + :mod:`warnings` in :c:func:`Py_Initialize` to be effective, but can't be + called until enough of the runtime has been initialized to permit the + creation of Unicode objects. + +.. c:function:: void PySys_SetPath(const wchar_t *path) + + Set :data:`sys.path` to a list object of paths found in *path* which should + be a list of paths separated with the platform's search path delimiter + (``:`` on Unix, ``;`` on Windows). + +.. c:function:: void PySys_WriteStdout(const char *format, ...) + + Write the output string described by *format* to :data:`sys.stdout`. No + exceptions are raised, even if truncation occurs (see below). + + *format* should limit the total size of the formatted output string to + 1000 bytes or less -- after 1000 bytes, the output string is truncated. + In particular, this means that no unrestricted "%s" formats should occur; + these should be limited using "%.s" where is a decimal number + calculated so that plus the maximum size of other formatted text does not + exceed 1000 bytes. Also watch out for "%f", which can print hundreds of + digits for very large numbers. + + If a problem occurs, or :data:`sys.stdout` is unset, the formatted message + is written to the real (C level) *stdout*. + +.. c:function:: void PySys_WriteStderr(const char *format, ...) + + As :c:func:`PySys_WriteStdout`, but write to :data:`sys.stderr` or *stderr* + instead. + +.. c:function:: void PySys_FormatStdout(const char *format, ...) + + Function similar to PySys_WriteStdout() but format the message using + :c:func:`PyUnicode_FromFormatV` and don't truncate the message to an + arbitrary length. + + .. versionadded:: 3.2 + +.. c:function:: void PySys_FormatStderr(const char *format, ...) + + As :c:func:`PySys_FormatStdout`, but write to :data:`sys.stderr` or *stderr* + instead. + + .. versionadded:: 3.2 + +.. c:function:: void PySys_AddXOption(const wchar_t *s) + + Parse *s* as a set of :option:`-X` options and add them to the current + options mapping as returned by :c:func:`PySys_GetXOptions`. This function + may be called prior to :c:func:`Py_Initialize`. + + .. versionadded:: 3.2 + +.. c:function:: PyObject *PySys_GetXOptions() + + Return the current dictionary of :option:`-X` options, similarly to + :data:`sys._xoptions`. On error, ``NULL`` is returned and an exception is + set. + + .. versionadded:: 3.2 + + +.. c:function:: int PySys_Audit(const char *event, const char *format, ...) + + Raise an auditing event with any active hooks. Return zero for success + and non-zero with an exception set on failure. + + If any hooks have been added, *format* and other arguments will be used + to construct a tuple to pass. Apart from ``N``, the same format characters + as used in :c:func:`Py_BuildValue` are available. If the built value is not + a tuple, it will be added into a single-element tuple. (The ``N`` format + option consumes a reference, but since there is no way to know whether + arguments to this function will be consumed, using it may cause reference + leaks.) + + Note that ``#`` format characters should always be treated as + ``Py_ssize_t``, regardless of whether ``PY_SSIZE_T_CLEAN`` was defined. + + :func:`sys.audit` performs the same function from Python code. + + .. versionadded:: 3.8 + + .. versionchanged:: 3.8.2 + + Require ``Py_ssize_t`` for ``#`` format characters. Previously, an + unavoidable deprecation warning was raised. + + +.. c:function:: int PySys_AddAuditHook(Py_AuditHookFunction hook, void *userData) + + Append the callable *hook* to the list of active auditing hooks. + Return zero for success + and non-zero on failure. If the runtime has been initialized, also set an + error on failure. Hooks added through this API are called for all + interpreters created by the runtime. + + The *userData* pointer is passed into the hook function. Since hook + functions may be called from different runtimes, this pointer should not + refer directly to Python state. + + This function is safe to call before :c:func:`Py_Initialize`. When called + after runtime initialization, existing audit hooks are notified and may + silently abort the operation by raising an error subclassed from + :class:`Exception` (other errors will not be silenced). + + The hook function is of type :c:type:`int (*)(const char *event, PyObject + *args, void *userData)`, where *args* is guaranteed to be a + :c:type:`PyTupleObject`. The hook function is always called with the GIL + held by the Python interpreter that raised the event. + + See :pep:`578` for a detailed description of auditing. Functions in the + runtime and standard library that raise events are listed in the + :ref:`audit events table `. + Details are in each function's documentation. + + .. audit-event:: sys.addaudithook "" c.PySys_AddAuditHook + + If the interpreter is initialized, this function raises a auditing event + ``sys.addaudithook`` with no arguments. If any existing hooks raise an + exception derived from :class:`Exception`, the new hook will not be + added and the exception is cleared. As a result, callers cannot assume + that their hook has been added unless they control all existing hooks. + + .. versionadded:: 3.8 + + +.. _processcontrol: + +Process Control +=============== + + +.. c:function:: void Py_FatalError(const char *message) + + .. index:: single: abort() + + 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 + make it dangerous to continue using the Python interpreter; e.g., when the + object administration appears to be corrupted. On Unix, the standard C library + function :c:func:`abort` is called which will attempt to produce a :file:`core` + file. + + 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. + + .. versionchanged:: 3.9 + Log the function name automatically. + + +.. c:function:: void Py_Exit(int status) + + .. index:: + single: Py_FinalizeEx() + single: exit() + + 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` + indicates an error, the exit status is set to 120. + + .. versionchanged:: 3.6 + Errors from finalization no longer ignored. + + +.. c:function:: int Py_AtExit(void (*func) ()) + + .. index:: + single: Py_FinalizeEx() + single: cleanup functions + + Register a cleanup function to be called by :c:func:`Py_FinalizeEx`. The cleanup + function will be called with no arguments and should return no value. At most + 32 cleanup functions can be registered. When the registration is successful, + :c:func:`Py_AtExit` returns ``0``; on failure, it returns ``-1``. The cleanup + function registered last is called first. Each cleanup function will be called + at most once. Since Python's internal finalization will have completed before + the cleanup function, no Python APIs should be called by *func*. diff --git a/cpython_2/environment/repo/Doc/c-api/tuple.rst b/cpython_2/environment/repo/Doc/c-api/tuple.rst new file mode 100644 index 0000000000000000000000000000000000000000..c14cb2d38fd54abfe0016132e466e59fd48fe5fc --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/tuple.rst @@ -0,0 +1,222 @@ +.. highlight:: c + +.. _tupleobjects: + +Tuple Objects +------------- + +.. index:: object: tuple + + +.. c:type:: PyTupleObject + + This subtype of :c:type:`PyObject` represents a Python tuple object. + + +.. c:var:: PyTypeObject PyTuple_Type + + This instance of :c:type:`PyTypeObject` represents the Python tuple type; it + is the same object as :class:`tuple` in the Python layer. + + +.. c:function:: int PyTuple_Check(PyObject *p) + + Return true if *p* is a tuple object or an instance of a subtype of the tuple + type. + + +.. c:function:: int PyTuple_CheckExact(PyObject *p) + + Return true if *p* is a tuple object, but not an instance of a subtype of the + tuple type. + + +.. c:function:: PyObject* PyTuple_New(Py_ssize_t len) + + Return a new tuple object of size *len*, or ``NULL`` on failure. + + +.. c:function:: PyObject* PyTuple_Pack(Py_ssize_t n, ...) + + Return a new tuple object of size *n*, or ``NULL`` on failure. The tuple values + are initialized to the subsequent *n* C arguments pointing to Python objects. + ``PyTuple_Pack(2, a, b)`` is equivalent to ``Py_BuildValue("(OO)", a, b)``. + + +.. c:function:: Py_ssize_t PyTuple_Size(PyObject *p) + + Take a pointer to a tuple object, and return the size of that tuple. + + +.. c:function:: Py_ssize_t PyTuple_GET_SIZE(PyObject *p) + + Return the size of the tuple *p*, which must be non-``NULL`` and point to a tuple; + no error checking is performed. + + +.. c:function:: PyObject* PyTuple_GetItem(PyObject *p, Py_ssize_t pos) + + Return the object at position *pos* in the tuple pointed to by *p*. If *pos* is + out of bounds, return ``NULL`` and set an :exc:`IndexError` exception. + + +.. c:function:: PyObject* PyTuple_GET_ITEM(PyObject *p, Py_ssize_t pos) + + Like :c:func:`PyTuple_GetItem`, but does no checking of its arguments. + + +.. c:function:: PyObject* PyTuple_GetSlice(PyObject *p, Py_ssize_t low, Py_ssize_t high) + + Return the slice of the tuple pointed to by *p* between *low* and *high*, + or ``NULL`` on failure. This is the equivalent of the Python expression + ``p[low:high]``. Indexing from the end of the list is not supported. + + +.. c:function:: int PyTuple_SetItem(PyObject *p, Py_ssize_t pos, PyObject *o) + + Insert a reference to object *o* at position *pos* of the tuple pointed to by + *p*. Return ``0`` on success. If *pos* is out of bounds, return ``-1`` + and set an :exc:`IndexError` exception. + + .. note:: + + This function "steals" a reference to *o* and discards a reference to + an item already in the tuple at the affected position. + + +.. c:function:: void PyTuple_SET_ITEM(PyObject *p, Py_ssize_t pos, PyObject *o) + + Like :c:func:`PyTuple_SetItem`, but does no error checking, and should *only* be + used to fill in brand new tuples. + + .. note:: + + This macro "steals" a reference to *o*, and, unlike + :c:func:`PyTuple_SetItem`, does *not* discard a reference to any item that + is being replaced; any reference in the tuple at position *pos* will be + leaked. + + +.. c:function:: int _PyTuple_Resize(PyObject **p, Py_ssize_t newsize) + + Can be used to resize a tuple. *newsize* will be the new length of the tuple. + Because tuples are *supposed* to be immutable, this should only be used if there + is only one reference to the object. Do *not* use this if the tuple may already + be known to some other part of the code. The tuple will always grow or shrink + at the end. Think of this as destroying the old tuple and creating a new one, + only more efficiently. Returns ``0`` on success. Client code should never + assume that the resulting value of ``*p`` will be the same as before calling + this function. If the object referenced by ``*p`` is replaced, the original + ``*p`` is destroyed. On failure, returns ``-1`` and sets ``*p`` to ``NULL``, and + raises :exc:`MemoryError` or :exc:`SystemError`. + + +Struct Sequence Objects +----------------------- + +Struct sequence objects are the C equivalent of :func:`~collections.namedtuple` +objects, i.e. a sequence whose items can also be accessed through attributes. +To create a struct sequence, you first have to create a specific struct sequence +type. + +.. c:function:: PyTypeObject* PyStructSequence_NewType(PyStructSequence_Desc *desc) + + Create a new struct sequence type from the data in *desc*, described below. Instances + of the resulting type can be created with :c:func:`PyStructSequence_New`. + + +.. c:function:: void PyStructSequence_InitType(PyTypeObject *type, PyStructSequence_Desc *desc) + + Initializes a struct sequence type *type* from *desc* in place. + + +.. c:function:: int PyStructSequence_InitType2(PyTypeObject *type, PyStructSequence_Desc *desc) + + The same as ``PyStructSequence_InitType``, but returns ``0`` on success and ``-1`` on + failure. + + .. versionadded:: 3.4 + + +.. c:type:: PyStructSequence_Desc + + Contains the meta information of a struct sequence type to create. + + +-------------------+------------------------------+--------------------------------------+ + | Field | C Type | Meaning | + +===================+==============================+======================================+ + | ``name`` | ``const char *`` | name of the struct sequence type | + +-------------------+------------------------------+--------------------------------------+ + | ``doc`` | ``const char *`` | pointer to docstring for the type | + | | | or ``NULL`` to omit | + +-------------------+------------------------------+--------------------------------------+ + | ``fields`` | ``PyStructSequence_Field *`` | pointer to ``NULL``-terminated array | + | | | with field names of the new type | + +-------------------+------------------------------+--------------------------------------+ + | ``n_in_sequence`` | ``int`` | number of fields visible to the | + | | | Python side (if used as tuple) | + +-------------------+------------------------------+--------------------------------------+ + + +.. c:type:: PyStructSequence_Field + + Describes a field of a struct sequence. As a struct sequence is modeled as a + tuple, all fields are typed as :c:type:`PyObject\*`. The index in the + :attr:`fields` array of the :c:type:`PyStructSequence_Desc` determines which + field of the struct sequence is described. + + +-----------+------------------+-----------------------------------------+ + | Field | C Type | Meaning | + +===========+==================+=========================================+ + | ``name`` | ``const char *`` | name for the field or ``NULL`` to end | + | | | the list of named fields, set to | + | | | :c:data:`PyStructSequence_UnnamedField` | + | | | to leave unnamed | + +-----------+------------------+-----------------------------------------+ + | ``doc`` | ``const char *`` | field docstring or ``NULL`` to omit | + +-----------+------------------+-----------------------------------------+ + + +.. c:var:: const char * const PyStructSequence_UnnamedField + + Special value for a field name to leave it unnamed. + + .. versionchanged:: 3.9 + The type was changed from ``char *``. + + +.. c:function:: PyObject* PyStructSequence_New(PyTypeObject *type) + + Creates an instance of *type*, which must have been created with + :c:func:`PyStructSequence_NewType`. + + +.. c:function:: PyObject* PyStructSequence_GetItem(PyObject *p, Py_ssize_t pos) + + Return the object at position *pos* in the struct sequence pointed to by *p*. + No bounds checking is performed. + + +.. c:function:: PyObject* PyStructSequence_GET_ITEM(PyObject *p, Py_ssize_t pos) + + Macro equivalent of :c:func:`PyStructSequence_GetItem`. + + +.. c:function:: void PyStructSequence_SetItem(PyObject *p, Py_ssize_t pos, PyObject *o) + + Sets the field at index *pos* of the struct sequence *p* to value *o*. Like + :c:func:`PyTuple_SET_ITEM`, this should only be used to fill in brand new + instances. + + .. note:: + + This function "steals" a reference to *o*. + + +.. c:function:: void PyStructSequence_SET_ITEM(PyObject *p, Py_ssize_t *pos, PyObject *o) + + Macro equivalent of :c:func:`PyStructSequence_SetItem`. + + .. note:: + + This function "steals" a reference to *o*. diff --git a/cpython_2/environment/repo/Doc/c-api/type.rst b/cpython_2/environment/repo/Doc/c-api/type.rst new file mode 100644 index 0000000000000000000000000000000000000000..f387279d143eecb235d0e96052805d1dcb14e672 --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/type.rst @@ -0,0 +1,244 @@ +.. highlight:: c + +.. _typeobjects: + +Type Objects +------------ + +.. index:: object: type + + +.. c:type:: PyTypeObject + + The C structure of the objects used to describe built-in types. + + +.. c:var:: PyObject* PyType_Type + + This is the type object for type objects; it is the same object as + :class:`type` in the Python layer. + + +.. c:function:: int PyType_Check(PyObject *o) + + Return non-zero if the object *o* is a type object, including instances of + types derived from the standard type object. Return 0 in all other cases. + + +.. c:function:: int PyType_CheckExact(PyObject *o) + + Return non-zero if the object *o* is a type object, but not a subtype of the + standard type object. Return 0 in all other cases. + + +.. c:function:: unsigned int PyType_ClearCache() + + Clear the internal lookup cache. Return the current version tag. + +.. c:function:: unsigned long PyType_GetFlags(PyTypeObject* type) + + Return the :c:member:`~PyTypeObject.tp_flags` member of *type*. This function is primarily + meant for use with `Py_LIMITED_API`; the individual flag bits are + guaranteed to be stable across Python releases, but access to + :c:member:`~PyTypeObject.tp_flags` itself is not part of the limited API. + + .. versionadded:: 3.2 + + .. versionchanged:: 3.4 + The return type is now ``unsigned long`` rather than ``long``. + + +.. c:function:: void PyType_Modified(PyTypeObject *type) + + Invalidate the internal lookup cache for the type and all of its + subtypes. This function must be called after any manual + modification of the attributes or base classes of the type. + + +.. c:function:: int PyType_HasFeature(PyTypeObject *o, int feature) + + Return non-zero if the type object *o* sets the feature *feature*. + Type features are denoted by single bit flags. + + +.. c:function:: int PyType_IS_GC(PyTypeObject *o) + + Return true if the type object includes support for the cycle detector; this + tests the type flag :const:`Py_TPFLAGS_HAVE_GC`. + + +.. c:function:: int PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b) + + Return true if *a* is a subtype of *b*. + + This function only checks for actual subtypes, which means that + :meth:`~class.__subclasscheck__` is not called on *b*. Call + :c:func:`PyObject_IsSubclass` to do the same check that :func:`issubclass` + would do. + + +.. c:function:: PyObject* PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems) + + Generic handler for the :c:member:`~PyTypeObject.tp_alloc` slot of a type object. Use + Python's default memory allocation mechanism to allocate a new instance and + initialize all its contents to ``NULL``. + +.. c:function:: PyObject* PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds) + + Generic handler for the :c:member:`~PyTypeObject.tp_new` slot of a type object. Create a + new instance using the type's :c:member:`~PyTypeObject.tp_alloc` slot. + +.. c:function:: int PyType_Ready(PyTypeObject *type) + + Finalize a type object. This should be called on all type objects to finish + their initialization. This function is responsible for adding inherited slots + from a type's base class. Return ``0`` on success, or return ``-1`` and sets an + exception on error. + +.. c:function:: void* PyType_GetSlot(PyTypeObject *type, int slot) + + Return the function pointer stored in the given slot. If the + result is ``NULL``, this indicates that either the slot is ``NULL``, + or that the function was called with invalid parameters. + Callers will typically cast the result pointer into the appropriate + function type. + + See :c:member:`PyType_Slot.slot` for possible values of the *slot* argument. + + An exception is raised if *type* is not a heap type. + + .. versionadded:: 3.4 + +.. c:function:: PyObject* PyType_GetModule(PyTypeObject *type) + + Return the module object associated with the given type when the type was + created using :c:func:`PyType_FromModuleAndSpec`. + + If no module is associated with the given type, sets :py:class:`TypeError` + and returns ``NULL``. + + .. versionadded:: 3.9 + +.. c:function:: void* PyType_GetModuleState(PyTypeObject *type) + + Return the state of the module object associated with the given type. + This is a shortcut for calling :c:func:`PyModule_GetState()` on the result + of :c:func:`PyType_GetModule`. + + If no module is associated with the given type, sets :py:class:`TypeError` + and returns ``NULL``. + + If the *type* has an associated module but its state is ``NULL``, + returns ``NULL`` without setting an exception. + + .. versionadded:: 3.9 + + +Creating Heap-Allocated Types +............................. + +The following functions and structs are used to create +:ref:`heap types `. + +.. c:function:: PyObject* PyType_FromModuleAndSpec(PyObject *module, PyType_Spec *spec, PyObject *bases) + + Creates and returns a heap type object from the *spec* + (:const:`Py_TPFLAGS_HEAPTYPE`). + + If *bases* is a tuple, the created heap type contains all types contained + in it as base types. + + If *bases* is ``NULL``, the *Py_tp_base* slot is used instead. + If that also is ``NULL``, the new type derives from :class:`object`. + + The *module* must be a module object or ``NULL``. + If not ``NULL``, the module is associated with the new type and can later be + retreived with :c:func:`PyType_GetModule`. + + This function calls :c:func:`PyType_Ready` on the new type. + + .. versionadded:: 3.9 + +.. c:function:: PyObject* PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases) + + Equivalent to ``PyType_FromModuleAndSpec(NULL, spec, bases)``. + + .. versionadded:: 3.3 + +.. c:function:: PyObject* PyType_FromSpec(PyType_Spec *spec) + + Equivalent to ``PyType_FromSpecWithBases(spec, NULL)``. + +.. c:type:: PyType_Spec + + Structure defining a type's behavior. + + .. c:member:: const char* PyType_Spec.name + + Name of the type, used to set :c:member:`PyTypeObject.tp_name`. + + .. c:member:: int PyType_Spec.basicsize + .. c:member:: int PyType_Spec.itemsize + + Size of the instance in bytes, used to set + :c:member:`PyTypeObject.tp_basicsize` and + :c:member:`PyTypeObject.tp_itemsize`. + + .. c:member:: int PyType_Spec.flags + + Type flags, used to set :c:member:`PyTypeObject.tp_flags`. + + If the ``Py_TPFLAGS_HEAPTYPE`` flag is not set, + :c:func:`PyType_FromSpecWithBases` sets it automatically. + + .. c:member:: PyType_Slot *PyType_Spec.slots + + Array of :c:type:`PyType_Slot` structures. + Terminated by the special slot value ``{0, NULL}``. + +.. c:type:: PyType_Slot + + Structure defining optional functionality of a type, containing a slot ID + and a value pointer. + + .. c:member:: int PyType_Slot.slot + + A slot ID. + + Slot IDs are named like the field names of the structures + :c:type:`PyTypeObject`, :c:type:`PyNumberMethods`, + :c:type:`PySequenceMethods`, :c:type:`PyMappingMethods` and + :c:type:`PyAsyncMethods` with an added ``Py_`` prefix. + For example, use: + + * ``Py_tp_dealloc`` to set :c:member:`PyTypeObject.tp_dealloc` + * ``Py_nb_add`` to set :c:member:`PyNumberMethods.nb_add` + * ``Py_sq_length`` to set :c:member:`PySequenceMethods.sq_length` + + The following fields cannot be set using :c:type:`PyType_Spec` and :c:type:`PyType_Slot`: + + * :c:member:`~PyTypeObject.tp_dict` + * :c:member:`~PyTypeObject.tp_mro` + * :c:member:`~PyTypeObject.tp_cache` + * :c:member:`~PyTypeObject.tp_subclasses` + * :c:member:`~PyTypeObject.tp_weaklist` + * :c:member:`~PyTypeObject.tp_vectorcall` + * :c:member:`~PyTypeObject.tp_weaklistoffset` + (see :ref:`PyMemberDef `) + * :c:member:`~PyTypeObject.tp_dictoffset` + (see :ref:`PyMemberDef `) + * :c:member:`~PyTypeObject.tp_vectorcall_offset` + (see :ref:`PyMemberDef `) + * :c:member:`~PyBufferProcs.bf_getbuffer` + * :c:member:`~PyBufferProcs.bf_releasebuffer` + + Setting :c:data:`Py_tp_bases` may be problematic on some platforms. + To avoid issues, use the *bases* argument of + :py:func:`PyType_FromSpecWithBases` instead. + + .. c:member:: void *PyType_Slot.pfunc + + The desired value of the slot. In most cases, this is a pointer + to a function. + + May not be ``NULL``. diff --git a/cpython_2/environment/repo/Doc/c-api/typeobj.rst b/cpython_2/environment/repo/Doc/c-api/typeobj.rst new file mode 100644 index 0000000000000000000000000000000000000000..ce4e8c926b2943badc89eae596075371db6249f6 --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/typeobj.rst @@ -0,0 +1,2571 @@ +.. highlight:: c + +.. _type-structs: + +Type Objects +============ + +Perhaps one of the most important structures of the Python object system is the +structure that defines a new type: the :c:type:`PyTypeObject` structure. Type +objects can be handled using any of the :c:func:`PyObject_\*` or +:c:func:`PyType_\*` functions, but do not offer much that's interesting to most +Python applications. These objects are fundamental to how objects behave, so +they are very important to the interpreter itself and to any extension module +that implements new types. + +Type objects are fairly large compared to most of the standard types. The reason +for the size is that each type object stores a large number of values, mostly C +function pointers, each of which implements a small part of the type's +functionality. The fields of the type object are examined in detail in this +section. The fields will be described in the order in which they occur in the +structure. + +In addition to the following quick reference, the :ref:`typedef-examples` +section provides at-a-glance insight into the meaning and use of +:c:type:`PyTypeObject`. + + +Quick Reference +--------------- + +.. _tp-slots-table: + +"tp slots" +^^^^^^^^^^ + +.. table:: + :widths: 18,18,18,1,1,1,1 + + +------------------------------------------------+-----------------------------------+-------------------+---------------+ + | PyTypeObject Slot [#slots]_ | :ref:`Type ` | special | Info [#cols]_ | + | | | methods/attrs +---+---+---+---+ + | | | | O | T | D | I | + +================================================+===================================+===================+===+===+===+===+ + | :c:member:`~PyTypeObject.tp_name` | const char * | __name__ | X | X | | | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_basicsize` | Py_ssize_t | | X | X | | X | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_itemsize` | Py_ssize_t | | | X | | X | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_dealloc` | :c:type:`destructor` | | X | X | | X | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_vectorcall_offset` | Py_ssize_t | | | X | | X | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | (:c:member:`~PyTypeObject.tp_getattr`) | :c:type:`getattrfunc` | __getattribute__, | | | | G | + | | | __getattr__ | | | | | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | (:c:member:`~PyTypeObject.tp_setattr`) | :c:type:`setattrfunc` | __setattr__, | | | | G | + | | | __delattr__ | | | | | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_as_async` | :c:type:`PyAsyncMethods` * | :ref:`sub-slots` | | | | % | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_repr` | :c:type:`reprfunc` | __repr__ | X | X | | X | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_as_number` | :c:type:`PyNumberMethods` * | :ref:`sub-slots` | | | | % | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_as_sequence` | :c:type:`PySequenceMethods` * | :ref:`sub-slots` | | | | % | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_as_mapping` | :c:type:`PyMappingMethods` * | :ref:`sub-slots` | | | | % | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_hash` | :c:type:`hashfunc` | __hash__ | X | | | G | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_call` | :c:type:`ternaryfunc` | __call__ | | X | | X | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_str` | :c:type:`reprfunc` | __str__ | X | | | X | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_getattro` | :c:type:`getattrofunc` | __getattribute__, | X | X | | G | + | | | __getattr__ | | | | | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_setattro` | :c:type:`setattrofunc` | __setattr__, | X | X | | G | + | | | __delattr__ | | | | | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_as_buffer` | :c:type:`PyBufferProcs` * | | | | | % | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_flags` | unsigned long | | X | X | | ? | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_doc` | const char * | __doc__ | X | X | | | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_traverse` | :c:type:`traverseproc` | | | X | | G | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_clear` | :c:type:`inquiry` | | | X | | G | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_richcompare` | :c:type:`richcmpfunc` | __lt__, | X | | | G | + | | | __le__, | | | | | + | | | __eq__, | | | | | + | | | __ne__, | | | | | + | | | __gt__, | | | | | + | | | __ge__ | | | | | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_weaklistoffset` | Py_ssize_t | | | X | | ? | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_iter` | :c:type:`getiterfunc` | __iter__ | | | | X | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_iternext` | :c:type:`iternextfunc` | __next__ | | | | X | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_methods` | :c:type:`PyMethodDef` [] | | X | X | | | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_members` | :c:type:`PyMemberDef` [] | | | X | | | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_getset` | :c:type:`PyGetSetDef` [] | | X | X | | | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_base` | :c:type:`PyTypeObject` * | __base__ | | | X | | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_dict` | :c:type:`PyObject` * | __dict__ | | | ? | | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_descr_get` | :c:type:`descrgetfunc` | __get__ | | | | X | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_descr_set` | :c:type:`descrsetfunc` | __set__, | | | | X | + | | | __delete__ | | | | | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_dictoffset` | Py_ssize_t | | | X | | ? | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_init` | :c:type:`initproc` | __init__ | X | X | | X | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_alloc` | :c:type:`allocfunc` | | X | | ? | ? | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_new` | :c:type:`newfunc` | __new__ | X | X | ? | ? | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_free` | :c:type:`freefunc` | | X | X | ? | ? | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_is_gc` | :c:type:`inquiry` | | | X | | X | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | <:c:member:`~PyTypeObject.tp_bases`> | :c:type:`PyObject` * | __bases__ | | | ~ | | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | <:c:member:`~PyTypeObject.tp_mro`> | :c:type:`PyObject` * | __mro__ | | | ~ | | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | [:c:member:`~PyTypeObject.tp_cache`] | :c:type:`PyObject` * | | | | | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | [:c:member:`~PyTypeObject.tp_subclasses`] | :c:type:`PyObject` * | __subclasses__ | | | | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | [:c:member:`~PyTypeObject.tp_weaklist`] | :c:type:`PyObject` * | | | | | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | (:c:member:`~PyTypeObject.tp_del`) | :c:type:`destructor` | | | | | | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | [:c:member:`~PyTypeObject.tp_version_tag`] | unsigned int | | | | | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_finalize` | :c:type:`destructor` | __del__ | | | | X | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + | :c:member:`~PyTypeObject.tp_vectorcall` | :c:type:`vectorcallfunc` | | | | | | + +------------------------------------------------+-----------------------------------+-------------------+---+---+---+---+ + +.. [#slots] + A slot name in parentheses indicates it is (effectively) deprecated. + Names in angle brackets should be treated as read-only. + Names in square brackets are for internal use only. + "" (as a prefix) means the field is required (must be non-``NULL``). +.. [#cols] Columns: + + **"O"**: set on :c:type:`PyBaseObject_Type` + + **"T"**: set on :c:type:`PyType_Type` + + **"D"**: default (if slot is set to ``NULL``) + + .. code-block:: none + + 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"**: inheritance + + .. code-block:: none + + 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 + + Note that some slots are effectively inherited through the normal + attribute lookup chain. + +.. _sub-slots: + +sub-slots +^^^^^^^^^ + +.. table:: + :widths: 26,17,12 + + +---------------------------------------------------------+-----------------------------------+--------------+ + | Slot | :ref:`Type ` | special | + | | | methods | + +=========================================================+===================================+==============+ + | :c:member:`~PyAsyncMethods.am_await` | :c:type:`unaryfunc` | __await__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyAsyncMethods.am_aiter` | :c:type:`unaryfunc` | __aiter__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyAsyncMethods.am_anext` | :c:type:`unaryfunc` | __anext__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_add` | :c:type:`binaryfunc` | __add__ | + | | | __radd__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_inplace_add` | :c:type:`binaryfunc` | __iadd__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_subtract` | :c:type:`binaryfunc` | __sub__ | + | | | __rsub__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_inplace_subtract` | :c:type:`binaryfunc` | __sub__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_multiply` | :c:type:`binaryfunc` | __mul__ | + | | | __rmul__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_inplace_multiply` | :c:type:`binaryfunc` | __mul__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_remainder` | :c:type:`binaryfunc` | __mod__ | + | | | __rmod__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_inplace_remainder` | :c:type:`binaryfunc` | __mod__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_divmod` | :c:type:`binaryfunc` | __divmod__ | + | | | __rdivmod__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_power` | :c:type:`ternaryfunc` | __pow__ | + | | | __rpow__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_inplace_power` | :c:type:`ternaryfunc` | __pow__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_negative` | :c:type:`unaryfunc` | __neg__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_positive` | :c:type:`unaryfunc` | __pos__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_absolute` | :c:type:`unaryfunc` | __abs__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_bool` | :c:type:`inquiry` | __bool__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_invert` | :c:type:`unaryfunc` | __invert__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_lshift` | :c:type:`binaryfunc` | __lshift__ | + | | | __rlshift__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_inplace_lshift` | :c:type:`binaryfunc` | __lshift__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_rshift` | :c:type:`binaryfunc` | __rshift__ | + | | | __rrshift__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_inplace_rshift` | :c:type:`binaryfunc` | __rshift__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_and` | :c:type:`binaryfunc` | __and__ | + | | | __rand__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_inplace_and` | :c:type:`binaryfunc` | __and__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_xor` | :c:type:`binaryfunc` | __xor__ | + | | | __rxor__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_inplace_xor` | :c:type:`binaryfunc` | __xor__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_or` | :c:type:`binaryfunc` | __or__ | + | | | __ror__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_inplace_or` | :c:type:`binaryfunc` | __or__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_int` | :c:type:`unaryfunc` | __int__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_reserved` | void * | | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_float` | :c:type:`unaryfunc` | __float__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_floor_divide` | :c:type:`binaryfunc` | __floordiv__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_inplace_floor_divide` | :c:type:`binaryfunc` | __floordiv__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_true_divide` | :c:type:`binaryfunc` | __truediv__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_inplace_true_divide` | :c:type:`binaryfunc` | __truediv__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_index` | :c:type:`unaryfunc` | __index__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_matrix_multiply` | :c:type:`binaryfunc` | __matmul__ | + | | | __rmatmul__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyNumberMethods.nb_inplace_matrix_multiply` | :c:type:`binaryfunc` | __matmul__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyMappingMethods.mp_length` | :c:type:`lenfunc` | __len__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyMappingMethods.mp_subscript` | :c:type:`binaryfunc` | __getitem__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyMappingMethods.mp_ass_subscript` | :c:type:`objobjargproc` | __setitem__, | + | | | __delitem__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PySequenceMethods.sq_length` | :c:type:`lenfunc` | __len__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PySequenceMethods.sq_concat` | :c:type:`binaryfunc` | __add__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PySequenceMethods.sq_repeat` | :c:type:`ssizeargfunc` | __mul__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PySequenceMethods.sq_item` | :c:type:`ssizeargfunc` | __getitem__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PySequenceMethods.sq_ass_item` | :c:type:`ssizeobjargproc` | __setitem__ | + | | | __delitem__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PySequenceMethods.sq_contains` | :c:type:`objobjproc` | __contains__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PySequenceMethods.sq_inplace_concat` | :c:type:`binaryfunc` | __iadd__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PySequenceMethods.sq_inplace_repeat` | :c:type:`ssizeargfunc` | __imul__ | + +---------------------------------------------------------+-----------------------------------+--------------+ + | | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyBufferProcs.bf_getbuffer` | :c:func:`getbufferproc` | | + +---------------------------------------------------------+-----------------------------------+--------------+ + | :c:member:`~PyBufferProcs.bf_releasebuffer` | :c:func:`releasebufferproc` | | + +---------------------------------------------------------+-----------------------------------+--------------+ + +.. _slot-typedefs-table: + +slot typedefs +^^^^^^^^^^^^^ + ++-----------------------------+-----------------------------+----------------------+ +| typedef | Parameter Types | Return Type | ++=============================+=============================+======================+ +| :c:type:`allocfunc` | .. line-block:: | :c:type:`PyObject` * | +| | | | +| | :c:type:`PyTypeObject` * | | +| | Py_ssize_t | | ++-----------------------------+-----------------------------+----------------------+ +| :c:type:`destructor` | void * | void | ++-----------------------------+-----------------------------+----------------------+ +| :c:type:`freefunc` | void * | void | ++-----------------------------+-----------------------------+----------------------+ +| :c:type:`traverseproc` | .. line-block:: | int | +| | | | +| | void * | | +| | :c:type:`visitproc` | | +| | void * | | ++-----------------------------+-----------------------------+----------------------+ +| :c:type:`newfunc` | .. line-block:: | :c:type:`PyObject` * | +| | | | +| | :c:type:`PyObject` * | | +| | :c:type:`PyObject` * | | +| | :c:type:`PyObject` * | | ++-----------------------------+-----------------------------+----------------------+ +| :c:type:`initproc` | .. line-block:: | int | +| | | | +| | :c:type:`PyObject` * | | +| | :c:type:`PyObject` * | | +| | :c:type:`PyObject` * | | ++-----------------------------+-----------------------------+----------------------+ +| :c:type:`reprfunc` | :c:type:`PyObject` * | :c:type:`PyObject` * | ++-----------------------------+-----------------------------+----------------------+ +| :c:type:`getattrfunc` | .. line-block:: | :c:type:`PyObject` * | +| | | | +| | :c:type:`PyObject` * | | +| | const char * | | ++-----------------------------+-----------------------------+----------------------+ +| :c:type:`setattrfunc` | .. line-block:: | int | +| | | | +| | :c:type:`PyObject` * | | +| | const char * | | +| | :c:type:`PyObject` * | | ++-----------------------------+-----------------------------+----------------------+ +| :c:type:`getattrofunc` | .. line-block:: | :c:type:`PyObject` * | +| | | | +| | :c:type:`PyObject` * | | +| | :c:type:`PyObject` * | | ++-----------------------------+-----------------------------+----------------------+ +| :c:type:`setattrofunc` | .. line-block:: | int | +| | | | +| | :c:type:`PyObject` * | | +| | :c:type:`PyObject` * | | +| | :c:type:`PyObject` * | | ++-----------------------------+-----------------------------+----------------------+ +| :c:type:`descrgetfunc` | .. line-block:: | :c:type:`PyObject` * | +| | | | +| | :c:type:`PyObject` * | | +| | :c:type:`PyObject` * | | +| | :c:type:`PyObject` * | | ++-----------------------------+-----------------------------+----------------------+ +| :c:type:`descrsetfunc` | .. line-block:: | int | +| | | | +| | :c:type:`PyObject` * | | +| | :c:type:`PyObject` * | | +| | :c:type:`PyObject` * | | ++-----------------------------+-----------------------------+----------------------+ +| :c:type:`hashfunc` | :c:type:`PyObject` * | Py_hash_t | ++-----------------------------+-----------------------------+----------------------+ +| :c:type:`richcmpfunc` | .. line-block:: | :c:type:`PyObject` * | +| | | | +| | :c:type:`PyObject` * | | +| | :c:type:`PyObject` * | | +| | int | | ++-----------------------------+-----------------------------+----------------------+ +| :c:type:`getiterfunc` | :c:type:`PyObject` * | :c:type:`PyObject` * | ++-----------------------------+-----------------------------+----------------------+ +| :c:type:`iternextfunc` | :c:type:`PyObject` * | :c:type:`PyObject` * | ++-----------------------------+-----------------------------+----------------------+ +| :c:type:`lenfunc` | :c:type:`PyObject` * | Py_ssize_t | ++-----------------------------+-----------------------------+----------------------+ +| :c:type:`getbufferproc` | .. line-block:: | int | +| | | | +| | :c:type:`PyObject` * | | +| | :c:type:`Py_buffer` * | | +| | int | | ++-----------------------------+-----------------------------+----------------------+ +| :c:type:`releasebufferproc` | .. line-block:: | void | +| | | | +| | :c:type:`PyObject` * | | +| | :c:type:`Py_buffer` * | | ++-----------------------------+-----------------------------+----------------------+ +| :c:type:`inquiry` | void * | int | ++-----------------------------+-----------------------------+----------------------+ +| :c:type:`unaryfunc` | .. line-block:: | :c:type:`PyObject` * | +| | | | +| | :c:type:`PyObject` * | | ++-----------------------------+-----------------------------+----------------------+ +| :c:type:`binaryfunc` | .. line-block:: | :c:type:`PyObject` * | +| | | | +| | :c:type:`PyObject` * | | +| | :c:type:`PyObject` * | | ++-----------------------------+-----------------------------+----------------------+ +| :c:type:`ternaryfunc` | .. line-block:: | :c:type:`PyObject` * | +| | | | +| | :c:type:`PyObject` * | | +| | :c:type:`PyObject` * | | +| | :c:type:`PyObject` * | | ++-----------------------------+-----------------------------+----------------------+ +| :c:type:`ssizeargfunc` | .. line-block:: | :c:type:`PyObject` * | +| | | | +| | :c:type:`PyObject` * | | +| | Py_ssize_t | | ++-----------------------------+-----------------------------+----------------------+ +| :c:type:`ssizeobjargproc` | .. line-block:: | int | +| | | | +| | :c:type:`PyObject` * | | +| | Py_ssize_t | | ++-----------------------------+-----------------------------+----------------------+ +| :c:type:`objobjproc` | .. line-block:: | int | +| | | | +| | :c:type:`PyObject` * | | +| | :c:type:`PyObject` * | | ++-----------------------------+-----------------------------+----------------------+ +| :c:type:`objobjargproc` | .. line-block:: | int | +| | | | +| | :c:type:`PyObject` * | | +| | :c:type:`PyObject` * | | +| | :c:type:`PyObject` * | | ++-----------------------------+-----------------------------+----------------------+ + +See :ref:`slot-typedefs` below for more detail. + + +PyTypeObject Definition +----------------------- + +The structure definition for :c:type:`PyTypeObject` can be found in +:file:`Include/object.h`. For convenience of reference, this repeats the +definition found there: + +.. XXX Drop this? + +.. literalinclude:: ../includes/typestruct.h + + +PyObject Slots +-------------- + +The type object structure extends the :c:type:`PyVarObject` structure. The +:attr:`ob_size` field is used for dynamic types (created by :func:`type_new`, +usually called from a class statement). Note that :c:data:`PyType_Type` (the +metatype) initializes :c:member:`~PyTypeObject.tp_itemsize`, which means that its instances (i.e. +type objects) *must* have the :attr:`ob_size` field. + + +.. c:member:: PyObject* PyObject._ob_next + PyObject* PyObject._ob_prev + + These fields are only present when the macro ``Py_TRACE_REFS`` is defined. + Their initialization to ``NULL`` is taken care of by the ``PyObject_HEAD_INIT`` + macro. For statically allocated objects, these fields always remain ``NULL``. + For dynamically allocated objects, these two fields are used to link the object + into a doubly-linked list of *all* live objects on the heap. This could be used + for various debugging purposes; currently the only use is to print the objects + that are still alive at the end of a run when the environment variable + :envvar:`PYTHONDUMPREFS` is set. + + **Inheritance:** + + These fields are not inherited by subtypes. + + +.. c:member:: Py_ssize_t PyObject.ob_refcnt + + This is the type object's reference count, initialized to ``1`` by the + ``PyObject_HEAD_INIT`` macro. Note that for statically allocated type objects, + the type's instances (objects whose :attr:`ob_type` points back to the type) do + *not* count as references. But for dynamically allocated type objects, the + instances *do* count as references. + + **Inheritance:** + + This field is not inherited by subtypes. + + +.. c:member:: PyTypeObject* PyObject.ob_type + + This is the type's type, in other words its metatype. It is initialized by the + argument to the ``PyObject_HEAD_INIT`` macro, and its value should normally be + ``&PyType_Type``. However, for dynamically loadable extension modules that must + be usable on Windows (at least), the compiler complains that this is not a valid + initializer. Therefore, the convention is to pass ``NULL`` to the + ``PyObject_HEAD_INIT`` macro and to initialize this field explicitly at the + start of the module's initialization function, before doing anything else. This + is typically done like this:: + + Foo_Type.ob_type = &PyType_Type; + + This should be done before any instances of the type are created. + :c:func:`PyType_Ready` checks if :attr:`ob_type` is ``NULL``, and if so, + initializes it to the :attr:`ob_type` field of the base class. + :c:func:`PyType_Ready` will not change this field if it is non-zero. + + **Inheritance:** + + This field is inherited by subtypes. + + +PyVarObject Slots +----------------- + +.. c:member:: Py_ssize_t PyVarObject.ob_size + + For statically allocated type objects, this should be initialized to zero. For + dynamically allocated type objects, this field has a special internal meaning. + + **Inheritance:** + + This field is not inherited by subtypes. + + +PyTypeObject Slots +------------------ + +Each slot has a section describing inheritance. If :c:func:`PyType_Ready` +may set a value when the field is set to ``NULL`` then there will also be +a "Default" section. (Note that many fields set on :c:type:`PyBaseObject_Type` +and :c:type:`PyType_Type` effectively act as defaults.) + +.. c:member:: const char* PyTypeObject.tp_name + + Pointer to a NUL-terminated string containing the name of the type. For types + that are accessible as module globals, the string should be the full module + name, followed by a dot, followed by the type name; for built-in types, it + should be just the type name. If the module is a submodule of a package, the + full package name is part of the full module name. For example, a type named + :class:`T` defined in module :mod:`M` in subpackage :mod:`Q` in package :mod:`P` + should have the :c:member:`~PyTypeObject.tp_name` initializer ``"P.Q.M.T"``. + + For dynamically allocated type objects, this should just be the type name, and + the module name explicitly stored in the type dict as the value for key + ``'__module__'``. + + For statically allocated type objects, the tp_name field should contain a dot. + Everything before the last dot is made accessible as the :attr:`__module__` + attribute, and everything after the last dot is made accessible as the + :attr:`~definition.__name__` attribute. + + If no dot is present, the entire :c:member:`~PyTypeObject.tp_name` field is made accessible as the + :attr:`~definition.__name__` attribute, and the :attr:`__module__` attribute is undefined + (unless explicitly set in the dictionary, as explained above). This means your + type will be impossible to pickle. Additionally, it will not be listed in + module documentations created with pydoc. + + This field must not be ``NULL``. It is the only required field + in :c:func:`PyTypeObject` (other than potentially + :c:member:`~PyTypeObject.tp_itemsize`). + + **Inheritance:** + + This field is not inherited by subtypes. + + +.. c:member:: Py_ssize_t PyTypeObject.tp_basicsize + Py_ssize_t PyTypeObject.tp_itemsize + + These fields allow calculating the size in bytes of instances of the type. + + There are two kinds of types: types with fixed-length instances have a zero + :c:member:`~PyTypeObject.tp_itemsize` field, types with variable-length instances have a non-zero + :c:member:`~PyTypeObject.tp_itemsize` field. For a type with fixed-length instances, all + instances have the same size, given in :c:member:`~PyTypeObject.tp_basicsize`. + + For a type with variable-length instances, the instances must have an + :attr:`ob_size` field, and the instance size is :c:member:`~PyTypeObject.tp_basicsize` plus N + times :c:member:`~PyTypeObject.tp_itemsize`, where N is the "length" of the object. The value of + N is typically stored in the instance's :attr:`ob_size` field. There are + exceptions: for example, ints use a negative :attr:`ob_size` to indicate a + negative number, and N is ``abs(ob_size)`` there. Also, the presence of an + :attr:`ob_size` field in the instance layout doesn't mean that the instance + structure is variable-length (for example, the structure for the list type has + fixed-length instances, yet those instances have a meaningful :attr:`ob_size` + field). + + The basic size includes the fields in the instance declared by the macro + :c:macro:`PyObject_HEAD` or :c:macro:`PyObject_VAR_HEAD` (whichever is used to + declare the instance struct) and this in turn includes the :attr:`_ob_prev` and + :attr:`_ob_next` fields if they are present. This means that the only correct + way to get an initializer for the :c:member:`~PyTypeObject.tp_basicsize` is to use the + ``sizeof`` operator on the struct used to declare the instance layout. + The basic size does not include the GC header size. + + A note about alignment: if the variable items require a particular alignment, + this should be taken care of by the value of :c:member:`~PyTypeObject.tp_basicsize`. Example: + suppose a type implements an array of ``double``. :c:member:`~PyTypeObject.tp_itemsize` is + ``sizeof(double)``. It is the programmer's responsibility that + :c:member:`~PyTypeObject.tp_basicsize` is a multiple of ``sizeof(double)`` (assuming this is the + alignment requirement for ``double``). + + For any type with variable-length instances, this field must not be ``NULL``. + + **Inheritance:** + + These fields are inherited separately by subtypes. If the base type has a + non-zero :c:member:`~PyTypeObject.tp_itemsize`, it is generally not safe to set + :c:member:`~PyTypeObject.tp_itemsize` to a different non-zero value in a subtype (though this + depends on the implementation of the base type). + + +.. c:member:: destructor PyTypeObject.tp_dealloc + + A pointer to the instance destructor function. This function must be defined + unless the type guarantees that its instances will never be deallocated (as is + the case for the singletons ``None`` and ``Ellipsis``). The function signature is:: + + void tp_dealloc(PyObject *self); + + The destructor function is called by the :c:func:`Py_DECREF` and + :c:func:`Py_XDECREF` macros when the new reference count is zero. At this point, + the instance is still in existence, but there are no references to it. The + destructor function should free all references which the instance owns, free all + memory buffers owned by the instance (using the freeing function corresponding + to the allocation function used to allocate the buffer), and call the type's + :c:member:`~PyTypeObject.tp_free` function. If the type is not subtypable + (doesn't have the :const:`Py_TPFLAGS_BASETYPE` flag bit set), it is + permissible to call the object deallocator directly instead of via + :c:member:`~PyTypeObject.tp_free`. The object deallocator should be the one used to allocate the + instance; this is normally :c:func:`PyObject_Del` if the instance was allocated + using :c:func:`PyObject_New` or :c:func:`PyObject_VarNew`, or + :c:func:`PyObject_GC_Del` if the instance was allocated using + :c:func:`PyObject_GC_New` or :c:func:`PyObject_GC_NewVar`. + + Finally, if the type is heap allocated (:const:`Py_TPFLAGS_HEAPTYPE`), the + deallocator should decrement the reference count for its type object after + calling the type deallocator. In order to avoid dangling pointers, the + recommended way to achieve this is: + + .. code-block:: c + + static void foo_dealloc(foo_object *self) { + PyTypeObject *tp = Py_TYPE(self); + // free references and buffers here + tp->tp_free(self); + Py_DECREF(tp); + } + + + **Inheritance:** + + This field is inherited by subtypes. + + +.. c:member:: Py_ssize_t PyTypeObject.tp_vectorcall_offset + + An optional offset to a per-instance function that implements calling + the object using the :ref:`vectorcall protocol `, + a more efficient alternative + of the simpler :c:member:`~PyTypeObject.tp_call`. + + This field is only used if the flag :const:`Py_TPFLAGS_HAVE_VECTORCALL` + is set. If so, this must be a positive integer containing the offset in the + instance of a :c:type:`vectorcallfunc` pointer. + + The *vectorcallfunc* pointer may be ``NULL``, in which case the instance behaves + as if :const:`Py_TPFLAGS_HAVE_VECTORCALL` was not set: calling the instance + falls back to :c:member:`~PyTypeObject.tp_call`. + + Any class that sets ``Py_TPFLAGS_HAVE_VECTORCALL`` must also set + :c:member:`~PyTypeObject.tp_call` and make sure its behaviour is consistent + with the *vectorcallfunc* function. + This can be done by setting *tp_call* to :c:func:`PyVectorcall_Call`. + + .. warning:: + + It is not recommended for :ref:`heap types ` to implement + the vectorcall protocol. + When a user sets :attr:`__call__` in Python code, only *tp_call* is updated, + likely making it inconsistent with the vectorcall function. + + .. note:: + + The semantics of the ``tp_vectorcall_offset`` slot are provisional and + expected to be finalized in Python 3.9. + If you use vectorcall, plan for updating your code for Python 3.9. + + .. versionchanged:: 3.8 + + Before version 3.8, this slot was named ``tp_print``. + In Python 2.x, it was used for printing to a file. + In Python 3.0 to 3.7, it was unused. + + **Inheritance:** + + This field is always inherited. + However, the :const:`Py_TPFLAGS_HAVE_VECTORCALL` flag is not + always inherited. If it's not, then the subclass won't use + :ref:`vectorcall `, except when + :c:func:`PyVectorcall_Call` is explicitly called. + This is in particular the case for `heap types`_ + (including subclasses defined in Python). + + +.. c:member:: getattrfunc PyTypeObject.tp_getattr + + An optional pointer to the get-attribute-string function. + + This field is deprecated. When it is defined, it should point to a function + that acts the same as the :c:member:`~PyTypeObject.tp_getattro` function, but taking a C string + instead of a Python string object to give the attribute name. + + **Inheritance:** + + Group: :attr:`tp_getattr`, :attr:`tp_getattro` + + This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_getattro`: a subtype + inherits both :c:member:`~PyTypeObject.tp_getattr` and :c:member:`~PyTypeObject.tp_getattro` from its base type when + the subtype's :c:member:`~PyTypeObject.tp_getattr` and :c:member:`~PyTypeObject.tp_getattro` are both ``NULL``. + + +.. c:member:: setattrfunc PyTypeObject.tp_setattr + + An optional pointer to the function for setting and deleting attributes. + + This field is deprecated. When it is defined, it should point to a function + that acts the same as the :c:member:`~PyTypeObject.tp_setattro` function, but taking a C string + instead of a Python string object to give the attribute name. + + **Inheritance:** + + Group: :attr:`tp_setattr`, :attr:`tp_setattro` + + This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_setattro`: a subtype + inherits both :c:member:`~PyTypeObject.tp_setattr` and :c:member:`~PyTypeObject.tp_setattro` from its base type when + the subtype's :c:member:`~PyTypeObject.tp_setattr` and :c:member:`~PyTypeObject.tp_setattro` are both ``NULL``. + + +.. c:member:: PyAsyncMethods* PyTypeObject.tp_as_async + + Pointer to an additional structure that contains fields relevant only to + objects which implement :term:`awaitable` and :term:`asynchronous iterator` + protocols at the C-level. See :ref:`async-structs` for details. + + .. versionadded:: 3.5 + Formerly known as ``tp_compare`` and ``tp_reserved``. + + **Inheritance:** + + The :c:member:`~PyTypeObject.tp_as_async` field is not inherited, + but the contained fields are inherited individually. + + +.. c:member:: reprfunc PyTypeObject.tp_repr + + .. index:: builtin: repr + + An optional pointer to a function that implements the built-in function + :func:`repr`. + + The signature is the same as for :c:func:`PyObject_Repr`:: + + PyObject *tp_repr(PyObject *self); + + The function must return a string or a Unicode object. Ideally, + this function should return a string that, when passed to + :func:`eval`, given a suitable environment, returns an object with the + same value. If this is not feasible, it should return a string starting with + ``'<'`` and ending with ``'>'`` from which both the type and the value of the + object can be deduced. + + **Inheritance:** + + This field is inherited by subtypes. + + **Default:** + + When this field is not set, a string of the form ``<%s object at %p>`` is + returned, where ``%s`` is replaced by the type name, and ``%p`` by the object's + memory address. + + +.. c:member:: PyNumberMethods* PyTypeObject.tp_as_number + + Pointer to an additional structure that contains fields relevant only to + objects which implement the number protocol. These fields are documented in + :ref:`number-structs`. + + **Inheritance:** + + The :c:member:`~PyTypeObject.tp_as_number` field is not inherited, but the contained fields are + inherited individually. + + +.. c:member:: PySequenceMethods* PyTypeObject.tp_as_sequence + + Pointer to an additional structure that contains fields relevant only to + objects which implement the sequence protocol. These fields are documented + in :ref:`sequence-structs`. + + **Inheritance:** + + The :c:member:`~PyTypeObject.tp_as_sequence` field is not inherited, but the contained fields + are inherited individually. + + +.. c:member:: PyMappingMethods* PyTypeObject.tp_as_mapping + + Pointer to an additional structure that contains fields relevant only to + objects which implement the mapping protocol. These fields are documented in + :ref:`mapping-structs`. + + **Inheritance:** + + The :c:member:`~PyTypeObject.tp_as_mapping` field is not inherited, but the contained fields + are inherited individually. + + +.. c:member:: hashfunc PyTypeObject.tp_hash + + .. index:: builtin: hash + + An optional pointer to a function that implements the built-in function + :func:`hash`. + + The signature is the same as for :c:func:`PyObject_Hash`:: + + Py_hash_t tp_hash(PyObject *); + + The value ``-1`` should not be returned as a + normal return value; when an error occurs during the computation of the hash + value, the function should set an exception and return ``-1``. + + When this field is not set (*and* :attr:`tp_richcompare` is not set), + an attempt to take the hash of the object raises :exc:`TypeError`. + This is the same as setting it to :c:func:`PyObject_HashNotImplemented`. + + This field can be set explicitly to :c:func:`PyObject_HashNotImplemented` to + block inheritance of the hash method from a parent type. This is interpreted + as the equivalent of ``__hash__ = None`` at the Python level, causing + ``isinstance(o, collections.Hashable)`` to correctly return ``False``. Note + that the converse is also true - setting ``__hash__ = None`` on a class at + the Python level will result in the ``tp_hash`` slot being set to + :c:func:`PyObject_HashNotImplemented`. + + **Inheritance:** + + Group: :attr:`tp_hash`, :attr:`tp_richcompare` + + This field is inherited by subtypes together with + :c:member:`~PyTypeObject.tp_richcompare`: a subtype inherits both of + :c:member:`~PyTypeObject.tp_richcompare` and :c:member:`~PyTypeObject.tp_hash`, when the subtype's + :c:member:`~PyTypeObject.tp_richcompare` and :c:member:`~PyTypeObject.tp_hash` are both ``NULL``. + + +.. c:member:: 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 :c:func:`PyObject_Call`:: + + PyObject *tp_call(PyObject *self, PyObject *args, PyObject *kwargs); + + **Inheritance:** + + This field is inherited by subtypes. + + +.. c:member:: reprfunc PyTypeObject.tp_str + + An optional pointer to a function that implements the built-in operation + :func:`str`. (Note that :class:`str` is a type now, and :func:`str` calls the + constructor for that type. This constructor calls :c:func:`PyObject_Str` to do + the actual work, and :c:func:`PyObject_Str` will call this handler.) + + The signature is the same as for :c:func:`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 :func:`print` function. + + **Inheritance:** + + This field is inherited by subtypes. + + **Default:** + + When this field is not set, :c:func:`PyObject_Repr` is called to return a string + representation. + + +.. c:member:: getattrofunc PyTypeObject.tp_getattro + + An optional pointer to the get-attribute function. + + The signature is the same as for :c:func:`PyObject_GetAttr`:: + + PyObject *tp_getattro(PyObject *self, PyObject *attr); + + It is usually convenient to set this field to :c:func:`PyObject_GenericGetAttr`, + which implements the normal way of looking for object attributes. + + **Inheritance:** + + Group: :attr:`tp_getattr`, :attr:`tp_getattro` + + This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_getattr`: a subtype + inherits both :c:member:`~PyTypeObject.tp_getattr` and :c:member:`~PyTypeObject.tp_getattro` from its base type when + the subtype's :c:member:`~PyTypeObject.tp_getattr` and :c:member:`~PyTypeObject.tp_getattro` are both ``NULL``. + + **Default:** + + :c:type:`PyBaseObject_Type` uses :c:func:`PyObject_GenericGetAttr`. + + +.. c:member:: setattrofunc PyTypeObject.tp_setattro + + An optional pointer to the function for setting and deleting attributes. + + The signature is the same as for :c:func:`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 + :c:func:`PyObject_GenericSetAttr`, which implements the normal + way of setting object attributes. + + **Inheritance:** + + Group: :attr:`tp_setattr`, :attr:`tp_setattro` + + This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_setattr`: a subtype + inherits both :c:member:`~PyTypeObject.tp_setattr` and :c:member:`~PyTypeObject.tp_setattro` from its base type when + the subtype's :c:member:`~PyTypeObject.tp_setattr` and :c:member:`~PyTypeObject.tp_setattro` are both ``NULL``. + + **Default:** + + :c:type:`PyBaseObject_Type` uses :c:func:`PyObject_GenericSetAttr`. + + +.. c:member:: PyBufferProcs* PyTypeObject.tp_as_buffer + + Pointer to an additional structure that contains fields relevant only to objects + which implement the buffer interface. These fields are documented in + :ref:`buffer-structs`. + + **Inheritance:** + + The :c:member:`~PyTypeObject.tp_as_buffer` field is not inherited, + but the contained fields are inherited individually. + + +.. c:member:: unsigned long PyTypeObject.tp_flags + + This field is a bit mask of various flags. Some flags indicate variant + semantics for certain situations; others are used to indicate that certain + fields in the type object (or in the extension structures referenced via + :c:member:`~PyTypeObject.tp_as_number`, :c:member:`~PyTypeObject.tp_as_sequence`, :c:member:`~PyTypeObject.tp_as_mapping`, and + :c:member:`~PyTypeObject.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:** + + 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 :const:`Py_TPFLAGS_HAVE_GC` flag bit is inherited together with + the :c:member:`~PyTypeObject.tp_traverse` and :c:member:`~PyTypeObject.tp_clear` fields, i.e. if the + :const:`Py_TPFLAGS_HAVE_GC` flag bit is clear in the subtype and the + :c:member:`~PyTypeObject.tp_traverse` and :c:member:`~PyTypeObject.tp_clear` fields in the subtype exist and have + ``NULL`` values. + + .. XXX are most flag bits *really* inherited individually? + + **Default:** + + :c:type:`PyBaseObject_Type` uses + ``Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE``. + + **Bit Masks:** + + The following bit masks are currently defined; these can be ORed together using + the ``|`` operator to form the value of the :c:member:`~PyTypeObject.tp_flags` field. The macro + :c:func:`PyType_HasFeature` takes a type and a flags value, *tp* and *f*, and + checks whether ``tp->tp_flags & f`` is non-zero. + + .. data:: Py_TPFLAGS_HEAPTYPE + + This bit is set when the type object itself is allocated on the heap, for + example, types created dynamically using :c:func:`PyType_FromSpec`. In this + case, the :attr:`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). + + **Inheritance:** + + ??? + + + .. data:: Py_TPFLAGS_BASETYPE + + This bit is set when the type can be used as the base type of another type. If + this bit is clear, the type cannot be subtyped (similar to a "final" class in + Java). + + **Inheritance:** + + ??? + + + .. data:: Py_TPFLAGS_READY + + This bit is set when the type object has been fully initialized by + :c:func:`PyType_Ready`. + + **Inheritance:** + + ??? + + + .. data:: Py_TPFLAGS_READYING + + This bit is set while :c:func:`PyType_Ready` is in the process of initializing + the type object. + + **Inheritance:** + + ??? + + + .. data:: Py_TPFLAGS_HAVE_GC + + This bit is set when the object supports garbage collection. If this bit + is set, instances must be created using :c:func:`PyObject_GC_New` and + destroyed using :c:func:`PyObject_GC_Del`. More information in section + :ref:`supporting-cycle-detection`. This bit also implies that the + GC-related fields :c:member:`~PyTypeObject.tp_traverse` and :c:member:`~PyTypeObject.tp_clear` are present in + the type object. + + **Inheritance:** + + Group: :const:`Py_TPFLAGS_HAVE_GC`, :attr:`tp_traverse`, :attr:`tp_clear` + + The :const:`Py_TPFLAGS_HAVE_GC` flag bit is inherited + together with the :attr:`tp_traverse` and :attr:`tp_clear` + fields, i.e. if the :const:`Py_TPFLAGS_HAVE_GC` flag bit is + clear in the subtype and the :attr:`tp_traverse` and + :attr:`tp_clear` fields in the subtype exist and have ``NULL`` + values. + + + .. data:: 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: :const:`Py_TPFLAGS_HAVE_STACKLESS_EXTENSION`, + :const:`Py_TPFLAGS_HAVE_VERSION_TAG`. + + **Inheritance:** + + ??? + + + .. data:: 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 temporary "bound method" object for + ``obj.meth``. + + .. versionadded:: 3.8 + + **Inheritance:** + + This flag is never inherited by heap types. + For extension types, it is inherited whenever + :c:member:`~PyTypeObject.tp_descr_get` is inherited. + + + .. XXX Document more flags here? + + + .. data:: Py_TPFLAGS_LONG_SUBCLASS + .. data:: Py_TPFLAGS_LIST_SUBCLASS + .. data:: Py_TPFLAGS_TUPLE_SUBCLASS + .. data:: Py_TPFLAGS_BYTES_SUBCLASS + .. data:: Py_TPFLAGS_UNICODE_SUBCLASS + .. data:: Py_TPFLAGS_DICT_SUBCLASS + .. data:: Py_TPFLAGS_BASE_EXC_SUBCLASS + .. data:: Py_TPFLAGS_TYPE_SUBCLASS + + These flags are used by functions such as + :c:func:`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 :c:func:`PyObject_IsInstance`. Custom types that inherit + from built-ins should have their :c:member:`~PyTypeObject.tp_flags` + set appropriately, or the code that interacts with such types + will behave differently depending on what kind of check is used. + + + .. data:: Py_TPFLAGS_HAVE_FINALIZE + + This bit is set when the :c:member:`~PyTypeObject.tp_finalize` slot is present in the + type structure. + + .. versionadded:: 3.4 + + .. deprecated:: 3.8 + This flag isn't necessary anymore, as the interpreter assumes the + :c:member:`~PyTypeObject.tp_finalize` slot is always present in the + type structure. + + + .. data:: Py_TPFLAGS_HAVE_VECTORCALL + + This bit is set when the class implements + the :ref:`vectorcall protocol `. + See :c:member:`~PyTypeObject.tp_vectorcall_offset` for details. + + **Inheritance:** + + This bit is inherited for *static* subtypes if + :c:member:`~PyTypeObject.tp_call` is also inherited. + `Heap types`_ do not inherit ``Py_TPFLAGS_HAVE_VECTORCALL``. + + .. versionadded:: 3.9 + + +.. c:member:: 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 :attr:`__doc__` attribute on the type and + instances of the type. + + **Inheritance:** + + This field is *not* inherited by subtypes. + + +.. c:member:: traverseproc PyTypeObject.tp_traverse + + An optional pointer to a traversal function for the garbage collector. This is + only used if the :const:`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 :ref:`supporting-cycle-detection`. + + The :c:member:`~PyTypeObject.tp_traverse` pointer is used by the garbage collector to detect + reference cycles. A typical implementation of a :c:member:`~PyTypeObject.tp_traverse` function + simply calls :c:func:`Py_VISIT` on each of the instance's members that are Python + objects that the instance owns. For example, this is function :c:func:`local_traverse` from the + :mod:`_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 :c:func:`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 :mod:`gc` module's + :func:`~gc.get_referents` function will include it. + + .. warning:: + When implementing :c:member:`~PyTypeObject.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 + :c:member:`~PyTypeObject.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 :c:func:`Py_VISIT` requires the *visit* and *arg* parameters to + :c:func:`local_traverse` to have these specific names; don't name them just + anything. + + **Inheritance:** + + Group: :const:`Py_TPFLAGS_HAVE_GC`, :attr:`tp_traverse`, :attr:`tp_clear` + + This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_clear` and the + :const:`Py_TPFLAGS_HAVE_GC` flag bit: the flag bit, :c:member:`~PyTypeObject.tp_traverse`, and + :c:member:`~PyTypeObject.tp_clear` are all inherited from the base type if they are all zero in + the subtype. + + +.. c:member:: inquiry PyTypeObject.tp_clear + + An optional pointer to a clear function for the garbage collector. This is only + used if the :const:`Py_TPFLAGS_HAVE_GC` flag bit is set. The signature is:: + + int tp_clear(PyObject *); + + The :c:member:`~PyTypeObject.tp_clear` member function is used to break reference cycles in cyclic + garbage detected by the garbage collector. Taken together, all :c:member:`~PyTypeObject.tp_clear` + functions in the system must combine to break all reference cycles. This is + subtle, and if in any doubt supply a :c:member:`~PyTypeObject.tp_clear` function. For example, + the tuple type does not implement a :c:member:`~PyTypeObject.tp_clear` function, because it's + possible to prove that no reference cycle can be composed entirely of tuples. + Therefore the :c:member:`~PyTypeObject.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 :c:member:`~PyTypeObject.tp_clear`. + + Implementations of :c:member:`~PyTypeObject.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 :c:func:`Py_CLEAR` macro should be used, because clearing references is + delicate: the reference to the contained object must not be decremented until + after the pointer to the contained object is set to ``NULL``. This is because + decrementing the reference count 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 important 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 + :c:func:`Py_CLEAR` macro performs the operations in a safe order. + + Because the goal of :c:member:`~PyTypeObject.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 + :c:member:`~PyTypeObject.tp_dealloc` function to invoke :c:member:`~PyTypeObject.tp_clear`. + + More information about Python's garbage collection scheme can be found in + section :ref:`supporting-cycle-detection`. + + **Inheritance:** + + Group: :const:`Py_TPFLAGS_HAVE_GC`, :attr:`tp_traverse`, :attr:`tp_clear` + + This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_traverse` and the + :const:`Py_TPFLAGS_HAVE_GC` flag bit: the flag bit, :c:member:`~PyTypeObject.tp_traverse`, and + :c:member:`~PyTypeObject.tp_clear` are all inherited from the base type if they are all zero in + the subtype. + + +.. c:member:: 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 :c:type:`PyTypeObject`. + + The function should return the result of the comparison (usually ``Py_True`` + or ``Py_False``). If the comparison is undefined, it must return + ``Py_NotImplemented``, if another error occurred it must return ``NULL`` and + set an exception condition. + + The following constants are defined to be used as the third argument for + :c:member:`~PyTypeObject.tp_richcompare` and for :c:func:`PyObject_RichCompare`: + + +----------------+------------+ + | Constant | Comparison | + +================+============+ + | :const:`Py_LT` | ``<`` | + +----------------+------------+ + | :const:`Py_LE` | ``<=`` | + +----------------+------------+ + | :const:`Py_EQ` | ``==`` | + +----------------+------------+ + | :const:`Py_NE` | ``!=`` | + +----------------+------------+ + | :const:`Py_GT` | ``>`` | + +----------------+------------+ + | :const:`Py_GE` | ``>=`` | + +----------------+------------+ + + The following macro is defined to ease writing rich comparison functions: + + .. c:function:: PyObject \*Py_RETURN_RICHCOMPARE(VAL_A, VAL_B, int 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 :c:func:`PyObject_RichCompare`. + + The return value's reference count is properly incremented. + + On error, sets an exception and returns ``NULL`` from the function. + + .. versionadded:: 3.7 + + **Inheritance:** + + Group: :attr:`tp_hash`, :attr:`tp_richcompare` + + This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_hash`: + a subtype inherits :c:member:`~PyTypeObject.tp_richcompare` and :c:member:`~PyTypeObject.tp_hash` when + the subtype's :c:member:`~PyTypeObject.tp_richcompare` and :c:member:`~PyTypeObject.tp_hash` are both + ``NULL``. + + **Default:** + + :c:type:`PyBaseObject_Type` provides a :attr:`tp_richcompare` + implementation, which may be inherited. However, if only + :attr:`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. + + +.. c:member:: Py_ssize_t PyTypeObject.tp_weaklistoffset + + 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 + :c:func:`PyObject_ClearWeakRefs` and the :c:func:`PyWeakref_\*` functions. The + instance structure needs to include a field of type :c:type:`PyObject\*` which is + initialized to ``NULL``. + + Do not confuse this field with :c:member:`~PyTypeObject.tp_weaklist`; that is the list head for + weak references to the type object itself. + + **Inheritance:** + + 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 + :c:member:`~PyTypeObject.tp_weaklistoffset`, this should not be a problem. + + When a type defined by a class statement has no :attr:`~object.__slots__` declaration, + and none of its base types are weakly referenceable, the type is made weakly + referenceable by adding a weak reference list head slot to the instance layout + and setting the :c:member:`~PyTypeObject.tp_weaklistoffset` of that slot's offset. + + When a type's :attr:`__slots__` declaration contains a slot named + :attr:`__weakref__`, that slot becomes the weak reference list head for + instances of the type, and the slot's offset is stored in the type's + :c:member:`~PyTypeObject.tp_weaklistoffset`. + + When a type's :attr:`__slots__` declaration does not contain a slot named + :attr:`__weakref__`, the type inherits its :c:member:`~PyTypeObject.tp_weaklistoffset` from its + base type. + + +.. c:member:: getiterfunc PyTypeObject.tp_iter + + An optional pointer to a function that returns an iterator for the object. Its + presence normally signals that the instances of this type are iterable (although + sequences may be iterable without this function). + + This function has the same signature as :c:func:`PyObject_GetIter`:: + + PyObject *tp_iter(PyObject *self); + + **Inheritance:** + + This field is inherited by subtypes. + + +.. c:member:: iternextfunc PyTypeObject.tp_iternext + + An optional pointer to a function that returns the next item in an iterator. + The signature is:: + + PyObject *tp_iternext(PyObject *self); + + When the iterator is exhausted, it must return ``NULL``; a :exc:`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 :c:member:`~PyTypeObject.tp_iter` function, and that + function should return the iterator instance itself (not a new iterator + instance). + + This function has the same signature as :c:func:`PyIter_Next`. + + **Inheritance:** + + This field is inherited by subtypes. + + +.. c:member:: struct PyMethodDef* PyTypeObject.tp_methods + + An optional pointer to a static ``NULL``-terminated array of :c:type:`PyMethodDef` + structures, declaring regular methods of this type. + + For each entry in the array, an entry is added to the type's dictionary (see + :c:member:`~PyTypeObject.tp_dict` below) containing a method descriptor. + + **Inheritance:** + + This field is not inherited by subtypes (methods are inherited through a + different mechanism). + + +.. c:member:: struct PyMemberDef* PyTypeObject.tp_members + + An optional pointer to a static ``NULL``-terminated array of :c:type:`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 + :c:member:`~PyTypeObject.tp_dict` below) containing a member descriptor. + + **Inheritance:** + + This field is not inherited by subtypes (members are inherited through a + different mechanism). + + +.. c:member:: struct PyGetSetDef* PyTypeObject.tp_getset + + An optional pointer to a static ``NULL``-terminated array of :c:type:`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 + :c:member:`~PyTypeObject.tp_dict` below) containing a getset descriptor. + + **Inheritance:** + + This field is not inherited by subtypes (computed attributes are inherited + through a different mechanism). + + +.. c:member:: 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. + + .. note:: + + .. from Modules/xxmodule.c + + Slot initialization is subject to the rules of initializing globals. + C99 requires the initializers to be "address constants". Function + designators like :c:func:`PyType_GenericNew`, with implicit conversion + to a pointer, are valid C99 address constants. + + However, the unary '&' operator applied to a non-static variable + like :c:func:`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, :c:member:`~PyTypeObject.tp_base` should be set in + the extension module's init function. + + **Inheritance:** + + This field is not inherited by subtypes (obviously). + + **Default:** + + This field defaults to ``&PyBaseObject_Type`` (which to Python + programmers is known as the type :class:`object`). + + +.. c:member:: PyObject* PyTypeObject.tp_dict + + The type's dictionary is stored here by :c:func:`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 :c:func:`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 :meth:`__add__`). + + **Inheritance:** + + This field is not inherited by subtypes (though the attributes defined in here + are inherited through a different mechanism). + + **Default:** + + If this field is ``NULL``, :c:func:`PyType_Ready` will assign a new + dictionary to it. + + .. warning:: + + It is not safe to use :c:func:`PyDict_SetItem` on or otherwise modify + :c:member:`~PyTypeObject.tp_dict` with the dictionary C-API. + + +.. c:member:: descrgetfunc PyTypeObject.tp_descr_get + + An optional pointer to a "descriptor get" function. + + The function signature is:: + + PyObject * tp_descr_get(PyObject *self, PyObject *obj, PyObject *type); + + .. XXX explain more? + + **Inheritance:** + + This field is inherited by subtypes. + + +.. c:member:: descrsetfunc PyTypeObject.tp_descr_set + + An optional pointer to a function for setting and deleting + a descriptor's value. + + The function signature is:: + + int tp_descr_set(PyObject *self, PyObject *obj, PyObject *value); + + The *value* argument is set to ``NULL`` to delete the value. + + .. XXX explain more? + + **Inheritance:** + + This field is inherited by subtypes. + + +.. c:member:: Py_ssize_t PyTypeObject.tp_dictoffset + + 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 + :c:func:`PyObject_GenericGetAttr`. + + Do not confuse this field with :c:member:`~PyTypeObject.tp_dict`; that is the dictionary for + attributes of the type object itself. + + If the value of this field is greater than zero, it specifies the offset from + the start of the instance structure. If the value is less than zero, it + specifies the offset from the *end* of the instance structure. A negative + offset is more expensive to use, and should only be used when the instance + structure contains a variable-length part. This is used for example to add an + instance variable dictionary to subtypes of :class:`str` or :class:`tuple`. Note + that the :c:member:`~PyTypeObject.tp_basicsize` field should account for the dictionary added to + the end in that case, even though the dictionary is not included in the basic + object layout. On a system with a pointer size of 4 bytes, + :c:member:`~PyTypeObject.tp_dictoffset` should be set to ``-4`` to indicate that the dictionary is + at the very end of the structure. + + The real dictionary offset in an instance can be computed from a negative + :c:member:`~PyTypeObject.tp_dictoffset` as follows:: + + dictoffset = tp_basicsize + abs(ob_size)*tp_itemsize + tp_dictoffset + if dictoffset is not aligned on sizeof(void*): + round up to sizeof(void*) + + where :c:member:`~PyTypeObject.tp_basicsize`, :c:member:`~PyTypeObject.tp_itemsize` and :c:member:`~PyTypeObject.tp_dictoffset` are + taken from the type object, and :attr:`ob_size` is taken from the instance. The + absolute value is taken because ints use the sign of :attr:`ob_size` to + store the sign of the number. (There's never a need to do this calculation + yourself; it is done for you by :c:func:`_PyObject_GetDictPtr`.) + + **Inheritance:** + + This field is inherited by subtypes, but see the rules listed below. A subtype + may override this offset; this means that the subtype instances store the + dictionary at a difference offset than the base type. Since the dictionary is + always found via :c:member:`~PyTypeObject.tp_dictoffset`, this should not be a problem. + + When a type defined by a class statement has no :attr:`~object.__slots__` declaration, + and none of its base types has an instance variable dictionary, a dictionary + slot is added to the instance layout and the :c:member:`~PyTypeObject.tp_dictoffset` is set to + that slot's offset. + + When a type defined by a class statement has a :attr:`__slots__` declaration, + the type inherits its :c:member:`~PyTypeObject.tp_dictoffset` from its base type. + + (Adding a slot named :attr:`~object.__dict__` to the :attr:`__slots__` declaration does + not have the expected effect, it just causes confusion. Maybe this should be + added as a feature just like :attr:`__weakref__` though.) + + **Default:** + + This slot has no default. For static types, if the field is + ``NULL`` then no :attr:`__dict__` gets created for instances. + + +.. c:member:: initproc PyTypeObject.tp_init + + An optional pointer to an instance initialization function. + + This function corresponds to the :meth:`__init__` method of classes. Like + :meth:`__init__`, it is possible to create an instance without calling + :meth:`__init__`, and it is possible to reinitialize an instance by calling its + :meth:`__init__` method again. + + The function signature is:: + + 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 + :meth:`__init__`. + + The :c:member:`~PyTypeObject.tp_init` function, if not ``NULL``, is called when an instance is + created normally by calling its type, after the type's :c:member:`~PyTypeObject.tp_new` function + has returned an instance of the type. If the :c:member:`~PyTypeObject.tp_new` function returns an + instance of some other type that is not a subtype of the original type, no + :c:member:`~PyTypeObject.tp_init` function is called; if :c:member:`~PyTypeObject.tp_new` returns an instance of a + subtype of the original type, the subtype's :c:member:`~PyTypeObject.tp_init` is called. + + Returns ``0`` on success, ``-1`` and sets an exception on error. + + **Inheritance:** + + This field is inherited by subtypes. + + **Default:** + + For static types this field does not have a default. + + +.. c:member:: allocfunc PyTypeObject.tp_alloc + + An optional pointer to an instance allocation function. + + The function signature is:: + + PyObject *tp_alloc(PyTypeObject *self, Py_ssize_t nitems); + + **Inheritance:** + + This field is inherited by static subtypes, but not by dynamic + subtypes (subtypes created by a class statement). + + **Default:** + + For dynamic subtypes, this field is always set to + :c:func:`PyType_GenericAlloc`, to force a standard heap + allocation strategy. + + For static subtypes, :c:type:`PyBaseObject_Type` uses + :c:func:`PyType_GenericAlloc`. That is the recommended value + for all statically defined types. + + +.. c:member:: newfunc PyTypeObject.tp_new + + An optional pointer to an instance creation function. + + The function signature is:: + + 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 :c:member:`~PyTypeObject.tp_new` + function is called; it may be a subtype of that type (but not an unrelated + type). + + The :c:member:`~PyTypeObject.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 :c:member:`~PyTypeObject.tp_init` handler. A good + rule of thumb is that for immutable types, all initialization should take place + in :c:member:`~PyTypeObject.tp_new`, while for mutable types, most initialization should be + deferred to :c:member:`~PyTypeObject.tp_init`. + + **Inheritance:** + + This field is inherited by subtypes, except it is not inherited by static types + whose :c:member:`~PyTypeObject.tp_base` is ``NULL`` or ``&PyBaseObject_Type``. + + **Default:** + + 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. + + +.. c:member:: 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 :c:func:`PyObject_Free`. + + **Inheritance:** + + This field is inherited by static subtypes, but not by dynamic + subtypes (subtypes created by a class statement) + + **Default:** + + In dynamic subtypes, this field is set to a deallocator suitable to + match :c:func:`PyType_GenericAlloc` and the value of the + :const:`Py_TPFLAGS_HAVE_GC` flag bit. + + For static subtypes, :c:type:`PyBaseObject_Type` uses PyObject_Del. + + +.. c:member:: inquiry PyTypeObject.tp_is_gc + + An optional pointer to a function called by the garbage collector. + + 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 + :c:member:`~PyTypeObject.tp_flags` field, and check the :const:`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, + :c:data:`PyType_Type`, defines this function to distinguish between statically + and dynamically allocated types.) + + **Inheritance:** + + This field is inherited by subtypes. + + **Default:** + + This slot has no default. If this field is ``NULL``, + :const:`Py_TPFLAGS_HAVE_GC` is used as the functional equivalent. + + +.. c:member:: PyObject* PyTypeObject.tp_bases + + Tuple of base types. + + This is set for types created by a class statement. It should be ``NULL`` for + statically defined types. + + **Inheritance:** + + This field is not inherited. + + +.. c:member:: PyObject* PyTypeObject.tp_mro + + Tuple containing the expanded set of base types, starting with the type itself + and ending with :class:`object`, in Method Resolution Order. + + + **Inheritance:** + + This field is not inherited; it is calculated fresh by + :c:func:`PyType_Ready`. + + +.. c:member:: PyObject* PyTypeObject.tp_cache + + Unused. Internal use only. + + **Inheritance:** + + This field is not inherited. + + +.. c:member:: PyObject* PyTypeObject.tp_subclasses + + List of weak references to subclasses. Internal use only. + + **Inheritance:** + + This field is not inherited. + + +.. c:member:: PyObject* PyTypeObject.tp_weaklist + + Weak reference list head, for weak references to this type object. Not + inherited. Internal use only. + + **Inheritance:** + + This field is not inherited. + + +.. c:member:: destructor PyTypeObject.tp_del + + This field is deprecated. Use :c:member:`~PyTypeObject.tp_finalize` instead. + + +.. c:member:: unsigned int PyTypeObject.tp_version_tag + + Used to index into the method cache. Internal use only. + + **Inheritance:** + + This field is not inherited. + + +.. c:member:: destructor PyTypeObject.tp_finalize + + An optional pointer to an instance finalization function. Its signature is:: + + void tp_finalize(PyObject *self); + + If :c:member:`~PyTypeObject.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. + + :c:member:`~PyTypeObject.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); + } + + For this field to be taken into account (even through inheritance), + you must also set the :const:`Py_TPFLAGS_HAVE_FINALIZE` flags bit. + + **Inheritance:** + + This field is inherited by subtypes. + + .. versionadded:: 3.4 + + .. seealso:: "Safe object finalization" (:pep:`442`) + + +.. c:member:: vectorcallfunc PyTypeObject.tp_vectorcall + + Vectorcall function to use for calls of this type object. + In other words, it is used to implement + :ref:`vectorcall ` for ``type.__call__``. + If ``tp_vectorcall`` is ``NULL``, the default call implementation + using :attr:`__new__` and :attr:`__init__` is used. + + **Inheritance:** + + This field is never inherited. + + .. versionadded:: 3.9 (the field exists since 3.8 but it's only used since 3.9) + + +Also, note that, in a garbage collected Python, :c:member:`~PyTypeObject.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. + + +.. _heap-types: + +Heap Types +---------- + +Traditionally, types defined in C code are *static*, that is, +a static :c:type:`PyTypeObject` structure is defined directly in code +and initialized using :c:func:`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 + :ref:`sub-interpreters `, so they should not + include any subinterpreter-specific state. + +Also, since :c:type:`PyTypeObject` is not part of the :ref:`stable ABI `, +any extension modules using static types must be compiled for a specific +Python minor version. + +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. + +This is done by filling a :c:type:`PyType_Spec` structure and calling +:c:func:`PyType_FromSpecWithBases`. + + +.. _number-structs: + +Number Object Structures +======================== + +.. sectionauthor:: Amaury Forgeot d'Arc + + +.. c: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 :ref:`number` section. + + .. XXX Drop the definition? + + Here is the structure definition:: + + typedef struct { + binaryfunc nb_add; + binaryfunc nb_subtract; + binaryfunc nb_multiply; + binaryfunc nb_remainder; + binaryfunc nb_divmod; + ternaryfunc nb_power; + unaryfunc nb_negative; + unaryfunc nb_positive; + unaryfunc nb_absolute; + inquiry nb_bool; + unaryfunc nb_invert; + binaryfunc nb_lshift; + binaryfunc nb_rshift; + binaryfunc nb_and; + binaryfunc nb_xor; + binaryfunc nb_or; + unaryfunc nb_int; + void *nb_reserved; + unaryfunc nb_float; + + binaryfunc nb_inplace_add; + binaryfunc nb_inplace_subtract; + binaryfunc nb_inplace_multiply; + binaryfunc nb_inplace_remainder; + ternaryfunc nb_inplace_power; + binaryfunc nb_inplace_lshift; + binaryfunc nb_inplace_rshift; + binaryfunc nb_inplace_and; + binaryfunc nb_inplace_xor; + binaryfunc nb_inplace_or; + + binaryfunc nb_floor_divide; + binaryfunc nb_true_divide; + binaryfunc nb_inplace_floor_divide; + binaryfunc nb_inplace_true_divide; + + unaryfunc nb_index; + + binaryfunc nb_matrix_multiply; + binaryfunc nb_inplace_matrix_multiply; + } PyNumberMethods; + + .. note:: + + 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. + + .. note:: + + The :c:data:`nb_reserved` field should always be ``NULL``. It + was previously called :c:data:`nb_long`, and was renamed in + Python 3.0.1. + +.. c:member:: binaryfunc PyNumberMethods.nb_add +.. c:member:: binaryfunc PyNumberMethods.nb_subtract +.. c:member:: binaryfunc PyNumberMethods.nb_multiply +.. c:member:: binaryfunc PyNumberMethods.nb_remainder +.. c:member:: binaryfunc PyNumberMethods.nb_divmod +.. c:member:: ternaryfunc PyNumberMethods.nb_power +.. c:member:: unaryfunc PyNumberMethods.nb_negative +.. c:member:: unaryfunc PyNumberMethods.nb_positive +.. c:member:: unaryfunc PyNumberMethods.nb_absolute +.. c:member:: inquiry PyNumberMethods.nb_bool +.. c:member:: unaryfunc PyNumberMethods.nb_invert +.. c:member:: binaryfunc PyNumberMethods.nb_lshift +.. c:member:: binaryfunc PyNumberMethods.nb_rshift +.. c:member:: binaryfunc PyNumberMethods.nb_and +.. c:member:: binaryfunc PyNumberMethods.nb_xor +.. c:member:: binaryfunc PyNumberMethods.nb_or +.. c:member:: unaryfunc PyNumberMethods.nb_int +.. c:member:: void *PyNumberMethods.nb_reserved +.. c:member:: unaryfunc PyNumberMethods.nb_float +.. c:member:: binaryfunc PyNumberMethods.nb_inplace_add +.. c:member:: binaryfunc PyNumberMethods.nb_inplace_subtract +.. c:member:: binaryfunc PyNumberMethods.nb_inplace_multiply +.. c:member:: binaryfunc PyNumberMethods.nb_inplace_remainder +.. c:member:: ternaryfunc PyNumberMethods.nb_inplace_power +.. c:member:: binaryfunc PyNumberMethods.nb_inplace_lshift +.. c:member:: binaryfunc PyNumberMethods.nb_inplace_rshift +.. c:member:: binaryfunc PyNumberMethods.nb_inplace_and +.. c:member:: binaryfunc PyNumberMethods.nb_inplace_xor +.. c:member:: binaryfunc PyNumberMethods.nb_inplace_or +.. c:member:: binaryfunc PyNumberMethods.nb_floor_divide +.. c:member:: binaryfunc PyNumberMethods.nb_true_divide +.. c:member:: binaryfunc PyNumberMethods.nb_inplace_floor_divide +.. c:member:: binaryfunc PyNumberMethods.nb_inplace_true_divide +.. c:member:: unaryfunc PyNumberMethods.nb_index +.. c:member:: binaryfunc PyNumberMethods.nb_matrix_multiply +.. c:member:: binaryfunc PyNumberMethods.nb_inplace_matrix_multiply + + +.. _mapping-structs: + +Mapping Object Structures +========================= + +.. sectionauthor:: Amaury Forgeot d'Arc + + +.. c:type:: PyMappingMethods + + This structure holds pointers to the functions which an object uses to + implement the mapping protocol. It has three members: + +.. c:member:: lenfunc PyMappingMethods.mp_length + + This function is used by :c:func:`PyMapping_Size` and + :c:func:`PyObject_Size`, and has the same signature. This slot may be set to + ``NULL`` if the object has no defined length. + +.. c:member:: binaryfunc PyMappingMethods.mp_subscript + + This function is used by :c:func:`PyObject_GetItem` and + :c:func:`PySequence_GetSlice`, and has the same signature as + :c:func:`!PyObject_GetItem`. This slot must be filled for the + :c:func:`PyMapping_Check` function to return ``1``, it can be ``NULL`` + otherwise. + +.. c:member:: objobjargproc PyMappingMethods.mp_ass_subscript + + This function is used by :c:func:`PyObject_SetItem`, + :c:func:`PyObject_DelItem`, :c:func:`PyObject_SetSlice` and + :c:func:`PyObject_DelSlice`. It has the same signature as + :c:func:`!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. + + +.. _sequence-structs: + +Sequence Object Structures +========================== + +.. sectionauthor:: Amaury Forgeot d'Arc + + +.. c:type:: PySequenceMethods + + This structure holds pointers to the functions which an object uses to + implement the sequence protocol. + +.. c:member:: lenfunc PySequenceMethods.sq_length + + This function is used by :c:func:`PySequence_Size` and + :c:func:`PyObject_Size`, and has the same signature. It is also used for + handling negative indices via the :c:member:`~PySequenceMethods.sq_item` + and the :c:member:`~PySequenceMethods.sq_ass_item` slots. + +.. c:member:: binaryfunc PySequenceMethods.sq_concat + + This function is used by :c:func:`PySequence_Concat` and has the same + signature. It is also used by the ``+`` operator, after trying the numeric + addition via the :c:member:`~PyNumberMethods.nb_add` slot. + +.. c:member:: ssizeargfunc PySequenceMethods.sq_repeat + + This function is used by :c:func:`PySequence_Repeat` and has the same + signature. It is also used by the ``*`` operator, after trying numeric + multiplication via the :c:member:`~PyNumberMethods.nb_multiply` slot. + +.. c:member:: ssizeargfunc PySequenceMethods.sq_item + + This function is used by :c:func:`PySequence_GetItem` and has the same + signature. It is also used by :c:func:`PyObject_GetItem`, after trying + the subscription via the :c:member:`~PyMappingMethods.mp_subscript` slot. + This slot must be filled for the :c:func:`PySequence_Check` + function to return ``1``, it can be ``NULL`` otherwise. + + Negative indexes are handled as follows: if the :attr:`sq_length` slot is + filled, it is called and the sequence length is used to compute a positive + index which is passed to :attr:`sq_item`. If :attr:`sq_length` is ``NULL``, + the index is passed as is to the function. + +.. c:member:: ssizeobjargproc PySequenceMethods.sq_ass_item + + This function is used by :c:func:`PySequence_SetItem` and has the same + signature. It is also used by :c:func:`PyObject_SetItem` and + :c:func:`PyObject_DelItem`, after trying the item assignment and deletion + via the :c:member:`~PyMappingMethods.mp_ass_subscript` slot. + This slot may be left to ``NULL`` if the object does not support + item assignment and deletion. + +.. c:member:: objobjproc PySequenceMethods.sq_contains + + This function may be used by :c:func:`PySequence_Contains` and has the same + signature. This slot may be left to ``NULL``, in this case + :c:func:`!PySequence_Contains` simply traverses the sequence until it + finds a match. + +.. c:member:: binaryfunc PySequenceMethods.sq_inplace_concat + + This function is used by :c:func:`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 :c:func:`!PySequence_InPlaceConcat` + will fall back to :c:func:`PySequence_Concat`. It is also used by the + augmented assignment ``+=``, after trying numeric in-place addition + via the :c:member:`~PyNumberMethods.nb_inplace_add` slot. + +.. c:member:: ssizeargfunc PySequenceMethods.sq_inplace_repeat + + This function is used by :c:func:`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 :c:func:`!PySequence_InPlaceRepeat` + will fall back to :c:func:`PySequence_Repeat`. It is also used by the + augmented assignment ``*=``, after trying numeric in-place multiplication + via the :c:member:`~PyNumberMethods.nb_inplace_multiply` slot. + + +.. _buffer-structs: + +Buffer Object Structures +======================== + +.. sectionauthor:: Greg J. Stein +.. sectionauthor:: Benjamin Peterson +.. sectionauthor:: Stefan Krah + +.. c:type:: PyBufferProcs + + This structure holds pointers to the functions required by the + :ref:`Buffer protocol `. The protocol defines how + an exporter object can expose its internal data to consumer objects. + +.. c:member:: 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 :c:data:`PyExc_BufferError`, + set :c:data:`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 :c:data:`view->obj` to *exporter* and increment :c:data:`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 :c:data:`view->obj` to a new reference to itself. + + * Redirect: The buffer request is redirected to the root object of the + tree. Here, :c:data:`view->obj` will be a new reference to the root + object. + + The individual fields of *view* are described in section + :ref:`Buffer structure `, the rules how an exporter + must react to specific requests are in section + :ref:`Buffer request types `. + + All memory pointed to in the :c:type:`Py_buffer` structure belongs to + the exporter and must remain valid until there are no consumers left. + :c:member:`~Py_buffer.format`, :c:member:`~Py_buffer.shape`, + :c:member:`~Py_buffer.strides`, :c:member:`~Py_buffer.suboffsets` + and :c:member:`~Py_buffer.internal` + are read-only for the consumer. + + :c:func:`PyBuffer_FillInfo` provides an easy way of exposing a simple + bytes buffer while dealing correctly with all request types. + + :c:func:`PyObject_GetBuffer` is the interface for the consumer that + wraps this function. + +.. c:member:: releasebufferproc PyBufferProcs.bf_releasebuffer + + The signature of this function is:: + + void (PyObject *exporter, Py_buffer *view); + + Handle a request to release the resources of the buffer. If no resources + need to be released, :c:member:`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 :c:member:`~Py_buffer.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 :c:data:`view->obj`, since that is + done automatically in :c:func:`PyBuffer_Release` (this scheme is + useful for breaking reference cycles). + + + :c:func:`PyBuffer_Release` is the interface for the consumer that + wraps this function. + + +.. _async-structs: + + +Async Object Structures +======================= + +.. sectionauthor:: Yury Selivanov + +.. versionadded:: 3.5 + +.. c:type:: PyAsyncMethods + + This structure holds pointers to the functions required to implement + :term:`awaitable` and :term:`asynchronous iterator` objects. + + Here is the structure definition:: + + typedef struct { + unaryfunc am_await; + unaryfunc am_aiter; + unaryfunc am_anext; + } PyAsyncMethods; + +.. c:member:: unaryfunc PyAsyncMethods.am_await + + The signature of this function is:: + + PyObject *am_await(PyObject *self); + + The returned object must be an iterator, i.e. :c:func:`PyIter_Check` must + return ``1`` for it. + + This slot may be set to ``NULL`` if an object is not an :term:`awaitable`. + +.. c:member:: unaryfunc PyAsyncMethods.am_aiter + + The signature of this function is:: + + PyObject *am_aiter(PyObject *self); + + Must return an :term:`awaitable` object. See :meth:`__anext__` for details. + + This slot may be set to ``NULL`` if an object does not implement + asynchronous iteration protocol. + +.. c:member:: unaryfunc PyAsyncMethods.am_anext + + The signature of this function is:: + + PyObject *am_anext(PyObject *self); + + Must return an :term:`awaitable` object. See :meth:`__anext__` for details. + This slot may be set to ``NULL``. + + +.. _slot-typedefs: + +Slot Type typedefs +================== + +.. c:type:: PyObject *(*allocfunc)(PyTypeObject *cls, Py_ssize_t nitems) + + 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 + :attr:`ob_refcnt` set to ``1`` and :attr:`ob_type` set to the type argument. If + the type's :c:member:`~PyTypeObject.tp_itemsize` is non-zero, the object's :attr:`ob_size` field + should be initialized to *nitems* and the length of the allocated 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 :c:member:`~PyTypeObject.tp_basicsize`. + + This function should not do any other instance initialization, not even to + allocate additional memory; that should be done by :c:member:`~PyTypeObject.tp_new`. + +.. c:type:: void (*destructor)(PyObject *) + +.. c:type:: void (*freefunc)(void *) + + See :c:member:`~PyTypeObject.tp_free`. + +.. c:type:: PyObject *(*newfunc)(PyObject *, PyObject *, PyObject *) + + See :c:member:`~PyTypeObject.tp_new`. + +.. c:type:: int (*initproc)(PyObject *, PyObject *, PyObject *) + + See :c:member:`~PyTypeObject.tp_init`. + +.. c:type:: PyObject *(*reprfunc)(PyObject *) + + See :c:member:`~PyTypeObject.tp_repr`. + +.. c:type:: PyObject *(*getattrfunc)(PyObject *self, char *attr) + + Return the value of the named attribute for the object. + +.. c:type:: int (*setattrfunc)(PyObject *self, char *attr, PyObject *value) + + Set the value of the named attribute for the object. + The value argument is set to ``NULL`` to delete the attribute. + +.. c:type:: PyObject *(*getattrofunc)(PyObject *self, PyObject *attr) + + Return the value of the named attribute for the object. + + See :c:member:`~PyTypeObject.tp_getattro`. + +.. c:type:: int (*setattrofunc)(PyObject *self, PyObject *attr, PyObject *value) + + Set the value of the named attribute for the object. + The value argument is set to ``NULL`` to delete the attribute. + + See :c:member:`~PyTypeObject.tp_setattro`. + +.. c:type:: PyObject *(*descrgetfunc)(PyObject *, PyObject *, PyObject *) + + See :c:member:`~PyTypeObject.tp_descrget`. + +.. c:type:: int (*descrsetfunc)(PyObject *, PyObject *, PyObject *) + + See :c:member:`~PyTypeObject.tp_descrset`. + +.. c:type:: Py_hash_t (*hashfunc)(PyObject *) + + See :c:member:`~PyTypeObject.tp_hash`. + +.. c:type:: PyObject *(*richcmpfunc)(PyObject *, PyObject *, int) + + See :c:member:`~PyTypeObject.tp_richcompare`. + +.. c:type:: PyObject *(*getiterfunc)(PyObject *) + + See :c:member:`~PyTypeObject.tp_iter`. + +.. c:type:: PyObject *(*iternextfunc)(PyObject *) + + See :c:member:`~PyTypeObject.tp_iternext`. + +.. c:type:: Py_ssize_t (*lenfunc)(PyObject *) + +.. c:type:: int (*getbufferproc)(PyObject *, Py_buffer *, int) + +.. c:type:: void (*releasebufferproc)(PyObject *, Py_buffer *) + +.. c:type:: PyObject *(*unaryfunc)(PyObject *) + +.. c:type:: PyObject *(*binaryfunc)(PyObject *, PyObject *) + +.. c:type:: PyObject *(*ternaryfunc)(PyObject *, PyObject *, PyObject *) + +.. c:type:: PyObject *(*ssizeargfunc)(PyObject *, Py_ssize_t) + +.. c:type:: int (*ssizeobjargproc)(PyObject *, Py_ssize_t) + +.. c:type:: int (*objobjproc)(PyObject *, PyObject *) + +.. c:type:: int (*objobjargproc)(PyObject *, PyObject *, PyObject *) + + +.. _typedef-examples: + +Examples +======== + +The following are simple examples of Python type definitions. They +include common usage you may encounter. Some demonstrate tricky corner +cases. For more examples, practical info, and a tutorial, see +:ref:`defining-new-types` and :ref:`new-types-topics`. + +A basic static type:: + + 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 = "My objects", + .tp_new = myobj_new, + .tp_dealloc = (destructor)myobj_dealloc, + .tp_repr = (reprfunc)myobj_repr, + }; + +You may also find older code (especially in the CPython code base) +with a more verbose initializer:: + + 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 */ + "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 */ + }; + +A type that supports weakrefs, instance dicts, and hashing:: + + typedef struct { + PyObject_HEAD + const char *data; + PyObject *inst_dict; + PyObject *weakreflist; + } MyObject; + + static PyTypeObject MyObject_Type = { + PyVarObject_HEAD_INIT(NULL, 0) + .tp_name = "mymod.MyObject", + .tp_basicsize = sizeof(MyObject), + .tp_doc = "My objects", + .tp_weaklistoffset = offsetof(MyObject, weakreflist), + .tp_dictoffset = offsetof(MyObject, inst_dict), + .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, + .tp_new = myobj_new, + .tp_traverse = (traverseproc)myobj_traverse, + .tp_clear = (inquiry)myobj_clear, + .tp_alloc = PyType_GenericNew, + .tp_dealloc = (destructor)myobj_dealloc, + .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):: + + 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 = "my custom str", + .tp_flags = Py_TPFLAGS_DEFAULT, + .tp_new = NULL, + .tp_repr = (reprfunc)myobj_repr, + }; + +The simplest static type (with fixed-length instances):: + + 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 *), + }; diff --git a/cpython_2/environment/repo/Doc/c-api/unicode.rst b/cpython_2/environment/repo/Doc/c-api/unicode.rst new file mode 100644 index 0000000000000000000000000000000000000000..b1787ed1ce89cf080cb1b887fe57620eee58bce5 --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/unicode.rst @@ -0,0 +1,1731 @@ +.. highlight:: c + +.. _unicodeobjects: + +Unicode Objects and Codecs +-------------------------- + +.. sectionauthor:: Marc-André Lemburg +.. sectionauthor:: Georg Brandl + +Unicode Objects +^^^^^^^^^^^^^^^ + +Since the implementation of :pep:`393` in Python 3.3, Unicode objects internally +use a variety of representations, in order to allow handling the complete range +of Unicode characters while staying memory efficient. There are special cases +for strings where all code points are below 128, 256, or 65536; otherwise, code +points must be below 1114112 (which is the full Unicode range). + +:c:type:`Py_UNICODE*` and UTF-8 representations are created on demand and cached +in the Unicode object. The :c:type:`Py_UNICODE*` representation is deprecated +and inefficient; it should be avoided in performance- or memory-sensitive +situations. + +Due to the transition between the old APIs and the new APIs, Unicode objects +can internally be in two states depending on how they were created: + +* "canonical" Unicode objects are all objects created by a non-deprecated + Unicode API. They use the most efficient representation allowed by the + implementation. + +* "legacy" Unicode objects have been created through one of the deprecated + APIs (typically :c:func:`PyUnicode_FromUnicode`) and only bear the + :c:type:`Py_UNICODE*` representation; you will have to call + :c:func:`PyUnicode_READY` on them before calling any other API. + + +Unicode Type +"""""""""""" + +These are the basic Unicode object types used for the Unicode implementation in +Python: + +.. c:type:: Py_UCS4 + Py_UCS2 + Py_UCS1 + + These types are typedefs for unsigned integer types wide enough to contain + characters of 32 bits, 16 bits and 8 bits, respectively. When dealing with + single Unicode characters, use :c:type:`Py_UCS4`. + + .. versionadded:: 3.3 + + +.. c:type:: Py_UNICODE + + This is a typedef of :c:type:`wchar_t`, which is a 16-bit type or 32-bit type + depending on the platform. + + .. versionchanged:: 3.3 + In previous versions, this was a 16-bit type or a 32-bit type depending on + whether you selected a "narrow" or "wide" Unicode version of Python at + build time. + + +.. c:type:: PyASCIIObject + PyCompactUnicodeObject + PyUnicodeObject + + These subtypes of :c:type:`PyObject` represent a Python Unicode object. In + almost all cases, they shouldn't be used directly, since all API functions + that deal with Unicode objects take and return :c:type:`PyObject` pointers. + + .. versionadded:: 3.3 + + +.. c:var:: PyTypeObject PyUnicode_Type + + This instance of :c:type:`PyTypeObject` represents the Python Unicode type. It + is exposed to Python code as ``str``. + + +The following APIs are really C macros and can be used to do fast checks and to +access internal read-only data of Unicode objects: + +.. c:function:: int PyUnicode_Check(PyObject *o) + + Return true if the object *o* is a Unicode object or an instance of a Unicode + subtype. + + +.. c:function:: int PyUnicode_CheckExact(PyObject *o) + + Return true if the object *o* is a Unicode object, but not an instance of a + subtype. + + +.. c:function:: int PyUnicode_READY(PyObject *o) + + Ensure the string object *o* is in the "canonical" representation. This is + required before using any of the access macros described below. + + .. XXX expand on when it is not required + + Returns ``0`` on success and ``-1`` with an exception set on failure, which in + particular happens if memory allocation fails. + + .. versionadded:: 3.3 + + +.. c:function:: Py_ssize_t PyUnicode_GET_LENGTH(PyObject *o) + + Return the length of the Unicode string, in code points. *o* has to be a + Unicode object in the "canonical" representation (not checked). + + .. versionadded:: 3.3 + + +.. c:function:: Py_UCS1* PyUnicode_1BYTE_DATA(PyObject *o) + Py_UCS2* PyUnicode_2BYTE_DATA(PyObject *o) + Py_UCS4* PyUnicode_4BYTE_DATA(PyObject *o) + + Return a pointer to the canonical representation cast to UCS1, UCS2 or UCS4 + integer types for direct character access. No checks are performed if the + canonical representation has the correct character size; use + :c:func:`PyUnicode_KIND` to select the right macro. Make sure + :c:func:`PyUnicode_READY` has been called before accessing this. + + .. versionadded:: 3.3 + + +.. c:macro:: PyUnicode_WCHAR_KIND + PyUnicode_1BYTE_KIND + PyUnicode_2BYTE_KIND + PyUnicode_4BYTE_KIND + + Return values of the :c:func:`PyUnicode_KIND` macro. + + .. versionadded:: 3.3 + + +.. c:function:: int PyUnicode_KIND(PyObject *o) + + Return one of the PyUnicode kind constants (see above) that indicate how many + bytes per character this Unicode object uses to store its data. *o* has to + be a Unicode object in the "canonical" representation (not checked). + + .. XXX document "0" return value? + + .. versionadded:: 3.3 + + +.. c:function:: void* PyUnicode_DATA(PyObject *o) + + Return a void pointer to the raw Unicode buffer. *o* has to be a Unicode + object in the "canonical" representation (not checked). + + .. versionadded:: 3.3 + + +.. c:function:: void PyUnicode_WRITE(int kind, void *data, Py_ssize_t index, \ + Py_UCS4 value) + + Write into a canonical representation *data* (as obtained with + :c:func:`PyUnicode_DATA`). This macro does not do any sanity checks and is + intended for usage in loops. The caller should cache the *kind* value and + *data* pointer as obtained from other macro calls. *index* is the index in + the string (starts at 0) and *value* is the new code point value which should + be written to that location. + + .. versionadded:: 3.3 + + +.. c:function:: Py_UCS4 PyUnicode_READ(int kind, void *data, Py_ssize_t index) + + Read a code point from a canonical representation *data* (as obtained with + :c:func:`PyUnicode_DATA`). No checks or ready calls are performed. + + .. versionadded:: 3.3 + + +.. c:function:: Py_UCS4 PyUnicode_READ_CHAR(PyObject *o, Py_ssize_t index) + + Read a character from a Unicode object *o*, which must be in the "canonical" + representation. This is less efficient than :c:func:`PyUnicode_READ` if you + do multiple consecutive reads. + + .. versionadded:: 3.3 + + +.. c:function:: PyUnicode_MAX_CHAR_VALUE(PyObject *o) + + Return the maximum code point that is suitable for creating another string + based on *o*, which must be in the "canonical" representation. This is + always an approximation but more efficient than iterating over the string. + + .. versionadded:: 3.3 + + +.. c:function:: Py_ssize_t PyUnicode_GET_SIZE(PyObject *o) + + Return the size of the deprecated :c:type:`Py_UNICODE` representation, in + code units (this includes surrogate pairs as 2 units). *o* has to be a + Unicode object (not checked). + + .. deprecated-removed:: 3.3 4.0 + Part of the old-style Unicode API, please migrate to using + :c:func:`PyUnicode_GET_LENGTH`. + + +.. c:function:: Py_ssize_t PyUnicode_GET_DATA_SIZE(PyObject *o) + + Return the size of the deprecated :c:type:`Py_UNICODE` representation in + bytes. *o* has to be a Unicode object (not checked). + + .. deprecated-removed:: 3.3 4.0 + Part of the old-style Unicode API, please migrate to using + :c:func:`PyUnicode_GET_LENGTH`. + + +.. c:function:: Py_UNICODE* PyUnicode_AS_UNICODE(PyObject *o) + const char* PyUnicode_AS_DATA(PyObject *o) + + Return a pointer to a :c:type:`Py_UNICODE` representation of the object. The + returned buffer is always terminated with an extra null code point. It + may also contain embedded null code points, which would cause the string + to be truncated when used in most C functions. The ``AS_DATA`` form + casts the pointer to :c:type:`const char *`. The *o* argument has to be + a Unicode object (not checked). + + .. versionchanged:: 3.3 + This macro is now inefficient -- because in many cases the + :c:type:`Py_UNICODE` representation does not exist and needs to be created + -- and can fail (return ``NULL`` with an exception set). Try to port the + code to use the new :c:func:`PyUnicode_nBYTE_DATA` macros or use + :c:func:`PyUnicode_WRITE` or :c:func:`PyUnicode_READ`. + + .. deprecated-removed:: 3.3 4.0 + Part of the old-style Unicode API, please migrate to using the + :c:func:`PyUnicode_nBYTE_DATA` family of macros. + + +.. c:function:: int PyUnicode_IsIdentifier(PyObject *o) + + Return ``1`` if the string is a valid identifier according to the language + definition, section :ref:`identifiers`. Return ``0`` otherwise. + + .. versionchanged:: 3.9 + The function does not call :c:func:`Py_FatalError` anymore if the string + is not ready. + + +Unicode Character Properties +"""""""""""""""""""""""""""" + +Unicode provides many different character properties. The most often needed ones +are available through these macros which are mapped to C functions depending on +the Python configuration. + + +.. c:function:: int Py_UNICODE_ISSPACE(Py_UNICODE ch) + + Return ``1`` or ``0`` depending on whether *ch* is a whitespace character. + + +.. c:function:: int Py_UNICODE_ISLOWER(Py_UNICODE ch) + + Return ``1`` or ``0`` depending on whether *ch* is a lowercase character. + + +.. c:function:: int Py_UNICODE_ISUPPER(Py_UNICODE ch) + + Return ``1`` or ``0`` depending on whether *ch* is an uppercase character. + + +.. c:function:: int Py_UNICODE_ISTITLE(Py_UNICODE ch) + + Return ``1`` or ``0`` depending on whether *ch* is a titlecase character. + + +.. c:function:: int Py_UNICODE_ISLINEBREAK(Py_UNICODE ch) + + Return ``1`` or ``0`` depending on whether *ch* is a linebreak character. + + +.. c:function:: int Py_UNICODE_ISDECIMAL(Py_UNICODE ch) + + Return ``1`` or ``0`` depending on whether *ch* is a decimal character. + + +.. c:function:: int Py_UNICODE_ISDIGIT(Py_UNICODE ch) + + Return ``1`` or ``0`` depending on whether *ch* is a digit character. + + +.. c:function:: int Py_UNICODE_ISNUMERIC(Py_UNICODE ch) + + Return ``1`` or ``0`` depending on whether *ch* is a numeric character. + + +.. c:function:: int Py_UNICODE_ISALPHA(Py_UNICODE ch) + + Return ``1`` or ``0`` depending on whether *ch* is an alphabetic character. + + +.. c:function:: int Py_UNICODE_ISALNUM(Py_UNICODE ch) + + Return ``1`` or ``0`` depending on whether *ch* is an alphanumeric character. + + +.. c:function:: int Py_UNICODE_ISPRINTABLE(Py_UNICODE ch) + + Return ``1`` or ``0`` depending on whether *ch* is a printable character. + Nonprintable characters are those characters defined in the Unicode character + database as "Other" or "Separator", excepting the ASCII space (0x20) which is + considered printable. (Note that printable characters in this context are + those which should not be escaped when :func:`repr` is invoked on a string. + It has no bearing on the handling of strings written to :data:`sys.stdout` or + :data:`sys.stderr`.) + + +These APIs can be used for fast direct character conversions: + + +.. c:function:: Py_UNICODE Py_UNICODE_TOLOWER(Py_UNICODE ch) + + Return the character *ch* converted to lower case. + + .. deprecated:: 3.3 + This function uses simple case mappings. + + +.. c:function:: Py_UNICODE Py_UNICODE_TOUPPER(Py_UNICODE ch) + + Return the character *ch* converted to upper case. + + .. deprecated:: 3.3 + This function uses simple case mappings. + + +.. c:function:: Py_UNICODE Py_UNICODE_TOTITLE(Py_UNICODE ch) + + Return the character *ch* converted to title case. + + .. deprecated:: 3.3 + This function uses simple case mappings. + + +.. c:function:: int Py_UNICODE_TODECIMAL(Py_UNICODE ch) + + Return the character *ch* converted to a decimal positive integer. Return + ``-1`` if this is not possible. This macro does not raise exceptions. + + +.. c:function:: int Py_UNICODE_TODIGIT(Py_UNICODE ch) + + Return the character *ch* converted to a single digit integer. Return ``-1`` if + this is not possible. This macro does not raise exceptions. + + +.. c:function:: double Py_UNICODE_TONUMERIC(Py_UNICODE ch) + + Return the character *ch* converted to a double. Return ``-1.0`` if this is not + possible. This macro does not raise exceptions. + + +These APIs can be used to work with surrogates: + +.. c:macro:: Py_UNICODE_IS_SURROGATE(ch) + + Check if *ch* is a surrogate (``0xD800 <= ch <= 0xDFFF``). + +.. c:macro:: Py_UNICODE_IS_HIGH_SURROGATE(ch) + + Check if *ch* is a high surrogate (``0xD800 <= ch <= 0xDBFF``). + +.. c:macro:: Py_UNICODE_IS_LOW_SURROGATE(ch) + + Check if *ch* is a low surrogate (``0xDC00 <= ch <= 0xDFFF``). + +.. c:macro:: Py_UNICODE_JOIN_SURROGATES(high, low) + + Join two surrogate characters and return a single Py_UCS4 value. + *high* and *low* are respectively the leading and trailing surrogates in a + surrogate pair. + + +Creating and accessing Unicode strings +"""""""""""""""""""""""""""""""""""""" + +To create Unicode objects and access their basic sequence properties, use these +APIs: + +.. c:function:: PyObject* PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar) + + Create a new Unicode object. *maxchar* should be the true maximum code point + to be placed in the string. As an approximation, it can be rounded up to the + nearest value in the sequence 127, 255, 65535, 1114111. + + This is the recommended way to allocate a new Unicode object. Objects + created using this function are not resizable. + + .. versionadded:: 3.3 + + +.. c:function:: PyObject* PyUnicode_FromKindAndData(int kind, const void *buffer, \ + Py_ssize_t size) + + Create a new Unicode object with the given *kind* (possible values are + :c:macro:`PyUnicode_1BYTE_KIND` etc., as returned by + :c:func:`PyUnicode_KIND`). The *buffer* must point to an array of *size* + units of 1, 2 or 4 bytes per character, as given by the kind. + + .. versionadded:: 3.3 + + +.. c:function:: PyObject* PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size) + + Create a Unicode object from the char buffer *u*. The bytes will be + interpreted as being UTF-8 encoded. The buffer is copied into the new + object. If the buffer is not ``NULL``, the return value might be a shared + object, i.e. modification of the data is not allowed. + + If *u* is ``NULL``, this function behaves like :c:func:`PyUnicode_FromUnicode` + with the buffer set to ``NULL``. This usage is deprecated in favor of + :c:func:`PyUnicode_New`. + + +.. c:function:: PyObject *PyUnicode_FromString(const char *u) + + Create a Unicode object from a UTF-8 encoded null-terminated char buffer + *u*. + + +.. c:function:: PyObject* PyUnicode_FromFormat(const char *format, ...) + + Take a C :c:func:`printf`\ -style *format* string and a variable number of + arguments, calculate the size of the resulting Python Unicode string and return + a string with the values formatted into it. The variable arguments must be C + types and must correspond exactly to the format characters in the *format* + ASCII-encoded string. The following format characters are allowed: + + .. % This should be exactly the same as the table in PyErr_Format. + .. % The descriptions for %zd and %zu are wrong, but the truth is complicated + .. % because not all compilers support the %z width modifier -- we fake it + .. % when necessary via interpolating PY_FORMAT_SIZE_T. + .. % Similar comments apply to the %ll width modifier and + + .. tabularcolumns:: |l|l|L| + + +-------------------+---------------------+----------------------------------+ + | Format Characters | Type | Comment | + +===================+=====================+==================================+ + | :attr:`%%` | *n/a* | The literal % character. | + +-------------------+---------------------+----------------------------------+ + | :attr:`%c` | int | A single character, | + | | | represented as a C int. | + +-------------------+---------------------+----------------------------------+ + | :attr:`%d` | int | Equivalent to | + | | | ``printf("%d")``. [1]_ | + +-------------------+---------------------+----------------------------------+ + | :attr:`%u` | unsigned int | Equivalent to | + | | | ``printf("%u")``. [1]_ | + +-------------------+---------------------+----------------------------------+ + | :attr:`%ld` | long | Equivalent to | + | | | ``printf("%ld")``. [1]_ | + +-------------------+---------------------+----------------------------------+ + | :attr:`%li` | long | Equivalent to | + | | | ``printf("%li")``. [1]_ | + +-------------------+---------------------+----------------------------------+ + | :attr:`%lu` | unsigned long | Equivalent to | + | | | ``printf("%lu")``. [1]_ | + +-------------------+---------------------+----------------------------------+ + | :attr:`%lld` | long long | Equivalent to | + | | | ``printf("%lld")``. [1]_ | + +-------------------+---------------------+----------------------------------+ + | :attr:`%lli` | long long | Equivalent to | + | | | ``printf("%lli")``. [1]_ | + +-------------------+---------------------+----------------------------------+ + | :attr:`%llu` | unsigned long long | Equivalent to | + | | | ``printf("%llu")``. [1]_ | + +-------------------+---------------------+----------------------------------+ + | :attr:`%zd` | Py_ssize_t | Equivalent to | + | | | ``printf("%zd")``. [1]_ | + +-------------------+---------------------+----------------------------------+ + | :attr:`%zi` | Py_ssize_t | Equivalent to | + | | | ``printf("%zi")``. [1]_ | + +-------------------+---------------------+----------------------------------+ + | :attr:`%zu` | size_t | Equivalent to | + | | | ``printf("%zu")``. [1]_ | + +-------------------+---------------------+----------------------------------+ + | :attr:`%i` | int | Equivalent to | + | | | ``printf("%i")``. [1]_ | + +-------------------+---------------------+----------------------------------+ + | :attr:`%x` | int | Equivalent to | + | | | ``printf("%x")``. [1]_ | + +-------------------+---------------------+----------------------------------+ + | :attr:`%s` | const char\* | A null-terminated C character | + | | | array. | + +-------------------+---------------------+----------------------------------+ + | :attr:`%p` | const void\* | The hex representation of a C | + | | | pointer. Mostly equivalent to | + | | | ``printf("%p")`` except that | + | | | it is guaranteed to start with | + | | | the literal ``0x`` regardless | + | | | of what the platform's | + | | | ``printf`` yields. | + +-------------------+---------------------+----------------------------------+ + | :attr:`%A` | PyObject\* | The result of calling | + | | | :func:`ascii`. | + +-------------------+---------------------+----------------------------------+ + | :attr:`%U` | PyObject\* | A Unicode object. | + +-------------------+---------------------+----------------------------------+ + | :attr:`%V` | PyObject\*, | A Unicode object (which may be | + | | const char\* | ``NULL``) and a null-terminated | + | | | C character array as a second | + | | | parameter (which will be used, | + | | | if the first parameter is | + | | | ``NULL``). | + +-------------------+---------------------+----------------------------------+ + | :attr:`%S` | PyObject\* | The result of calling | + | | | :c:func:`PyObject_Str`. | + +-------------------+---------------------+----------------------------------+ + | :attr:`%R` | PyObject\* | The result of calling | + | | | :c:func:`PyObject_Repr`. | + +-------------------+---------------------+----------------------------------+ + + An unrecognized format character causes all the rest of the format string to be + copied as-is to the result string, and any extra arguments discarded. + + .. note:: + The width formatter unit is number of characters rather than bytes. + The precision formatter unit is number of bytes for ``"%s"`` and + ``"%V"`` (if the ``PyObject*`` argument is ``NULL``), and a number of + characters for ``"%A"``, ``"%U"``, ``"%S"``, ``"%R"`` and ``"%V"`` + (if the ``PyObject*`` argument is not ``NULL``). + + .. [1] For integer specifiers (d, u, ld, li, lu, lld, lli, llu, zd, zi, + zu, i, x): the 0-conversion flag has effect even when a precision is given. + + .. versionchanged:: 3.2 + Support for ``"%lld"`` and ``"%llu"`` added. + + .. versionchanged:: 3.3 + Support for ``"%li"``, ``"%lli"`` and ``"%zi"`` added. + + .. versionchanged:: 3.4 + Support width and precision formatter for ``"%s"``, ``"%A"``, ``"%U"``, + ``"%V"``, ``"%S"``, ``"%R"`` added. + + +.. c:function:: PyObject* PyUnicode_FromFormatV(const char *format, va_list vargs) + + Identical to :c:func:`PyUnicode_FromFormat` except that it takes exactly two + arguments. + + +.. c:function:: PyObject* PyUnicode_FromEncodedObject(PyObject *obj, \ + const char *encoding, const char *errors) + + Decode an encoded object *obj* to a Unicode object. + + :class:`bytes`, :class:`bytearray` and other + :term:`bytes-like objects ` + are decoded according to the given *encoding* and using the error handling + defined by *errors*. Both can be ``NULL`` to have the interface use the default + values (see :ref:`builtincodecs` for details). + + All other objects, including Unicode objects, cause a :exc:`TypeError` to be + set. + + The API returns ``NULL`` if there was an error. The caller is responsible for + decref'ing the returned objects. + + +.. c:function:: Py_ssize_t PyUnicode_GetLength(PyObject *unicode) + + Return the length of the Unicode object, in code points. + + .. versionadded:: 3.3 + + +.. c:function:: Py_ssize_t PyUnicode_CopyCharacters(PyObject *to, \ + Py_ssize_t to_start, \ + PyObject *from, \ + Py_ssize_t from_start, \ + Py_ssize_t how_many) + + Copy characters from one Unicode object into another. This function performs + character conversion when necessary and falls back to :c:func:`memcpy` if + possible. Returns ``-1`` and sets an exception on error, otherwise returns + the number of copied characters. + + .. versionadded:: 3.3 + + +.. c:function:: Py_ssize_t PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, \ + Py_ssize_t length, Py_UCS4 fill_char) + + Fill a string with a character: write *fill_char* into + ``unicode[start:start+length]``. + + Fail if *fill_char* is bigger than the string maximum character, or if the + string has more than 1 reference. + + Return the number of written character, or return ``-1`` and raise an + exception on error. + + .. versionadded:: 3.3 + + +.. c:function:: int PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, \ + Py_UCS4 character) + + Write a character to a string. The string must have been created through + :c:func:`PyUnicode_New`. Since Unicode strings are supposed to be immutable, + the string must not be shared, or have been hashed yet. + + This function checks that *unicode* is a Unicode object, that the index is + not out of bounds, and that the object can be modified safely (i.e. that it + its reference count is one). + + .. versionadded:: 3.3 + + +.. c:function:: Py_UCS4 PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index) + + Read a character from a string. This function checks that *unicode* is a + Unicode object and the index is not out of bounds, in contrast to the macro + version :c:func:`PyUnicode_READ_CHAR`. + + .. versionadded:: 3.3 + + +.. c:function:: PyObject* PyUnicode_Substring(PyObject *str, Py_ssize_t start, \ + Py_ssize_t end) + + Return a substring of *str*, from character index *start* (included) to + character index *end* (excluded). Negative indices are not supported. + + .. versionadded:: 3.3 + + +.. c:function:: Py_UCS4* PyUnicode_AsUCS4(PyObject *u, Py_UCS4 *buffer, \ + Py_ssize_t buflen, int copy_null) + + Copy the string *u* into a UCS4 buffer, including a null character, if + *copy_null* is set. Returns ``NULL`` and sets an exception on error (in + particular, a :exc:`SystemError` if *buflen* is smaller than the length of + *u*). *buffer* is returned on success. + + .. versionadded:: 3.3 + + +.. c:function:: Py_UCS4* PyUnicode_AsUCS4Copy(PyObject *u) + + Copy the string *u* into a new UCS4 buffer that is allocated using + :c:func:`PyMem_Malloc`. If this fails, ``NULL`` is returned with a + :exc:`MemoryError` set. The returned buffer always has an extra + null code point appended. + + .. versionadded:: 3.3 + + +Deprecated Py_UNICODE APIs +"""""""""""""""""""""""""" + +.. deprecated-removed:: 3.3 4.0 + +These API functions are deprecated with the implementation of :pep:`393`. +Extension modules can continue using them, as they will not be removed in Python +3.x, but need to be aware that their use can now cause performance and memory hits. + + +.. c:function:: PyObject* PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size) + + Create a Unicode object from the Py_UNICODE buffer *u* of the given size. *u* + may be ``NULL`` which causes the contents to be undefined. It is the user's + responsibility to fill in the needed data. The buffer is copied into the new + object. + + If the buffer is not ``NULL``, the return value might be a shared object. + Therefore, modification of the resulting Unicode object is only allowed when + *u* is ``NULL``. + + If the buffer is ``NULL``, :c:func:`PyUnicode_READY` must be called once the + string content has been filled before using any of the access macros such as + :c:func:`PyUnicode_KIND`. + + Please migrate to using :c:func:`PyUnicode_FromKindAndData`, + :c:func:`PyUnicode_FromWideChar` or :c:func:`PyUnicode_New`. + + +.. c:function:: Py_UNICODE* PyUnicode_AsUnicode(PyObject *unicode) + + Return a read-only pointer to the Unicode object's internal + :c:type:`Py_UNICODE` buffer, or ``NULL`` on error. This will create the + :c:type:`Py_UNICODE*` representation of the object if it is not yet + available. The buffer is always terminated with an extra null code point. + Note that the resulting :c:type:`Py_UNICODE` string may also contain + embedded null code points, which would cause the string to be truncated when + used in most C functions. + + Please migrate to using :c:func:`PyUnicode_AsUCS4`, + :c:func:`PyUnicode_AsWideChar`, :c:func:`PyUnicode_ReadChar` or similar new + APIs. + + +.. c:function:: PyObject* PyUnicode_TransformDecimalToASCII(Py_UNICODE *s, Py_ssize_t size) + + Create a Unicode object by replacing all decimal digits in + :c:type:`Py_UNICODE` buffer of the given *size* by ASCII digits 0--9 + according to their decimal value. Return ``NULL`` if an exception occurs. + + +.. c:function:: Py_UNICODE* PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size) + + Like :c:func:`PyUnicode_AsUnicode`, but also saves the :c:func:`Py_UNICODE` + array length (excluding the extra null terminator) in *size*. + Note that the resulting :c:type:`Py_UNICODE*` string + may contain embedded null code points, which would cause the string to be + truncated when used in most C functions. + + .. versionadded:: 3.3 + + +.. c:function:: Py_UNICODE* PyUnicode_AsUnicodeCopy(PyObject *unicode) + + Create a copy of a Unicode string ending with a null code point. Return ``NULL`` + and raise a :exc:`MemoryError` exception on memory allocation failure, + otherwise return a new allocated buffer (use :c:func:`PyMem_Free` to free + the buffer). Note that the resulting :c:type:`Py_UNICODE*` string may + contain embedded null code points, which would cause the string to be + truncated when used in most C functions. + + .. versionadded:: 3.2 + + Please migrate to using :c:func:`PyUnicode_AsUCS4Copy` or similar new APIs. + + +.. c:function:: Py_ssize_t PyUnicode_GetSize(PyObject *unicode) + + Return the size of the deprecated :c:type:`Py_UNICODE` representation, in + code units (this includes surrogate pairs as 2 units). + + Please migrate to using :c:func:`PyUnicode_GetLength`. + + +.. c:function:: PyObject* PyUnicode_FromObject(PyObject *obj) + + Copy an instance of a Unicode subtype to a new true Unicode object if + necessary. If *obj* is already a true Unicode object (not a subtype), + return the reference with incremented refcount. + + Objects other than Unicode or its subtypes will cause a :exc:`TypeError`. + + +Locale Encoding +""""""""""""""" + +The current locale encoding can be used to decode text from the operating +system. + +.. c:function:: PyObject* PyUnicode_DecodeLocaleAndSize(const char *str, \ + Py_ssize_t len, \ + const char *errors) + + Decode a string from UTF-8 on Android and VxWorks, or from the current + locale encoding on other platforms. The supported + error handlers are ``"strict"`` and ``"surrogateescape"`` + (:pep:`383`). The decoder uses ``"strict"`` error handler if + *errors* is ``NULL``. *str* must end with a null character but + cannot contain embedded null characters. + + Use :c:func:`PyUnicode_DecodeFSDefaultAndSize` to decode a string from + :c:data:`Py_FileSystemDefaultEncoding` (the locale encoding read at + Python startup). + + This function ignores the Python UTF-8 mode. + + .. seealso:: + + The :c:func:`Py_DecodeLocale` function. + + .. versionadded:: 3.3 + + .. versionchanged:: 3.7 + The function now also uses the current locale encoding for the + ``surrogateescape`` error handler, except on Android. Previously, :c:func:`Py_DecodeLocale` + was used for the ``surrogateescape``, and the current locale encoding was + used for ``strict``. + + +.. c:function:: PyObject* PyUnicode_DecodeLocale(const char *str, const char *errors) + + Similar to :c:func:`PyUnicode_DecodeLocaleAndSize`, but compute the string + length using :c:func:`strlen`. + + .. versionadded:: 3.3 + + +.. c:function:: PyObject* PyUnicode_EncodeLocale(PyObject *unicode, const char *errors) + + Encode a Unicode object to UTF-8 on Android and VxWorks, or to the current + locale encoding on other platforms. The + supported error handlers are ``"strict"`` and ``"surrogateescape"`` + (:pep:`383`). The encoder uses ``"strict"`` error handler if + *errors* is ``NULL``. Return a :class:`bytes` object. *unicode* cannot + contain embedded null characters. + + Use :c:func:`PyUnicode_EncodeFSDefault` to encode a string to + :c:data:`Py_FileSystemDefaultEncoding` (the locale encoding read at + Python startup). + + This function ignores the Python UTF-8 mode. + + .. seealso:: + + The :c:func:`Py_EncodeLocale` function. + + .. versionadded:: 3.3 + + .. versionchanged:: 3.7 + The function now also uses the current locale encoding for the + ``surrogateescape`` error handler, except on Android. Previously, + :c:func:`Py_EncodeLocale` + was used for the ``surrogateescape``, and the current locale encoding was + used for ``strict``. + + +File System Encoding +"""""""""""""""""""" + +To encode and decode file names and other environment strings, +:c:data:`Py_FileSystemDefaultEncoding` should be used as the encoding, and +:c:data:`Py_FileSystemDefaultEncodeErrors` should be used as the error handler +(:pep:`383` and :pep:`529`). To encode file names to :class:`bytes` during +argument parsing, the ``"O&"`` converter should be used, passing +:c:func:`PyUnicode_FSConverter` as the conversion function: + +.. c:function:: int PyUnicode_FSConverter(PyObject* obj, void* result) + + ParseTuple converter: encode :class:`str` objects -- obtained directly or + through the :class:`os.PathLike` interface -- to :class:`bytes` using + :c:func:`PyUnicode_EncodeFSDefault`; :class:`bytes` objects are output as-is. + *result* must be a :c:type:`PyBytesObject*` which must be released when it is + no longer used. + + .. versionadded:: 3.1 + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + +To decode file names to :class:`str` during argument parsing, the ``"O&"`` +converter should be used, passing :c:func:`PyUnicode_FSDecoder` as the +conversion function: + +.. c:function:: int PyUnicode_FSDecoder(PyObject* obj, void* result) + + ParseTuple converter: decode :class:`bytes` objects -- obtained either + directly or indirectly through the :class:`os.PathLike` interface -- to + :class:`str` using :c:func:`PyUnicode_DecodeFSDefaultAndSize`; :class:`str` + objects are output as-is. *result* must be a :c:type:`PyUnicodeObject*` which + must be released when it is no longer used. + + .. versionadded:: 3.2 + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. c:function:: PyObject* PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size) + + Decode a string using :c:data:`Py_FileSystemDefaultEncoding` and the + :c:data:`Py_FileSystemDefaultEncodeErrors` error handler. + + If :c:data:`Py_FileSystemDefaultEncoding` is not set, fall back to the + locale encoding. + + :c:data:`Py_FileSystemDefaultEncoding` is initialized at startup from the + locale encoding and cannot be modified later. If you need to decode a string + from the current locale encoding, use + :c:func:`PyUnicode_DecodeLocaleAndSize`. + + .. seealso:: + + The :c:func:`Py_DecodeLocale` function. + + .. versionchanged:: 3.6 + Use :c:data:`Py_FileSystemDefaultEncodeErrors` error handler. + + +.. c:function:: PyObject* PyUnicode_DecodeFSDefault(const char *s) + + Decode a null-terminated string using :c:data:`Py_FileSystemDefaultEncoding` + and the :c:data:`Py_FileSystemDefaultEncodeErrors` error handler. + + If :c:data:`Py_FileSystemDefaultEncoding` is not set, fall back to the + locale encoding. + + Use :c:func:`PyUnicode_DecodeFSDefaultAndSize` if you know the string length. + + .. versionchanged:: 3.6 + Use :c:data:`Py_FileSystemDefaultEncodeErrors` error handler. + + +.. c:function:: PyObject* PyUnicode_EncodeFSDefault(PyObject *unicode) + + Encode a Unicode object to :c:data:`Py_FileSystemDefaultEncoding` with the + :c:data:`Py_FileSystemDefaultEncodeErrors` error handler, and return + :class:`bytes`. Note that the resulting :class:`bytes` object may contain + null bytes. + + If :c:data:`Py_FileSystemDefaultEncoding` is not set, fall back to the + locale encoding. + + :c:data:`Py_FileSystemDefaultEncoding` is initialized at startup from the + locale encoding and cannot be modified later. If you need to encode a string + to the current locale encoding, use :c:func:`PyUnicode_EncodeLocale`. + + .. seealso:: + + The :c:func:`Py_EncodeLocale` function. + + .. versionadded:: 3.2 + + .. versionchanged:: 3.6 + Use :c:data:`Py_FileSystemDefaultEncodeErrors` error handler. + +wchar_t Support +""""""""""""""" + +:c:type:`wchar_t` support for platforms which support it: + +.. c:function:: PyObject* PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size) + + Create a Unicode object from the :c:type:`wchar_t` buffer *w* of the given *size*. + Passing ``-1`` as the *size* indicates that the function must itself compute the length, + using wcslen. + Return ``NULL`` on failure. + + +.. c:function:: Py_ssize_t PyUnicode_AsWideChar(PyObject *unicode, wchar_t *w, Py_ssize_t size) + + Copy the Unicode object contents into the :c:type:`wchar_t` buffer *w*. At most + *size* :c:type:`wchar_t` characters are copied (excluding a possibly trailing + null termination character). Return the number of :c:type:`wchar_t` characters + copied or ``-1`` in case of an error. Note that the resulting :c:type:`wchar_t*` + string may or may not be null-terminated. It is the responsibility of the caller + to make sure that the :c:type:`wchar_t*` string is null-terminated in case this is + required by the application. Also, note that the :c:type:`wchar_t*` string + might contain null characters, which would cause the string to be truncated + when used with most C functions. + + +.. c:function:: wchar_t* PyUnicode_AsWideCharString(PyObject *unicode, Py_ssize_t *size) + + Convert the Unicode object to a wide character string. The output string + always ends with a null character. If *size* is not ``NULL``, write the number + of wide characters (excluding the trailing null termination character) into + *\*size*. Note that the resulting :c:type:`wchar_t` string might contain + null characters, which would cause the string to be truncated when used with + most C functions. If *size* is ``NULL`` and the :c:type:`wchar_t*` string + contains null characters a :exc:`ValueError` is raised. + + Returns a buffer allocated by :c:func:`PyMem_Alloc` (use + :c:func:`PyMem_Free` to free it) on success. On error, returns ``NULL`` + and *\*size* is undefined. Raises a :exc:`MemoryError` if memory allocation + is failed. + + .. versionadded:: 3.2 + + .. versionchanged:: 3.7 + Raises a :exc:`ValueError` if *size* is ``NULL`` and the :c:type:`wchar_t*` + string contains null characters. + + +.. _builtincodecs: + +Built-in Codecs +^^^^^^^^^^^^^^^ + +Python provides a set of built-in codecs which are written in C for speed. All of +these codecs are directly usable via the following functions. + +Many of the following APIs take two arguments encoding and errors, and they +have the same semantics as the ones of the built-in :func:`str` string object +constructor. + +Setting encoding to ``NULL`` causes the default encoding to be used +which is UTF-8. The file system calls should use +:c:func:`PyUnicode_FSConverter` for encoding file names. This uses the +variable :c:data:`Py_FileSystemDefaultEncoding` internally. This +variable should be treated as read-only: on some systems, it will be a +pointer to a static string, on others, it will change at run-time +(such as when the application invokes setlocale). + +Error handling is set by errors which may also be set to ``NULL`` meaning to use +the default handling defined for the codec. Default error handling for all +built-in codecs is "strict" (:exc:`ValueError` is raised). + +The codecs all use a similar interface. Only deviation from the following +generic ones are documented for simplicity. + + +Generic Codecs +"""""""""""""" + +These are the generic codec APIs: + + +.. c:function:: PyObject* PyUnicode_Decode(const char *s, Py_ssize_t size, \ + const char *encoding, const char *errors) + + Create a Unicode object by decoding *size* bytes of the encoded string *s*. + *encoding* and *errors* have the same meaning as the parameters of the same name + in the :func:`str` built-in function. The codec to be used is looked up + using the Python codec registry. Return ``NULL`` if an exception was raised by + the codec. + + +.. c:function:: PyObject* PyUnicode_AsEncodedString(PyObject *unicode, \ + const char *encoding, const char *errors) + + Encode a Unicode object and return the result as Python bytes object. + *encoding* and *errors* have the same meaning as the parameters of the same + name in the Unicode :meth:`~str.encode` method. The codec to be used is looked up + using the Python codec registry. Return ``NULL`` if an exception was raised by + the codec. + + +.. c:function:: PyObject* PyUnicode_Encode(const Py_UNICODE *s, Py_ssize_t size, \ + const char *encoding, const char *errors) + + Encode the :c:type:`Py_UNICODE` buffer *s* of the given *size* and return a Python + bytes object. *encoding* and *errors* have the same meaning as the + parameters of the same name in the Unicode :meth:`~str.encode` method. The codec + to be used is looked up using the Python codec registry. Return ``NULL`` if an + exception was raised by the codec. + + .. deprecated-removed:: 3.3 4.0 + Part of the old-style :c:type:`Py_UNICODE` API; please migrate to using + :c:func:`PyUnicode_AsEncodedString`. + + +UTF-8 Codecs +"""""""""""" + +These are the UTF-8 codec APIs: + + +.. c:function:: PyObject* PyUnicode_DecodeUTF8(const char *s, Py_ssize_t size, const char *errors) + + Create a Unicode object by decoding *size* bytes of the UTF-8 encoded string + *s*. Return ``NULL`` if an exception was raised by the codec. + + +.. c:function:: PyObject* PyUnicode_DecodeUTF8Stateful(const char *s, Py_ssize_t size, \ + const char *errors, Py_ssize_t *consumed) + + If *consumed* is ``NULL``, behave like :c:func:`PyUnicode_DecodeUTF8`. If + *consumed* is not ``NULL``, trailing incomplete UTF-8 byte sequences will not be + treated as an error. Those bytes will not be decoded and the number of bytes + that have been decoded will be stored in *consumed*. + + +.. c:function:: PyObject* PyUnicode_AsUTF8String(PyObject *unicode) + + Encode a Unicode object using UTF-8 and return the result as Python bytes + object. Error handling is "strict". Return ``NULL`` if an exception was + raised by the codec. + + +.. c:function:: const char* PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *size) + + Return a pointer to the UTF-8 encoding of the Unicode object, and + store the size of the encoded representation (in bytes) in *size*. The + *size* argument can be ``NULL``; in this case no size will be stored. The + returned buffer always has an extra null byte appended (not included in + *size*), regardless of whether there are any other null code points. + + In the case of an error, ``NULL`` is returned with an exception set and no + *size* is stored. + + This caches the UTF-8 representation of the string in the Unicode object, and + subsequent calls will return a pointer to the same buffer. The caller is not + responsible for deallocating the buffer. + + .. versionadded:: 3.3 + + .. versionchanged:: 3.7 + The return type is now ``const char *`` rather of ``char *``. + + +.. c:function:: const char* PyUnicode_AsUTF8(PyObject *unicode) + + As :c:func:`PyUnicode_AsUTF8AndSize`, but does not store the size. + + .. versionadded:: 3.3 + + .. versionchanged:: 3.7 + The return type is now ``const char *`` rather of ``char *``. + + +.. c:function:: PyObject* PyUnicode_EncodeUTF8(const Py_UNICODE *s, Py_ssize_t size, const char *errors) + + Encode the :c:type:`Py_UNICODE` buffer *s* of the given *size* using UTF-8 and + return a Python bytes object. Return ``NULL`` if an exception was raised by + the codec. + + .. deprecated-removed:: 3.3 4.0 + Part of the old-style :c:type:`Py_UNICODE` API; please migrate to using + :c:func:`PyUnicode_AsUTF8String`, :c:func:`PyUnicode_AsUTF8AndSize` or + :c:func:`PyUnicode_AsEncodedString`. + + +UTF-32 Codecs +""""""""""""" + +These are the UTF-32 codec APIs: + + +.. c:function:: PyObject* PyUnicode_DecodeUTF32(const char *s, Py_ssize_t size, \ + const char *errors, int *byteorder) + + Decode *size* bytes from a UTF-32 encoded buffer string and return the + corresponding Unicode object. *errors* (if non-``NULL``) defines the error + handling. It defaults to "strict". + + If *byteorder* is non-``NULL``, the decoder starts decoding using the given byte + order:: + + *byteorder == -1: little endian + *byteorder == 0: native order + *byteorder == 1: big endian + + If ``*byteorder`` is zero, and the first four bytes of the input data are a + byte order mark (BOM), the decoder switches to this byte order and the BOM is + not copied into the resulting Unicode string. If ``*byteorder`` is ``-1`` or + ``1``, any byte order mark is copied to the output. + + After completion, *\*byteorder* is set to the current byte order at the end + of input data. + + If *byteorder* is ``NULL``, the codec starts in native order mode. + + Return ``NULL`` if an exception was raised by the codec. + + +.. c:function:: PyObject* PyUnicode_DecodeUTF32Stateful(const char *s, Py_ssize_t size, \ + const char *errors, int *byteorder, Py_ssize_t *consumed) + + If *consumed* is ``NULL``, behave like :c:func:`PyUnicode_DecodeUTF32`. If + *consumed* is not ``NULL``, :c:func:`PyUnicode_DecodeUTF32Stateful` will not treat + trailing incomplete UTF-32 byte sequences (such as a number of bytes not divisible + by four) as an error. Those bytes will not be decoded and the number of bytes + that have been decoded will be stored in *consumed*. + + +.. c:function:: PyObject* PyUnicode_AsUTF32String(PyObject *unicode) + + Return a Python byte string using the UTF-32 encoding in native byte + order. The string always starts with a BOM mark. Error handling is "strict". + Return ``NULL`` if an exception was raised by the codec. + + +.. c:function:: PyObject* PyUnicode_EncodeUTF32(const Py_UNICODE *s, Py_ssize_t size, \ + const char *errors, int byteorder) + + Return a Python bytes object holding the UTF-32 encoded value of the Unicode + data in *s*. Output is written according to the following byte order:: + + byteorder == -1: little endian + byteorder == 0: native byte order (writes a BOM mark) + byteorder == 1: big endian + + If byteorder is ``0``, the output string will always start with the Unicode BOM + mark (U+FEFF). In the other two modes, no BOM mark is prepended. + + If ``Py_UNICODE_WIDE`` is not defined, surrogate pairs will be output + as a single code point. + + Return ``NULL`` if an exception was raised by the codec. + + .. deprecated-removed:: 3.3 4.0 + Part of the old-style :c:type:`Py_UNICODE` API; please migrate to using + :c:func:`PyUnicode_AsUTF32String` or :c:func:`PyUnicode_AsEncodedString`. + + +UTF-16 Codecs +""""""""""""" + +These are the UTF-16 codec APIs: + + +.. c:function:: PyObject* PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, \ + const char *errors, int *byteorder) + + Decode *size* bytes from a UTF-16 encoded buffer string and return the + corresponding Unicode object. *errors* (if non-``NULL``) defines the error + handling. It defaults to "strict". + + If *byteorder* is non-``NULL``, the decoder starts decoding using the given byte + order:: + + *byteorder == -1: little endian + *byteorder == 0: native order + *byteorder == 1: big endian + + If ``*byteorder`` is zero, and the first two bytes of the input data are a + byte order mark (BOM), the decoder switches to this byte order and the BOM is + not copied into the resulting Unicode string. If ``*byteorder`` is ``-1`` or + ``1``, any byte order mark is copied to the output (where it will result in + either a ``\ufeff`` or a ``\ufffe`` character). + + After completion, *\*byteorder* is set to the current byte order at the end + of input data. + + If *byteorder* is ``NULL``, the codec starts in native order mode. + + Return ``NULL`` if an exception was raised by the codec. + + +.. c:function:: PyObject* PyUnicode_DecodeUTF16Stateful(const char *s, Py_ssize_t size, \ + const char *errors, int *byteorder, Py_ssize_t *consumed) + + If *consumed* is ``NULL``, behave like :c:func:`PyUnicode_DecodeUTF16`. If + *consumed* is not ``NULL``, :c:func:`PyUnicode_DecodeUTF16Stateful` will not treat + trailing incomplete UTF-16 byte sequences (such as an odd number of bytes or a + split surrogate pair) as an error. Those bytes will not be decoded and the + number of bytes that have been decoded will be stored in *consumed*. + + +.. c:function:: PyObject* PyUnicode_AsUTF16String(PyObject *unicode) + + Return a Python byte string using the UTF-16 encoding in native byte + order. The string always starts with a BOM mark. Error handling is "strict". + Return ``NULL`` if an exception was raised by the codec. + + +.. c:function:: PyObject* PyUnicode_EncodeUTF16(const Py_UNICODE *s, Py_ssize_t size, \ + const char *errors, int byteorder) + + Return a Python bytes object holding the UTF-16 encoded value of the Unicode + data in *s*. Output is written according to the following byte order:: + + byteorder == -1: little endian + byteorder == 0: native byte order (writes a BOM mark) + byteorder == 1: big endian + + If byteorder is ``0``, the output string will always start with the Unicode BOM + mark (U+FEFF). In the other two modes, no BOM mark is prepended. + + If ``Py_UNICODE_WIDE`` is defined, a single :c:type:`Py_UNICODE` value may get + represented as a surrogate pair. If it is not defined, each :c:type:`Py_UNICODE` + values is interpreted as a UCS-2 character. + + Return ``NULL`` if an exception was raised by the codec. + + .. deprecated-removed:: 3.3 4.0 + Part of the old-style :c:type:`Py_UNICODE` API; please migrate to using + :c:func:`PyUnicode_AsUTF16String` or :c:func:`PyUnicode_AsEncodedString`. + + +UTF-7 Codecs +"""""""""""" + +These are the UTF-7 codec APIs: + + +.. c:function:: PyObject* PyUnicode_DecodeUTF7(const char *s, Py_ssize_t size, const char *errors) + + Create a Unicode object by decoding *size* bytes of the UTF-7 encoded string + *s*. Return ``NULL`` if an exception was raised by the codec. + + +.. c:function:: PyObject* PyUnicode_DecodeUTF7Stateful(const char *s, Py_ssize_t size, \ + const char *errors, Py_ssize_t *consumed) + + If *consumed* is ``NULL``, behave like :c:func:`PyUnicode_DecodeUTF7`. If + *consumed* is not ``NULL``, trailing incomplete UTF-7 base-64 sections will not + be treated as an error. Those bytes will not be decoded and the number of + bytes that have been decoded will be stored in *consumed*. + + +.. c:function:: PyObject* PyUnicode_EncodeUTF7(const Py_UNICODE *s, Py_ssize_t size, \ + int base64SetO, int base64WhiteSpace, const char *errors) + + Encode the :c:type:`Py_UNICODE` buffer of the given size using UTF-7 and + return a Python bytes object. Return ``NULL`` if an exception was raised by + the codec. + + If *base64SetO* is nonzero, "Set O" (punctuation that has no otherwise + special meaning) will be encoded in base-64. If *base64WhiteSpace* is + nonzero, whitespace will be encoded in base-64. Both are set to zero for the + Python "utf-7" codec. + + .. deprecated-removed:: 3.3 4.0 + Part of the old-style :c:type:`Py_UNICODE` API; please migrate to using + :c:func:`PyUnicode_AsEncodedString`. + + +Unicode-Escape Codecs +""""""""""""""""""""" + +These are the "Unicode Escape" codec APIs: + + +.. c:function:: PyObject* PyUnicode_DecodeUnicodeEscape(const char *s, \ + Py_ssize_t size, const char *errors) + + Create a Unicode object by decoding *size* bytes of the Unicode-Escape encoded + string *s*. Return ``NULL`` if an exception was raised by the codec. + + +.. c:function:: PyObject* PyUnicode_AsUnicodeEscapeString(PyObject *unicode) + + Encode a Unicode object using Unicode-Escape and return the result as a + bytes object. Error handling is "strict". Return ``NULL`` if an exception was + raised by the codec. + + +.. c:function:: PyObject* PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size) + + Encode the :c:type:`Py_UNICODE` buffer of the given *size* using Unicode-Escape and + return a bytes object. Return ``NULL`` if an exception was raised by the codec. + + .. deprecated-removed:: 3.3 4.0 + Part of the old-style :c:type:`Py_UNICODE` API; please migrate to using + :c:func:`PyUnicode_AsUnicodeEscapeString`. + + +Raw-Unicode-Escape Codecs +""""""""""""""""""""""""" + +These are the "Raw Unicode Escape" codec APIs: + + +.. c:function:: PyObject* PyUnicode_DecodeRawUnicodeEscape(const char *s, \ + Py_ssize_t size, const char *errors) + + Create a Unicode object by decoding *size* bytes of the Raw-Unicode-Escape + encoded string *s*. Return ``NULL`` if an exception was raised by the codec. + + +.. c:function:: PyObject* PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode) + + Encode a Unicode object using Raw-Unicode-Escape and return the result as + a bytes object. Error handling is "strict". Return ``NULL`` if an exception + was raised by the codec. + + +.. c:function:: PyObject* PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s, \ + Py_ssize_t size) + + Encode the :c:type:`Py_UNICODE` buffer of the given *size* using Raw-Unicode-Escape + and return a bytes object. Return ``NULL`` if an exception was raised by the codec. + + .. deprecated-removed:: 3.3 4.0 + Part of the old-style :c:type:`Py_UNICODE` API; please migrate to using + :c:func:`PyUnicode_AsRawUnicodeEscapeString` or + :c:func:`PyUnicode_AsEncodedString`. + + +Latin-1 Codecs +"""""""""""""" + +These are the Latin-1 codec APIs: Latin-1 corresponds to the first 256 Unicode +ordinals and only these are accepted by the codecs during encoding. + + +.. c:function:: PyObject* PyUnicode_DecodeLatin1(const char *s, Py_ssize_t size, const char *errors) + + Create a Unicode object by decoding *size* bytes of the Latin-1 encoded string + *s*. Return ``NULL`` if an exception was raised by the codec. + + +.. c:function:: PyObject* PyUnicode_AsLatin1String(PyObject *unicode) + + Encode a Unicode object using Latin-1 and return the result as Python bytes + object. Error handling is "strict". Return ``NULL`` if an exception was + raised by the codec. + + +.. c:function:: PyObject* PyUnicode_EncodeLatin1(const Py_UNICODE *s, Py_ssize_t size, const char *errors) + + Encode the :c:type:`Py_UNICODE` buffer of the given *size* using Latin-1 and + return a Python bytes object. Return ``NULL`` if an exception was raised by + the codec. + + .. deprecated-removed:: 3.3 4.0 + Part of the old-style :c:type:`Py_UNICODE` API; please migrate to using + :c:func:`PyUnicode_AsLatin1String` or + :c:func:`PyUnicode_AsEncodedString`. + + +ASCII Codecs +"""""""""""" + +These are the ASCII codec APIs. Only 7-bit ASCII data is accepted. All other +codes generate errors. + + +.. c:function:: PyObject* PyUnicode_DecodeASCII(const char *s, Py_ssize_t size, const char *errors) + + Create a Unicode object by decoding *size* bytes of the ASCII encoded string + *s*. Return ``NULL`` if an exception was raised by the codec. + + +.. c:function:: PyObject* PyUnicode_AsASCIIString(PyObject *unicode) + + Encode a Unicode object using ASCII and return the result as Python bytes + object. Error handling is "strict". Return ``NULL`` if an exception was + raised by the codec. + + +.. c:function:: PyObject* PyUnicode_EncodeASCII(const Py_UNICODE *s, Py_ssize_t size, const char *errors) + + Encode the :c:type:`Py_UNICODE` buffer of the given *size* using ASCII and + return a Python bytes object. Return ``NULL`` if an exception was raised by + the codec. + + .. deprecated-removed:: 3.3 4.0 + Part of the old-style :c:type:`Py_UNICODE` API; please migrate to using + :c:func:`PyUnicode_AsASCIIString` or + :c:func:`PyUnicode_AsEncodedString`. + + +Character Map Codecs +"""""""""""""""""""" + +This codec is special in that it can be used to implement many different codecs +(and this is in fact what was done to obtain most of the standard codecs +included in the :mod:`encodings` package). The codec uses mapping to encode and +decode characters. The mapping objects provided must support the +:meth:`__getitem__` mapping interface; dictionaries and sequences work well. + +These are the mapping codec APIs: + +.. c:function:: PyObject* PyUnicode_DecodeCharmap(const char *data, Py_ssize_t size, \ + PyObject *mapping, const char *errors) + + Create a Unicode object by decoding *size* bytes of the encoded string *s* + using the given *mapping* object. Return ``NULL`` if an exception was raised + by the codec. + + If *mapping* is ``NULL``, Latin-1 decoding will be applied. Else + *mapping* must map bytes ordinals (integers in the range from 0 to 255) + to Unicode strings, integers (which are then interpreted as Unicode + ordinals) or ``None``. Unmapped data bytes -- ones which cause a + :exc:`LookupError`, as well as ones which get mapped to ``None``, + ``0xFFFE`` or ``'\ufffe'``, are treated as undefined mappings and cause + an error. + + +.. c:function:: PyObject* PyUnicode_AsCharmapString(PyObject *unicode, PyObject *mapping) + + Encode a Unicode object using the given *mapping* object and return the + result as a bytes object. Error handling is "strict". Return ``NULL`` if an + exception was raised by the codec. + + The *mapping* object must map Unicode ordinal integers to bytes objects, + integers in the range from 0 to 255 or ``None``. Unmapped character + ordinals (ones which cause a :exc:`LookupError`) as well as mapped to + ``None`` are treated as "undefined mapping" and cause an error. + + +.. c:function:: PyObject* PyUnicode_EncodeCharmap(const Py_UNICODE *s, Py_ssize_t size, \ + PyObject *mapping, const char *errors) + + Encode the :c:type:`Py_UNICODE` buffer of the given *size* using the given + *mapping* object and return the result as a bytes object. Return ``NULL`` if + an exception was raised by the codec. + + .. deprecated-removed:: 3.3 4.0 + Part of the old-style :c:type:`Py_UNICODE` API; please migrate to using + :c:func:`PyUnicode_AsCharmapString` or + :c:func:`PyUnicode_AsEncodedString`. + + +The following codec API is special in that maps Unicode to Unicode. + +.. c:function:: PyObject* PyUnicode_Translate(PyObject *unicode, \ + PyObject *mapping, const char *errors) + + Translate a Unicode object using the given *mapping* object and return the + resulting Unicode object. Return ``NULL`` if an exception was raised by the + codec. + + The *mapping* object must map Unicode ordinal integers to Unicode strings, + integers (which are then interpreted as Unicode ordinals) or ``None`` + (causing deletion of the character). Unmapped character ordinals (ones + which cause a :exc:`LookupError`) are left untouched and are copied as-is. + + +.. c:function:: PyObject* PyUnicode_TranslateCharmap(const Py_UNICODE *s, Py_ssize_t size, \ + PyObject *mapping, const char *errors) + + Translate a :c:type:`Py_UNICODE` buffer of the given *size* by applying a + character *mapping* table to it and return the resulting Unicode object. + Return ``NULL`` when an exception was raised by the codec. + + .. deprecated-removed:: 3.3 4.0 + Part of the old-style :c:type:`Py_UNICODE` API; please migrate to using + :c:func:`PyUnicode_Translate`. or :ref:`generic codec based API + ` + + +MBCS codecs for Windows +""""""""""""""""""""""" + +These are the MBCS codec APIs. They are currently only available on Windows and +use the Win32 MBCS converters to implement the conversions. Note that MBCS (or +DBCS) is a class of encodings, not just one. The target encoding is defined by +the user settings on the machine running the codec. + +.. c:function:: PyObject* PyUnicode_DecodeMBCS(const char *s, Py_ssize_t size, const char *errors) + + Create a Unicode object by decoding *size* bytes of the MBCS encoded string *s*. + Return ``NULL`` if an exception was raised by the codec. + + +.. c:function:: PyObject* PyUnicode_DecodeMBCSStateful(const char *s, Py_ssize_t size, \ + const char *errors, Py_ssize_t *consumed) + + If *consumed* is ``NULL``, behave like :c:func:`PyUnicode_DecodeMBCS`. If + *consumed* is not ``NULL``, :c:func:`PyUnicode_DecodeMBCSStateful` will not decode + trailing lead byte and the number of bytes that have been decoded will be stored + in *consumed*. + + +.. c:function:: PyObject* PyUnicode_AsMBCSString(PyObject *unicode) + + Encode a Unicode object using MBCS and return the result as Python bytes + object. Error handling is "strict". Return ``NULL`` if an exception was + raised by the codec. + + +.. c:function:: PyObject* PyUnicode_EncodeCodePage(int code_page, PyObject *unicode, const char *errors) + + Encode the Unicode object using the specified code page and return a Python + bytes object. Return ``NULL`` if an exception was raised by the codec. Use + :c:data:`CP_ACP` code page to get the MBCS encoder. + + .. versionadded:: 3.3 + + +.. c:function:: PyObject* PyUnicode_EncodeMBCS(const Py_UNICODE *s, Py_ssize_t size, const char *errors) + + Encode the :c:type:`Py_UNICODE` buffer of the given *size* using MBCS and return + a Python bytes object. Return ``NULL`` if an exception was raised by the + codec. + + .. deprecated-removed:: 3.3 4.0 + Part of the old-style :c:type:`Py_UNICODE` API; please migrate to using + :c:func:`PyUnicode_AsMBCSString`, :c:func:`PyUnicode_EncodeCodePage` or + :c:func:`PyUnicode_AsEncodedString`. + + +Methods & Slots +""""""""""""""" + + +.. _unicodemethodsandslots: + +Methods and Slot Functions +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The following APIs are capable of handling Unicode objects and strings on input +(we refer to them as strings in the descriptions) and return Unicode objects or +integers as appropriate. + +They all return ``NULL`` or ``-1`` if an exception occurs. + + +.. c:function:: PyObject* PyUnicode_Concat(PyObject *left, PyObject *right) + + Concat two strings giving a new Unicode string. + + +.. c:function:: PyObject* PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit) + + Split a string giving a list of Unicode strings. If *sep* is ``NULL``, splitting + will be done at all whitespace substrings. Otherwise, splits occur at the given + separator. At most *maxsplit* splits will be done. If negative, no limit is + set. Separators are not included in the resulting list. + + +.. c:function:: PyObject* PyUnicode_Splitlines(PyObject *s, int keepend) + + Split a Unicode string at line breaks, returning a list of Unicode strings. + CRLF is considered to be one line break. If *keepend* is ``0``, the Line break + characters are not included in the resulting strings. + + +.. c:function:: PyObject* PyUnicode_Translate(PyObject *str, PyObject *table, \ + const char *errors) + + Translate a string by applying a character mapping table to it and return the + resulting Unicode object. + + The mapping table must map Unicode ordinal integers to Unicode ordinal integers + or ``None`` (causing deletion of the character). + + Mapping tables need only provide the :meth:`__getitem__` interface; dictionaries + and sequences work well. Unmapped character ordinals (ones which cause a + :exc:`LookupError`) are left untouched and are copied as-is. + + *errors* has the usual meaning for codecs. It may be ``NULL`` which indicates to + use the default error handling. + + +.. c:function:: PyObject* PyUnicode_Join(PyObject *separator, PyObject *seq) + + Join a sequence of strings using the given *separator* and return the resulting + Unicode string. + + +.. c:function:: Py_ssize_t PyUnicode_Tailmatch(PyObject *str, PyObject *substr, \ + Py_ssize_t start, Py_ssize_t end, int direction) + + Return ``1`` if *substr* matches ``str[start:end]`` at the given tail end + (*direction* == ``-1`` means to do a prefix match, *direction* == ``1`` a suffix match), + ``0`` otherwise. Return ``-1`` if an error occurred. + + +.. c:function:: Py_ssize_t PyUnicode_Find(PyObject *str, PyObject *substr, \ + Py_ssize_t start, Py_ssize_t end, int direction) + + Return the first position of *substr* in ``str[start:end]`` using the given + *direction* (*direction* == ``1`` means to do a forward search, *direction* == ``-1`` a + backward search). The return value is the index of the first match; a value of + ``-1`` indicates that no match was found, and ``-2`` indicates that an error + occurred and an exception has been set. + + +.. c:function:: Py_ssize_t PyUnicode_FindChar(PyObject *str, Py_UCS4 ch, \ + Py_ssize_t start, Py_ssize_t end, int direction) + + Return the first position of the character *ch* in ``str[start:end]`` using + the given *direction* (*direction* == ``1`` means to do a forward search, + *direction* == ``-1`` a backward search). The return value is the index of the + first match; a value of ``-1`` indicates that no match was found, and ``-2`` + indicates that an error occurred and an exception has been set. + + .. versionadded:: 3.3 + + .. versionchanged:: 3.7 + *start* and *end* are now adjusted to behave like ``str[start:end]``. + + +.. c:function:: Py_ssize_t PyUnicode_Count(PyObject *str, PyObject *substr, \ + Py_ssize_t start, Py_ssize_t end) + + Return the number of non-overlapping occurrences of *substr* in + ``str[start:end]``. Return ``-1`` if an error occurred. + + +.. c:function:: PyObject* PyUnicode_Replace(PyObject *str, PyObject *substr, \ + PyObject *replstr, Py_ssize_t maxcount) + + Replace at most *maxcount* occurrences of *substr* in *str* with *replstr* and + return the resulting Unicode object. *maxcount* == ``-1`` means replace all + occurrences. + + +.. c:function:: int PyUnicode_Compare(PyObject *left, PyObject *right) + + Compare two strings and return ``-1``, ``0``, ``1`` for less than, equal, and greater than, + respectively. + + This function returns ``-1`` upon failure, so one should call + :c:func:`PyErr_Occurred` to check for errors. + + +.. c:function:: int PyUnicode_CompareWithASCIIString(PyObject *uni, const char *string) + + Compare a Unicode object, *uni*, with *string* and return ``-1``, ``0``, ``1`` for less + than, equal, and greater than, respectively. It is best to pass only + ASCII-encoded strings, but the function interprets the input string as + ISO-8859-1 if it contains non-ASCII characters. + + This function does not raise exceptions. + + +.. c:function:: PyObject* PyUnicode_RichCompare(PyObject *left, PyObject *right, int op) + + Rich compare two Unicode strings and return one of the following: + + * ``NULL`` in case an exception was raised + * :const:`Py_True` or :const:`Py_False` for successful comparisons + * :const:`Py_NotImplemented` in case the type combination is unknown + + Possible values for *op* are :const:`Py_GT`, :const:`Py_GE`, :const:`Py_EQ`, + :const:`Py_NE`, :const:`Py_LT`, and :const:`Py_LE`. + + +.. c:function:: PyObject* PyUnicode_Format(PyObject *format, PyObject *args) + + Return a new string object from *format* and *args*; this is analogous to + ``format % args``. + + +.. c:function:: int PyUnicode_Contains(PyObject *container, PyObject *element) + + Check whether *element* is contained in *container* and return true or false + accordingly. + + *element* has to coerce to a one element Unicode string. ``-1`` is returned + if there was an error. + + +.. c:function:: void PyUnicode_InternInPlace(PyObject **string) + + Intern the argument *\*string* in place. The argument must be the address of a + pointer variable pointing to a Python Unicode string object. If there is an + existing interned string that is the same as *\*string*, it sets *\*string* to + it (decrementing the reference count of the old string object and incrementing + the reference count of the interned string object), otherwise it leaves + *\*string* alone and interns it (incrementing its reference count). + (Clarification: even though there is a lot of talk about reference counts, think + of this function as reference-count-neutral; you own the object after the call + if and only if you owned it before the call.) + + +.. c:function:: PyObject* PyUnicode_InternFromString(const char *v) + + A combination of :c:func:`PyUnicode_FromString` and + :c:func:`PyUnicode_InternInPlace`, returning either a new Unicode string + object that has been interned, or a new ("owned") reference to an earlier + interned string object with the same value. diff --git a/cpython_2/environment/repo/Doc/c-api/utilities.rst b/cpython_2/environment/repo/Doc/c-api/utilities.rst new file mode 100644 index 0000000000000000000000000000000000000000..a805b564763c407e0ae83f6b363645001fcac694 --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/utilities.rst @@ -0,0 +1,21 @@ +.. highlight:: c + +.. _utilities: + +********* +Utilities +********* + +The functions in this chapter perform various utility tasks, ranging from +helping C code be more portable across platforms, using Python modules from C, +and parsing function arguments and constructing Python values from C values. + +.. toctree:: + + sys.rst + import.rst + marshal.rst + arg.rst + conversion.rst + reflection.rst + codec.rst diff --git a/cpython_2/environment/repo/Doc/c-api/veryhigh.rst b/cpython_2/environment/repo/Doc/c-api/veryhigh.rst new file mode 100644 index 0000000000000000000000000000000000000000..d6aecc394c9e70a8084750df748ed06a9065f22c --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/veryhigh.rst @@ -0,0 +1,412 @@ +.. highlight:: c + + +.. _veryhigh: + +************************* +The Very High Level Layer +************************* + +The functions in this chapter will let you execute Python source code given in a +file or a buffer, but they will not let you interact in a more detailed way with +the interpreter. + +Several of these functions accept a start symbol from the grammar as a +parameter. The available start symbols are :const:`Py_eval_input`, +:const:`Py_file_input`, and :const:`Py_single_input`. These are described +following the functions which accept them as parameters. + +Note also that several of these functions take :c:type:`FILE\*` parameters. One +particular issue which needs to be handled carefully is that the :c:type:`FILE` +structure for different C libraries can be different and incompatible. Under +Windows (at least), it is possible for dynamically linked extensions to actually +use different libraries, so care should be taken that :c:type:`FILE\*` parameters +are only passed to these functions if it is certain that they were created by +the same library that the Python runtime is using. + + +.. c:function:: int Py_Main(int argc, wchar_t **argv) + + The main program for the standard interpreter. This is made available for + programs which embed Python. The *argc* and *argv* parameters should be + prepared exactly as those which are passed to a C program's :c:func:`main` + function (converted to wchar_t according to the user's locale). It is + important to note that the argument list may be modified (but the contents of + the strings pointed to by the argument list are not). The return value will + be ``0`` if the interpreter exits normally (i.e., without an exception), + ``1`` if the interpreter exits due to an exception, or ``2`` if the parameter + list does not represent a valid Python command line. + + Note that if an otherwise unhandled :exc:`SystemExit` is raised, this + function will not return ``1``, but exit the process, as long as + ``Py_InspectFlag`` is not set. + + +.. c:function:: int Py_BytesMain(int argc, char **argv) + + Similar to :c:func:`Py_Main` but *argv* is an array of bytes strings. + + .. versionadded:: 3.8 + + +.. c:function:: int PyRun_AnyFile(FILE *fp, const char *filename) + + This is a simplified interface to :c:func:`PyRun_AnyFileExFlags` below, leaving + *closeit* set to ``0`` and *flags* set to ``NULL``. + + +.. c:function:: int PyRun_AnyFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags) + + This is a simplified interface to :c:func:`PyRun_AnyFileExFlags` below, leaving + the *closeit* argument set to ``0``. + + +.. c:function:: int PyRun_AnyFileEx(FILE *fp, const char *filename, int closeit) + + This is a simplified interface to :c:func:`PyRun_AnyFileExFlags` below, leaving + the *flags* argument set to ``NULL``. + + +.. c:function:: int PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags) + + If *fp* refers to a file associated with an interactive device (console or + terminal input or Unix pseudo-terminal), return the value of + :c:func:`PyRun_InteractiveLoop`, otherwise return the result of + :c:func:`PyRun_SimpleFile`. *filename* is decoded from the filesystem + encoding (:func:`sys.getfilesystemencoding`). If *filename* is ``NULL``, this + function uses ``"???"`` as the filename. + + +.. c:function:: int PyRun_SimpleString(const char *command) + + This is a simplified interface to :c:func:`PyRun_SimpleStringFlags` below, + leaving the :c:type:`PyCompilerFlags`\* argument set to ``NULL``. + + +.. c:function:: int PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags) + + Executes the Python source code from *command* in the :mod:`__main__` module + according to the *flags* argument. If :mod:`__main__` does not already exist, it + is created. Returns ``0`` on success or ``-1`` if an exception was raised. If + there was an error, there is no way to get the exception information. For the + meaning of *flags*, see below. + + Note that if an otherwise unhandled :exc:`SystemExit` is raised, this + function will not return ``-1``, but exit the process, as long as + ``Py_InspectFlag`` is not set. + + +.. c:function:: int PyRun_SimpleFile(FILE *fp, const char *filename) + + This is a simplified interface to :c:func:`PyRun_SimpleFileExFlags` below, + leaving *closeit* set to ``0`` and *flags* set to ``NULL``. + + +.. c:function:: int PyRun_SimpleFileEx(FILE *fp, const char *filename, int closeit) + + This is a simplified interface to :c:func:`PyRun_SimpleFileExFlags` below, + leaving *flags* set to ``NULL``. + + +.. c:function:: int PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags) + + Similar to :c:func:`PyRun_SimpleStringFlags`, but the Python source code is read + from *fp* instead of an in-memory string. *filename* should be the name of + the file, it is decoded from the filesystem encoding + (:func:`sys.getfilesystemencoding`). If *closeit* is true, the file is + closed before PyRun_SimpleFileExFlags returns. + + .. note:: + On Windows, *fp* should be opened as binary mode (e.g. ``fopen(filename, "rb")``). + Otherwise, Python may not handle script file with LF line ending correctly. + + +.. c:function:: int PyRun_InteractiveOne(FILE *fp, const char *filename) + + This is a simplified interface to :c:func:`PyRun_InteractiveOneFlags` below, + leaving *flags* set to ``NULL``. + + +.. c:function:: int PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags) + + Read and execute a single statement from a file associated with an + interactive device according to the *flags* argument. The user will be + prompted using ``sys.ps1`` and ``sys.ps2``. *filename* is decoded from the + filesystem encoding (:func:`sys.getfilesystemencoding`). + + Returns ``0`` when the input was + executed successfully, ``-1`` if there was an exception, or an error code + from the :file:`errcode.h` include file distributed as part of Python if + there was a parse error. (Note that :file:`errcode.h` is not included by + :file:`Python.h`, so must be included specifically if needed.) + + +.. c:function:: int PyRun_InteractiveLoop(FILE *fp, const char *filename) + + This is a simplified interface to :c:func:`PyRun_InteractiveLoopFlags` below, + leaving *flags* set to ``NULL``. + + +.. c:function:: int PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags) + + Read and execute statements from a file associated with an interactive device + until EOF is reached. The user will be prompted using ``sys.ps1`` and + ``sys.ps2``. *filename* is decoded from the filesystem encoding + (:func:`sys.getfilesystemencoding`). Returns ``0`` at EOF or a negative + number upon failure. + + +.. c:var:: int (*PyOS_InputHook)(void) + + Can be set to point to a function with the prototype + ``int func(void)``. The function will be called when Python's + interpreter prompt is about to become idle and wait for user input + from the terminal. The return value is ignored. Overriding this + hook can be used to integrate the interpreter's prompt with other + event loops, as done in the :file:`Modules/_tkinter.c` in the + Python source code. + + +.. c:var:: char* (*PyOS_ReadlineFunctionPointer)(FILE *, FILE *, const char *) + + Can be set to point to a function with the prototype + ``char *func(FILE *stdin, FILE *stdout, char *prompt)``, + overriding the default function used to read a single line of input + at the interpreter's prompt. The function is expected to output + the string *prompt* if it's not ``NULL``, and then read a line of + input from the provided standard input file, returning the + resulting string. For example, The :mod:`readline` module sets + this hook to provide line-editing and tab-completion features. + + The result must be a string allocated by :c:func:`PyMem_RawMalloc` or + :c:func:`PyMem_RawRealloc`, or ``NULL`` if an error occurred. + + .. versionchanged:: 3.4 + The result must be allocated by :c:func:`PyMem_RawMalloc` or + :c:func:`PyMem_RawRealloc`, instead of being allocated by + :c:func:`PyMem_Malloc` or :c:func:`PyMem_Realloc`. + + +.. c:function:: struct _node* PyParser_SimpleParseString(const char *str, int start) + + This is a simplified interface to + :c:func:`PyParser_SimpleParseStringFlagsFilename` below, leaving *filename* set + to ``NULL`` and *flags* set to ``0``. + + +.. c:function:: struct _node* PyParser_SimpleParseStringFlags( const char *str, int start, int flags) + + This is a simplified interface to + :c:func:`PyParser_SimpleParseStringFlagsFilename` below, leaving *filename* set + to ``NULL``. + + +.. c:function:: struct _node* PyParser_SimpleParseStringFlagsFilename( const char *str, const char *filename, int start, int flags) + + Parse Python source code from *str* using the start token *start* according to + the *flags* argument. The result can be used to create a code object which can + be evaluated efficiently. This is useful if a code fragment must be evaluated + many times. *filename* is decoded from the filesystem encoding + (:func:`sys.getfilesystemencoding`). + + +.. c:function:: struct _node* PyParser_SimpleParseFile(FILE *fp, const char *filename, int start) + + This is a simplified interface to :c:func:`PyParser_SimpleParseFileFlags` below, + leaving *flags* set to ``0``. + + +.. c:function:: struct _node* PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags) + + Similar to :c:func:`PyParser_SimpleParseStringFlagsFilename`, but the Python + source code is read from *fp* instead of an in-memory string. + + +.. c:function:: PyObject* PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals) + + This is a simplified interface to :c:func:`PyRun_StringFlags` below, leaving + *flags* set to ``NULL``. + + +.. c:function:: PyObject* PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals, PyCompilerFlags *flags) + + Execute Python source code from *str* in the context specified by the + objects *globals* and *locals* with the compiler flags specified by + *flags*. *globals* must be a dictionary; *locals* can be any object + that implements the mapping protocol. The parameter *start* specifies + the start token that should be used to parse the source code. + + Returns the result of executing the code as a Python object, or ``NULL`` if an + exception was raised. + + +.. c:function:: PyObject* PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals) + + This is a simplified interface to :c:func:`PyRun_FileExFlags` below, leaving + *closeit* set to ``0`` and *flags* set to ``NULL``. + + +.. c:function:: PyObject* PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, int closeit) + + This is a simplified interface to :c:func:`PyRun_FileExFlags` below, leaving + *flags* set to ``NULL``. + + +.. c:function:: PyObject* PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, PyCompilerFlags *flags) + + This is a simplified interface to :c:func:`PyRun_FileExFlags` below, leaving + *closeit* set to ``0``. + + +.. c:function:: PyObject* PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, int closeit, PyCompilerFlags *flags) + + Similar to :c:func:`PyRun_StringFlags`, but the Python source code is read from + *fp* instead of an in-memory string. *filename* should be the name of the file, + it is decoded from the filesystem encoding (:func:`sys.getfilesystemencoding`). + If *closeit* is true, the file is closed before :c:func:`PyRun_FileExFlags` + returns. + + +.. c:function:: PyObject* Py_CompileString(const char *str, const char *filename, int start) + + This is a simplified interface to :c:func:`Py_CompileStringFlags` below, leaving + *flags* set to ``NULL``. + + +.. c:function:: PyObject* Py_CompileStringFlags(const char *str, const char *filename, int start, PyCompilerFlags *flags) + + This is a simplified interface to :c:func:`Py_CompileStringExFlags` below, with + *optimize* set to ``-1``. + + +.. c:function:: PyObject* Py_CompileStringObject(const char *str, PyObject *filename, int start, PyCompilerFlags *flags, int optimize) + + Parse and compile the Python source code in *str*, returning the resulting code + object. The start token is given by *start*; this can be used to constrain the + code which can be compiled and should be :const:`Py_eval_input`, + :const:`Py_file_input`, or :const:`Py_single_input`. The filename specified by + *filename* is used to construct the code object and may appear in tracebacks or + :exc:`SyntaxError` exception messages. This returns ``NULL`` if the code + cannot be parsed or compiled. + + The integer *optimize* specifies the optimization level of the compiler; a + value of ``-1`` selects the optimization level of the interpreter as given by + :option:`-O` options. Explicit levels are ``0`` (no optimization; + ``__debug__`` is true), ``1`` (asserts are removed, ``__debug__`` is false) + or ``2`` (docstrings are removed too). + + .. versionadded:: 3.4 + + +.. c:function:: PyObject* Py_CompileStringExFlags(const char *str, const char *filename, int start, PyCompilerFlags *flags, int optimize) + + Like :c:func:`Py_CompileStringObject`, but *filename* is a byte string + decoded from the filesystem encoding (:func:`os.fsdecode`). + + .. versionadded:: 3.2 + +.. c:function:: PyObject* PyEval_EvalCode(PyObject *co, PyObject *globals, PyObject *locals) + + This is a simplified interface to :c:func:`PyEval_EvalCodeEx`, with just + the code object, and global and local variables. The other arguments are + set to ``NULL``. + + +.. c:function:: 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) + + Evaluate a precompiled code object, given a particular environment for its + evaluation. This environment consists of a dictionary of global variables, + a mapping object of local variables, arrays of arguments, keywords and + defaults, a dictionary of default values for :ref:`keyword-only + ` arguments and a closure tuple of cells. + + +.. c:type:: PyFrameObject + + The C structure of the objects used to describe frame objects. The + fields of this type are subject to change at any time. + + +.. c:function:: PyObject* PyEval_EvalFrame(PyFrameObject *f) + + Evaluate an execution frame. This is a simplified interface to + :c:func:`PyEval_EvalFrameEx`, for backward compatibility. + + +.. c:function:: PyObject* PyEval_EvalFrameEx(PyFrameObject *f, int throwflag) + + This is the main, unvarnished function of Python interpretation. The code + object associated with the execution frame *f* is executed, interpreting + bytecode and executing calls as needed. The additional *throwflag* + parameter can mostly be ignored - if true, then it causes an exception + to immediately be thrown; this is used for the :meth:`~generator.throw` + methods of generator objects. + + .. versionchanged:: 3.4 + This function now includes a debug assertion to help ensure that it + does not silently discard an active exception. + + +.. c:function:: int PyEval_MergeCompilerFlags(PyCompilerFlags *cf) + + This function changes the flags of the current evaluation frame, and returns + true on success, false on failure. + + +.. c:var:: int Py_eval_input + + .. index:: single: Py_CompileString() + + 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() + + 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 + the symbol to use when compiling arbitrarily long Python source code. + + +.. c:var:: int Py_single_input + + .. index:: single: Py_CompileString() + + 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 + interpreter loop. + + +.. c:type:: struct PyCompilerFlags + + This is the structure used to hold compiler flags. In cases where code is only + being compiled, it is passed as ``int flags``, and in cases where code is being + executed, it is passed as ``PyCompilerFlags *flags``. In this case, ``from + __future__ import`` can modify *flags*. + + Whenever ``PyCompilerFlags *flags`` is ``NULL``, :attr:`cf_flags` is treated as + equal to ``0``, and any modification due to ``from __future__ import`` is + discarded. + + .. c:member:: int cf_flags + + Compiler flags. + + .. c:member:: int cf_feature_version + + *cf_feature_version* is the minor Python version. It should be + initialized to ``PY_MINOR_VERSION``. + + The field is ignored by default, it is used if and only if + ``PyCF_ONLY_AST`` flag is set in *cf_flags*. + + .. versionchanged:: 3.8 + Added *cf_feature_version* field. + + +.. c:var:: int CO_FUTURE_DIVISION + + This bit can be set in *flags* to cause division operator ``/`` to be + interpreted as "true division" according to :pep:`238`. diff --git a/cpython_2/environment/repo/Doc/c-api/weakref.rst b/cpython_2/environment/repo/Doc/c-api/weakref.rst new file mode 100644 index 0000000000000000000000000000000000000000..e3a9bda54d671a52634b158e7197a00c34d6d178 --- /dev/null +++ b/cpython_2/environment/repo/Doc/c-api/weakref.rst @@ -0,0 +1,69 @@ +.. highlight:: c + +.. _weakrefobjects: + +Weak Reference Objects +---------------------- + +Python supports *weak references* as first-class objects. There are two +specific object types which directly implement weak references. The first is a +simple reference object, and the second acts as a proxy for the original object +as much as it can. + + +.. c:function:: int PyWeakref_Check(ob) + + Return true if *ob* is either a reference or proxy object. + + +.. c:function:: int PyWeakref_CheckRef(ob) + + Return true if *ob* is a reference object. + + +.. c:function:: int PyWeakref_CheckProxy(ob) + + Return true if *ob* is a proxy object. + + +.. c:function:: PyObject* PyWeakref_NewRef(PyObject *ob, PyObject *callback) + + Return a weak reference object for the object *ob*. This will always return + a new reference, but is not guaranteed to create a new object; an existing + reference object may be returned. The second parameter, *callback*, can be a + callable object that receives notification when *ob* is garbage collected; it + should accept a single parameter, which will be the weak reference object + itself. *callback* may also be ``None`` or ``NULL``. If *ob* is not a + weakly-referencable object, or if *callback* is not callable, ``None``, or + ``NULL``, this will return ``NULL`` and raise :exc:`TypeError`. + + +.. c:function:: PyObject* PyWeakref_NewProxy(PyObject *ob, PyObject *callback) + + Return a weak reference proxy object for the object *ob*. This will always + return a new reference, but is not guaranteed to create a new object; an + existing proxy object may be returned. The second parameter, *callback*, can + be a callable object that receives notification when *ob* is garbage + collected; it should accept a single parameter, which will be the weak + reference object itself. *callback* may also be ``None`` or ``NULL``. If *ob* + is not a weakly-referencable object, or if *callback* is not callable, + ``None``, or ``NULL``, this will return ``NULL`` and raise :exc:`TypeError`. + + +.. c:function:: PyObject* PyWeakref_GetObject(PyObject *ref) + + Return the referenced object from a weak reference, *ref*. If the referent is + no longer live, returns :const:`Py_None`. + + .. note:: + + This function returns a **borrowed reference** to the referenced object. + This means that you should always call :c:func:`Py_INCREF` on the object + except if you know that it cannot be destroyed while you are still + using it. + + +.. c:function:: PyObject* PyWeakref_GET_OBJECT(PyObject *ref) + + Similar to :c:func:`PyWeakref_GetObject`, but implemented as a macro that does no + error checking. diff --git a/cpython_2/environment/repo/Doc/conf.py b/cpython_2/environment/repo/Doc/conf.py new file mode 100644 index 0000000000000000000000000000000000000000..12d74ea24ce4aca139b5f2a1120b365d488e7fa0 --- /dev/null +++ b/cpython_2/environment/repo/Doc/conf.py @@ -0,0 +1,230 @@ +# +# Python documentation build configuration file +# +# This file is execfile()d with the current directory set to its containing dir. +# +# The contents of this file are pickled, so don't put values in the namespace +# that aren't pickleable (module imports are okay, they're removed automatically). + +import sys, os, time +sys.path.append(os.path.abspath('tools/extensions')) +sys.path.append(os.path.abspath('includes')) + +# General configuration +# --------------------- + +extensions = ['sphinx.ext.coverage', 'sphinx.ext.doctest', + 'pyspecific', 'c_annotations', 'escape4chm', + 'asdl_highlight'] + + +doctest_global_setup = ''' +try: + import _tkinter +except ImportError: + _tkinter = None +''' + +manpages_url = 'https://manpages.debian.org/{path}' + +# General substitutions. +project = 'Python' +copyright = '2001-%s, Python Software Foundation' % time.strftime('%Y') + +# We look for the Include/patchlevel.h file in the current Python source tree +# and replace the values accordingly. +import patchlevel +version, release = patchlevel.get_version_info() + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +today = '' +# Else, today_fmt is used as the format for a strftime call. +today_fmt = '%B %d, %Y' + +# By default, highlight as Python 3. +highlight_language = 'python3' + +# Minimum version of sphinx required +needs_sphinx = '1.8' + +# Ignore any .rst files in the venv/ directory. +exclude_patterns = ['venv/*', 'README.rst'] +venvdir = os.getenv('VENVDIR') +if venvdir is not None: + exclude_patterns.append(venvdir + '/*') + +# Disable Docutils smartquotes for several translations +smartquotes_excludes = { + 'languages': ['ja', 'fr', 'zh_TW', 'zh_CN'], 'builders': ['man', 'text'], +} + +# Avoid a warning with Sphinx >= 2.0 +master_doc = 'contents' + +# Options for HTML output +# ----------------------- + +# Use our custom theme. +html_theme = 'python_docs_theme' +html_theme_path = ['tools'] +html_theme_options = { + 'collapsiblesidebar': True, + 'issues_url': 'https://docs.python.org/3/bugs.html', + 'root_include_title': False # We use the version switcher instead. +} + +# Short title used e.g. for HTML tags. +html_short_title = '%s Documentation' % release + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +html_last_updated_fmt = '%b %d, %Y' + +# Path to find HTML templates. +templates_path = ['tools/templates'] + +# Custom sidebar templates, filenames relative to this file. +html_sidebars = { + # Defaults taken from http://www.sphinx-doc.org/en/stable/config.html#confval-html_sidebars + # Removes the quick search block + '**': ['localtoc.html', 'relations.html', 'customsourcelink.html'], + 'index': ['indexsidebar.html'], +} + +# Additional templates that should be rendered to pages. +html_additional_pages = { + 'download': 'download.html', + 'index': 'indexcontent.html', +} + +# Output an OpenSearch description file. +html_use_opensearch = 'https://docs.python.org/' + version + +# Additional static files. +html_static_path = ['tools/static'] + +# Output file base name for HTML help builder. +htmlhelp_basename = 'python' + release.replace('.', '') + +# Split the index +html_split_index = True + + +# Options for LaTeX output +# ------------------------ + +latex_engine = 'xelatex' + +# Get LaTeX to handle Unicode correctly +latex_elements = { +} + +# Additional stuff for the LaTeX preamble. +latex_elements['preamble'] = r''' +\authoraddress{ + \sphinxstrong{Python Software Foundation}\\ + Email: \sphinxemail{docs@python.org} +} +\let\Verbatim=\OriginalVerbatim +\let\endVerbatim=\endOriginalVerbatim +\setcounter{tocdepth}{2} +''' + +# The paper size ('letter' or 'a4'). +latex_elements['papersize'] = 'a4' + +# The font size ('10pt', '11pt' or '12pt'). +latex_elements['pointsize'] = '10pt' + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, document class [howto/manual]). +_stdauthor = r'Guido van Rossum\\and the Python development team' +latex_documents = [ + ('c-api/index', 'c-api.tex', + 'The Python/C API', _stdauthor, 'manual'), + ('distributing/index', 'distributing.tex', + 'Distributing Python Modules', _stdauthor, 'manual'), + ('extending/index', 'extending.tex', + 'Extending and Embedding Python', _stdauthor, 'manual'), + ('installing/index', 'installing.tex', + 'Installing Python Modules', _stdauthor, 'manual'), + ('library/index', 'library.tex', + 'The Python Library Reference', _stdauthor, 'manual'), + ('reference/index', 'reference.tex', + 'The Python Language Reference', _stdauthor, 'manual'), + ('tutorial/index', 'tutorial.tex', + 'Python Tutorial', _stdauthor, 'manual'), + ('using/index', 'using.tex', + 'Python Setup and Usage', _stdauthor, 'manual'), + ('faq/index', 'faq.tex', + 'Python Frequently Asked Questions', _stdauthor, 'manual'), + ('whatsnew/' + version, 'whatsnew.tex', + 'What\'s New in Python', 'A. M. Kuchling', 'howto'), +] +# Collect all HOWTOs individually +latex_documents.extend(('howto/' + fn[:-4], 'howto-' + fn[:-4] + '.tex', + '', _stdauthor, 'howto') + for fn in os.listdir('howto') + if fn.endswith('.rst') and fn != 'index.rst') + +# Documents to append as an appendix to all manuals. +latex_appendices = ['glossary', 'about', 'license', 'copyright'] + +# Options for Epub output +# ----------------------- + +epub_author = 'Python Documentation Authors' +epub_publisher = 'Python Software Foundation' + +# Options for the coverage checker +# -------------------------------- + +# The coverage checker will ignore all modules/functions/classes whose names +# match any of the following regexes (using re.match). +coverage_ignore_modules = [ + r'[T|t][k|K]', + r'Tix', + r'distutils.*', +] + +coverage_ignore_functions = [ + 'test($|_)', +] + +coverage_ignore_classes = [ +] + +# Glob patterns for C source files for C API coverage, relative to this directory. +coverage_c_path = [ + '../Include/*.h', +] + +# Regexes to find C items in the source files. +coverage_c_regexes = { + 'cfunction': (r'^PyAPI_FUNC\(.*\)\s+([^_][\w_]+)'), + 'data': (r'^PyAPI_DATA\(.*\)\s+([^_][\w_]+)'), + 'macro': (r'^#define ([^_][\w_]+)\(.*\)[\s|\\]'), +} + +# The coverage checker will ignore all C items whose names match these regexes +# (using re.match) -- the keys must be the same as in coverage_c_regexes. +coverage_ignore_c_items = { +# 'cfunction': [...] +} + + +# Options for the link checker +# ---------------------------- + +# Ignore certain URLs. +linkcheck_ignore = [r'https://bugs.python.org/(issue)?\d+', + # Ignore PEPs for now, they all have permanent redirects. + r'http://www.python.org/dev/peps/pep-\d+'] + + +# Options for extensions +# ---------------------- + +# Relative filename of the reference count data file. +refcount_file = 'data/refcounts.dat' diff --git a/cpython_2/environment/repo/Doc/contents.rst b/cpython_2/environment/repo/Doc/contents.rst new file mode 100644 index 0000000000000000000000000000000000000000..8690de77bf3d82b94927322b5241561c3f73d5da --- /dev/null +++ b/cpython_2/environment/repo/Doc/contents.rst @@ -0,0 +1,31 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + Python Documentation contents +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +.. toctree:: + + whatsnew/index.rst + tutorial/index.rst + using/index.rst + reference/index.rst + library/index.rst + extending/index.rst + c-api/index.rst + distributing/index.rst + installing/index.rst + howto/index.rst + faq/index.rst + glossary.rst + + about.rst + bugs.rst + copyright.rst + license.rst + +.. to include legacy packaging docs in build + +.. toctree:: + :hidden: + + distutils/index.rst + install/index.rst diff --git a/cpython_2/environment/repo/Doc/copyright.rst b/cpython_2/environment/repo/Doc/copyright.rst new file mode 100644 index 0000000000000000000000000000000000000000..1b90d9f172c992e852a95fd128f92e06dd776cc4 --- /dev/null +++ b/cpython_2/environment/repo/Doc/copyright.rst @@ -0,0 +1,19 @@ +********* +Copyright +********* + +Python and this documentation is: + +Copyright © 2001-2020 Python Software Foundation. All rights reserved. + +Copyright © 2000 BeOpen.com. All rights reserved. + +Copyright © 1995-2000 Corporation for National Research Initiatives. All rights +reserved. + +Copyright © 1991-1995 Stichting Mathematisch Centrum. All rights reserved. + +------- + +See :ref:`history-and-license` for complete license and permissions information. + diff --git a/cpython_2/environment/repo/Doc/data/refcounts.dat b/cpython_2/environment/repo/Doc/data/refcounts.dat new file mode 100644 index 0000000000000000000000000000000000000000..4dacbe201d22a5bd079e4c605df67ffe0d6c00bb --- /dev/null +++ b/cpython_2/environment/repo/Doc/data/refcounts.dat @@ -0,0 +1,3085 @@ +# Created by Skip Montanaro <skip@mojam.com>. + +# Format: +# function ':' type ':' [param name] ':' [refcount effect] ':' [comment] +# If the param name slot is empty, that line corresponds to the function's +# return value, otherwise it's the type of the named parameter. + +# The first line of a function block gives type/refcount information for the +# function's return value. Successive lines with the same function name +# correspond to the function's parameter list and appear in the order the +# parameters appear in the function's prototype. + +# For readability, each function's lines are surrounded by a blank line. +# The blocks are sorted alphabetically by function name. + +# Refcount behavior is given for all PyObject* types: 0 (no change), +1 +# (increment) and -1 (decrement). A blank refcount field indicates the +# parameter or function value is not a PyObject* and is therefore not +# subject to reference counting. A special case for the value "null" +# (without quotes) is used for functions which return a PyObject* type but +# always return NULL. This is used by some of the PyErr_*() functions, in +# particular. + +# XXX NOTE: the 0/+1/-1 refcount information for arguments is +# confusing! Much more useful would be to indicate whether the +# function "steals" a reference to the argument or not. Take for +# example PyList_SetItem(list, i, item). This lists as a 0 change for +# both the list and the item arguments. However, in fact it steals a +# reference to the item argument! + +# The parameter names are as they appear in the API manual, not the source +# code. + +PyAnySet_Check:int::: +PyAnySet_Check:PyObject*:p:0: + +PyAnySet_CheckExact:int::: +PyAnySet_CheckExact:PyObject*:p:0: + +PyBool_Check:int::: +PyBool_Check:PyObject*:o:0: + +PyBool_FromLong:PyObject*::+1: +PyBool_FromLong:long:v:: + +PyBuffer_FillContiguousStrides:void::: +PyBuffer_FillContiguousStrides:int:ndims:: +PyBuffer_FillContiguousStrides:Py_ssize_t*:shape:: +PyBuffer_FillContiguousStrides:Py_ssize_t*:strides:: +PyBuffer_FillContiguousStrides:int:itemsize:: +PyBuffer_FillContiguousStrides:char:order:: + +PyBuffer_FillInfo:int::: +PyBuffer_FillInfo:Py_buffer*:view:: +PyBuffer_FillInfo:PyObject*:exporter:0: +PyBuffer_FillInfo:void*:buf:: +PyBuffer_FillInfo:Py_ssize_t:len:: +PyBuffer_FillInfo:int:readonly:: +PyBuffer_FillInfo:int:flags:: + +PyBuffer_IsContiguous:int::: +PyBuffer_IsContiguous:Py_buffer*:view:: +PyBuffer_IsContiguous:char:order:: + +PyBuffer_Release:void::: +PyBuffer_Release:Py_buffer*:view:: + +PyBuffer_ToContiguous:int::: +PyBuffer_ToContiguous:void*:buf:: +PyBuffer_ToContiguous:Py_buffer*:src:: +PyBuffer_ToContiguous:Py_ssize_t:len:: +PyBuffer_ToContiguous:char:order:: + +PyByteArray_AS_STRING:char*::: +PyByteArray_AS_STRING:PyObject*:bytearray:0: + +PyByteArray_AsString:char*::: +PyByteArray_AsString:PyObject*:bytearray:0: + +PyByteArray_Check:int::: +PyByteArray_Check:PyObject*:o:0: + +PyByteArray_CheckExact:int::: +PyByteArray_CheckExact:PyObject*:o:0: + +PyByteArray_Concat:PyObject*::+1: +PyByteArray_Concat:PyObject*:a:0: +PyByteArray_Concat:PyObject*:b:0: + +PyByteArray_FromObject:PyObject*::+1: +PyByteArray_FromObject:PyObject*:o:0: + +PyByteArray_FromStringAndSize:PyObject*::+1: +PyByteArray_FromStringAndSize:const char*:string:: +PyByteArray_FromStringAndSize:Py_ssize_t:len:: + +PyByteArray_GET_SIZE:Py_ssize_t::: +PyByteArray_GET_SIZE:PyObject*:bytearray:0: + +PyByteArray_Resize:int::: +PyByteArray_Resize:PyObject*:bytearray:0: +PyByteArray_Resize:Py_ssize_t:len:: + +PyByteArray_Size:Py_ssize_t::: +PyByteArray_Size:PyObject*:bytearray:0: + +PyBytes_AS_STRING:char*::: +PyBytes_AS_STRING:PyObject*:string:0: + +PyBytes_AsString:char*::: +PyBytes_AsString:PyObject*:o:0: + +PyBytes_AsStringAndSize:int::: +PyBytes_AsStringAndSize:PyObject*:obj:0: +PyBytes_AsStringAndSize:char**:buffer:: +PyBytes_AsStringAndSize:Py_ssize_t*:length:: + +PyBytes_Check:int::: +PyBytes_Check:PyObject*:o:0: + +PyBytes_CheckExact:int::: +PyBytes_CheckExact:PyObject*:o:0: + +PyBytes_Concat:void::: +PyBytes_Concat:PyObject**:bytes:0: +PyBytes_Concat:PyObject*:newpart:0: + +PyBytes_ConcatAndDel:void::: +PyBytes_ConcatAndDel:PyObject**:bytes:0: +PyBytes_ConcatAndDel:PyObject*:newpart:-1: + +PyBytes_FromString:PyObject*::+1: +PyBytes_FromString:const char*:v:: + +PyBytes_FromStringAndSize:PyObject*::+1: +PyBytes_FromStringAndSize:const char*:v:: +PyBytes_FromStringAndSize:Py_ssize_t:len:: + +PyBytes_FromFormat:PyObject*::+1: +PyBytes_FromFormat:const char*:format:: +PyBytes_FromFormat::...:: + +PyBytes_FromFormatV:PyObject*::+1: +PyBytes_FromFormatV:const char*:format:: +PyBytes_FromFormatV:va_list:vargs:: + +PyBytes_FromObject:PyObject*::+1: +PyBytes_FromObject:PyObject*:o:0: + +PyBytes_GET_SIZE:Py_ssize_t::: +PyBytes_GET_SIZE:PyObject*:o:0: + +PyBytes_Size:Py_ssize_t::: +PyBytes_Size:PyObject*:o:0: + +PyCapsule_CheckExact:int::: +PyCapsule_CheckExact:PyObject*:p:0: + +PyCapsule_GetContext:void *::: +PyCapsule_GetContext:PyObject*:self:0: + +PyCapsule_GetDestructor:void (*)(PyObject *)::: +PyCapsule_GetDestructor:PyObject*:self:0: + +PyCapsule_GetName:const char *::: +PyCapsule_GetName:PyObject*:self:0: + +PyCapsule_GetPointer:void*::: +PyCapsule_GetPointer:PyObject*:self:0: +PyCapsule_GetPointer:const char *:name:: + +PyCapsule_Import:void *::: +PyCapsule_Import:const char *:name:: +PyCapsule_Import:int:no_block:: + +PyCapsule_IsValid:int::: +PyCapsule_IsValid:PyObject*:capsule:0: +PyCapsule_IsValid:const char*:name:: + +PyCapsule_New:PyObject*::+1: +PyCapsule_New:void*:pointer:: +PyCapsule_New:const char *:name:: +PyCapsule_New::void (* destructor)(PyObject* ):: + +PyCapsule_SetContext:int::: +PyCapsule_SetContext:PyObject*:self:0: +PyCapsule_SetContext:void *:context:: + +PyCapsule_SetDestructor:int::: +PyCapsule_SetDestructor:PyObject*:self:0: +PyCapsule_SetDestructor:void (*)(PyObject *):destructor:: + +PyCapsule_SetName:int::: +PyCapsule_SetName:PyObject*:self:0: +PyCapsule_SetName:const char *:name:: + +PyCapsule_SetPointer:int::: +PyCapsule_SetPointer:PyObject*:self:0: +PyCapsule_SetPointer:void*:pointer:: + +PyCell_Check:int::: +PyCell_Check::ob:: + +PyCell_New:PyObject*::+1: +PyCell_New:PyObject*:ob:0: + +PyCell_GET:PyObject*::0: +PyCell_GET:PyObject*:ob:0: + +PyCell_Get:PyObject*::+1: +PyCell_Get:PyObject*:cell:0: + +PyCell_SET:void::: +PyCell_SET:PyObject*:cell:0: +PyCell_SET:PyObject*:value:0: + +PyCell_Set:int::: +PyCell_Set:PyObject*:cell:0: +PyCell_Set:PyObject*:value:0: + +PyCallIter_Check:int::: +PyCallIter_Check::op:: + +PyCallIter_New:PyObject*::+1: +PyCallIter_New:PyObject*:callable:+1: +PyCallIter_New:PyObject*:sentinel:+1: + +PyCallable_Check:int::: +PyCallable_Check:PyObject*:o:0: + +PyCode_Check:int::: +PyCode_Check:PyObject*:co:0: + +PyCode_GetNumFree:int::: +PyCode_GetNumFree:PyCodeObject*:co:0: + +PyCode_NewWithPosOnlyArgs:PyCodeObject*::+1: +PyCode_NewWithPosOnlyArgs:int:argcount:: +PyCode_NewWithPosOnlyArgs:int:posonlyargcount:: +PyCode_NewWithPosOnlyArgs:int:kwonlyargcount:: +PyCode_NewWithPosOnlyArgs:int:nlocals:: +PyCode_NewWithPosOnlyArgs:int:stacksize:: +PyCode_NewWithPosOnlyArgs:int:flags:: +PyCode_NewWithPosOnlyArgs:PyObject*:code:0: +PyCode_NewWithPosOnlyArgs:PyObject*:consts:0: +PyCode_NewWithPosOnlyArgs:PyObject*:names:0: +PyCode_NewWithPosOnlyArgs:PyObject*:varnames:0: +PyCode_NewWithPosOnlyArgs:PyObject*:freevars:0: +PyCode_NewWithPosOnlyArgs:PyObject*:cellvars:0: +PyCode_NewWithPosOnlyArgs:PyObject*:filename:0: +PyCode_NewWithPosOnlyArgs:PyObject*:name:0: +PyCode_NewWithPosOnlyArgs:int:firstlineno:: +PyCode_NewWithPosOnlyArgs:PyObject*:lnotab:0: + +PyCode_New:PyCodeObject*::+1: +PyCode_New:int:argcount:: +PyCode_New:int:kwonlyargcount:: +PyCode_New:int:nlocals:: +PyCode_New:int:stacksize:: +PyCode_New:int:flags:: +PyCode_New:PyObject*:code:0: +PyCode_New:PyObject*:consts:0: +PyCode_New:PyObject*:names:0: +PyCode_New:PyObject*:varnames:0: +PyCode_New:PyObject*:freevars:0: +PyCode_New:PyObject*:cellvars:0: +PyCode_New:PyObject*:filename:0: +PyCode_New:PyObject*:name:0: +PyCode_New:int:firstlineno:: +PyCode_New:PyObject*:lnotab:0: + +PyCode_NewEmpty:PyCodeObject*::+1: +PyCode_NewEmpty:const char*:filename:: +PyCode_NewEmpty:const char*:funcname:: +PyCode_NewEmpty:int:firstlineno:: + +PyCodec_Register:int::: +PyCodec_Register:PyObject*:search_function:+1: + +PyCodec_KnownEncoding:int::: +PyCodec_KnownEncoding:const char*:encoding:: + +PyCodec_Encode:PyObject*::+1: +PyCodec_Encode:PyObject*:object:0: +PyCodec_Encode:const char*:encoding:: +PyCodec_Encode:const char*:errors:: + +PyCodec_Decode:PyObject*::+1: +PyCodec_Decode:PyObject*:object:0: +PyCodec_Decode:const char*:encoding:: +PyCodec_Decode:const char*:errors:: + +PyCodec_Encoder:PyObject*::+1: +PyCodec_Encoder:const char*:encoding:: + +PyCodec_Decoder:PyObject*::+1: +PyCodec_Decoder:const char*:encoding:: + +PyCodec_IncrementalEncoder:PyObject*::+1: +PyCodec_IncrementalEncoder:const char*:encoding:: +PyCodec_IncrementalEncoder:const char*:errors:: + +PyCodec_IncrementalDecoder:PyObject*::+1: +PyCodec_IncrementalDecoder:const char*:encoding:: +PyCodec_IncrementalDecoder:const char*:errors:: + +PyCodec_StreamReader:PyObject*::+1: +PyCodec_StreamReader:const char*:encoding:: +PyCodec_StreamReader:PyObject*:stream:0: +PyCodec_StreamReader:const char*:errors:: + +PyCodec_StreamWriter:PyObject*::+1: +PyCodec_StreamWriter:const char*:encoding:: +PyCodec_StreamWriter:PyObject*:stream:0: +PyCodec_StreamWriter:const char*:errors:: + +PyCodec_RegisterError:int::: +PyCodec_RegisterError:const char*:name:: +PyCodec_RegisterError:PyObject*:error:+1: + +PyCodec_LookupError:PyObject*::+1: +PyCodec_LookupError:const char*:name:: + +PyCodec_StrictErrors:PyObject*::null: +PyCodec_StrictErrors:PyObject*:exc:0: + +PyCodec_IgnoreErrors:PyObject*::+1: +PyCodec_IgnoreErrors:PyObject*:exc:0: + +PyCodec_ReplaceErrors:PyObject*::+1: +PyCodec_ReplaceErrors:PyObject*:exc:0: + +PyCodec_XMLCharRefReplaceErrors:PyObject*::+1: +PyCodec_XMLCharRefReplaceErrors:PyObject*:exc:0: + +PyCodec_BackslashReplaceErrors:PyObject*::+1: +PyCodec_BackslashReplaceErrors:PyObject*:exc:0: + +PyCodec_NameReplaceErrors:PyObject*::+1: +PyCodec_NameReplaceErrors:PyObject*:exc:0: + +PyComplex_AsCComplex:Py_complex::: +PyComplex_AsCComplex:PyObject*:op:0: + +PyComplex_Check:int::: +PyComplex_Check:PyObject*:p:0: + +PyComplex_CheckExact:int::: +PyComplex_CheckExact:PyObject*:p:0: + +PyComplex_FromCComplex:PyObject*::+1: +PyComplex_FromCComplex::Py_complex v:: + +PyComplex_FromDoubles:PyObject*::+1: +PyComplex_FromDoubles::double real:: +PyComplex_FromDoubles::double imag:: + +PyComplex_ImagAsDouble:double::: +PyComplex_ImagAsDouble:PyObject*:op:0: + +PyComplex_RealAsDouble:double::: +PyComplex_RealAsDouble:PyObject*:op:0: + +PyContext_CheckExact:int::: +PyContext_CheckExact:PyObject*:o:0: + +PyContext_ClearFreeList:int::: + +PyContext_Copy:PyObject*::+1: +PyContext_Copy:PyObject*:ctx:0: + +PyContext_CopyCurrent:PyObject*::+1: + +PyContext_Enter:int::: +PyContext_Enter:PyObject*:ctx:+1: + +PyContext_Exit:int::: +PyContext_Exit:PyObject*:ctx:-1: + +PyContext_New:PyObject*::+1: + +PyContextToken_CheckExact:int::: +PyContextToken_CheckExact:PyObject*:o:0: + +PyContextVar_CheckExact:int::: +PyContextVar_CheckExact:PyObject*:o:0: + +PyContextVar_Get:int::: +PyContextVar_Get:PyObject*:var:0: +PyContextVar_Get:PyObject*:default_value:0: +PyContextVar_Get:PyObject**:value:+1:??? + +PyContextVar_New:PyObject*::+1: +PyContextVar_New:const char*:name:: +PyContextVar_New:PyObject*:def:+1: + +PyContextVar_Set:PyObject*::+1: +PyContextVar_Set:PyObject*:var:0: +PyContextVar_Set:PyObject*:value:+1: + +PyContextVar_Reset:int::: +PyContextVar_Reset:PyObject*:var:0: +PyContextVar_Reset:PyObject*:token:-1: + +PyDate_Check:int::: +PyDate_Check:PyObject*:ob:0: + +PyDate_CheckExact:int::: +PyDate_CheckExact:PyObject*:ob:0: + +PyDate_FromDate:PyObject*::+1: +PyDate_FromDate:int:year:: +PyDate_FromDate:int:month:: +PyDate_FromDate:int:day:: + +PyDate_FromTimestamp:PyObject*::+1: +PyDate_FromTimestamp:PyObject*:args:0: + +PyDateTime_Check:int::: +PyDateTime_Check:PyObject*:ob:0: + +PyDateTime_CheckExact:int::: +PyDateTime_CheckExact:PyObject*:ob:0: + +PyDateTime_FromDateAndTime:PyObject*::+1: +PyDateTime_FromDateAndTime:int:year:: +PyDateTime_FromDateAndTime:int:month:: +PyDateTime_FromDateAndTime:int:day:: +PyDateTime_FromDateAndTime:int:hour:: +PyDateTime_FromDateAndTime:int:minute:: +PyDateTime_FromDateAndTime:int:second:: +PyDateTime_FromDateAndTime:int:usecond:: + +PyDateTime_FromDateAndTimeAndFold:PyObject*::+1: +PyDateTime_FromDateAndTimeAndFold:int:year:: +PyDateTime_FromDateAndTimeAndFold:int:month:: +PyDateTime_FromDateAndTimeAndFold:int:day:: +PyDateTime_FromDateAndTimeAndFold:int:hour:: +PyDateTime_FromDateAndTimeAndFold:int:minute:: +PyDateTime_FromDateAndTimeAndFold:int:second:: +PyDateTime_FromDateAndTimeAndFold:int:usecond:: +PyDateTime_FromDateAndTimeAndFold:int:fold:: + +PyDateTime_FromTimestamp:PyObject*::+1: +PyDateTime_FromTimestamp:PyObject*:args:0: + +PyDelta_Check:int::: +PyDelta_Check:PyObject*:ob:0: + +PyDelta_CheckExact:int::: +PyDelta_CheckExact:PyObject*:ob:0: + +PyDelta_FromDSU:PyObject*::+1: +PyDelta_FromDSU:int:days:: +PyDelta_FromDSU:int:seconds:: +PyDelta_FromDSU:int:useconds:: + +PyTimeZone_FromOffset:PyObject*::+1: +PyTimeZone_FromOffset:PyObject*:offset:+1:Reference count not increased if offset is +00:00 + +PyTimeZone_FromOffsetAndName:PyObject*::+1: +PyTimeZone_FromOffsetAndName:PyObject*:offset:+1:Reference count not increased if offset is +00:00 and name == NULL +PyTimeZone_FromOffsetAndName:PyObject*:name:+1: + + +PyDescr_IsData:int::: +PyDescr_IsData:PyObject*:descr:0: + +PyDescr_NewClassMethod:PyObject*::+1: +PyDescr_NewClassMethod:PyTypeObject*:type:+1: +PyDescr_NewClassMethod:PyMethodDef*:method:: + +PyDescr_NewGetSet:PyObject*::+1: +PyDescr_NewGetSet:PyTypeObject*:type:+1: +PyDescr_NewGetSet:PyGetSetDef*:getset:: + +PyDescr_NewMember:PyObject*::+1: +PyDescr_NewMember:PyTypeObject*:type:+1: +PyDescr_NewMember:PyMemberDef*:member:: + +PyDescr_NewMethod:PyObject*::+1: +PyDescr_NewMethod:PyTypeObject*:type:+1: +PyDescr_NewMethod:PyMethodDef*:meth:: + +PyDescr_NewWrapper:PyObject*::+1: +PyDescr_NewWrapper:PyTypeObject*:type:+1: +PyDescr_NewWrapper:struct wrapperbase*:base:: +PyDescr_NewWrapper:void*:wrapped:: + +PyDict_Check:int::: +PyDict_Check:PyObject*:p:0: + +PyDict_CheckExact:int::: +PyDict_CheckExact:PyObject*:p:0: + +PyDict_Clear:void::: +PyDict_Clear:PyObject*:p:0: + +PyDict_Contains:int::: +PyDict_Contains:PyObject*:p:0: +PyDict_Contains:PyObject*:key:0: + +PyDict_DelItem:int::: +PyDict_DelItem:PyObject*:p:0: +PyDict_DelItem:PyObject*:key:0: + +PyDict_DelItemString:int::: +PyDict_DelItemString:PyObject*:p:0: +PyDict_DelItemString:const char*:key:: + +PyDict_GetItem:PyObject*::0: +PyDict_GetItem:PyObject*:p:0: +PyDict_GetItem:PyObject*:key:0: + +PyDict_GetItemWithError:PyObject*::0:0 +PyDict_GetItemWithError:PyObject*:p:0: +PyDict_GetItemWithError:PyObject*:key:0: + +PyDict_GetItemString:PyObject*::0: +PyDict_GetItemString:PyObject*:p:0: +PyDict_GetItemString:const char*:key:: + +PyDict_SetDefault:PyObject*::0: +PyDict_SetDefault:PyObject*:p:0: +PyDict_SetDefault:PyObject*:key:0:conditionally +1 if inserted into the dict +PyDict_SetDefault:PyObject*:default:0:conditionally +1 if inserted into the dict + +PyDict_Items:PyObject*::+1: +PyDict_Items:PyObject*:p:0: + +PyDict_Keys:PyObject*::+1: +PyDict_Keys:PyObject*:p:0: + +PyDict_New:PyObject*::+1: + +PyDict_Copy:PyObject*::+1: +PyDict_Copy:PyObject*:p:0: + +PyDict_Merge:int::: +PyDict_Merge:PyObject*:a:0: +PyDict_Merge:PyObject*:b:0: +PyDict_Merge:int:override:: + +PyDict_MergeFromSeq2:int::: +PyDict_MergeFromSeq2:PyObject*:a:0: +PyDict_MergeFromSeq2:PyObject*:seq2:0: +PyDict_MergeFromSeq2:int:override:: + +PyDict_Next:int::: +PyDict_Next:PyObject*:p:0: +PyDict_Next:Py_ssize_t:ppos:: +PyDict_Next:PyObject**:pkey:0: +PyDict_Next:PyObject**:pvalue:0: + +PyDict_SetItem:int::: +PyDict_SetItem:PyObject*:p:0: +PyDict_SetItem:PyObject*:key:+1: +PyDict_SetItem:PyObject*:val:+1: + +PyDict_SetItemString:int::: +PyDict_SetItemString:PyObject*:p:0: +PyDict_SetItemString:const char*:key:: +PyDict_SetItemString:PyObject*:val:+1: + +PyDict_Size:Py_ssize_t::: +PyDict_Size:PyObject*:p:0: + +PyDict_Update:int::: +PyDict_Update:PyObject*:a:0: +PyDict_Update:PyObject*:b:0: + +PyDict_Values:PyObject*::+1: +PyDict_Values:PyObject*:p:0: + +PyDictProxy_New:PyObject*::+1: +PyDictProxy_New:PyObject*:dict:0: + +PyErr_BadArgument:int::: + +PyErr_BadInternalCall:void::: + +PyErr_CheckSignals:int::: + +PyErr_Clear:void::: + +PyErr_ExceptionMatches:int::: +PyErr_ExceptionMatches:PyObject*:exc:0: + +PyErr_Fetch:void::: +PyErr_Fetch:PyObject**:ptype:0: +PyErr_Fetch:PyObject**:pvalue:0: +PyErr_Fetch:PyObject**:ptraceback:0: + +PyErr_Format:PyObject*::null: +PyErr_Format:PyObject*:exception:+1: +PyErr_Format:const char*:format:: +PyErr_Format::...:: + +PyErr_FormatV:PyObject*::null: +PyErr_FormatV:PyObject*:exception:+1: +PyErr_FormatV:const char*:format:: +PyErr_FormatV:va_list:vargs:: + +PyErr_GetExcInfo:void::: +PyErr_GetExcInfo:PyObject**:ptype:+1: +PyErr_GetExcInfo:PyObject**:pvalue:+1: +PyErr_GetExcInfo:PyObject**:ptraceback:+1: + +PyErr_GivenExceptionMatches:int::: +PyErr_GivenExceptionMatches:PyObject*:given:0: +PyErr_GivenExceptionMatches:PyObject*:exc:0: + +PyErr_NewException:PyObject*::+1: +PyErr_NewException:const char*:name:: +PyErr_NewException:PyObject*:base:0: +PyErr_NewException:PyObject*:dict:0: + +PyErr_NewExceptionWithDoc:PyObject*::+1: +PyErr_NewExceptionWithDoc:const char*:name:: +PyErr_NewExceptionWithDoc:const char*:doc:: +PyErr_NewExceptionWithDoc:PyObject*:base:0: +PyErr_NewExceptionWithDoc:PyObject*:dict:0: + +PyErr_NoMemory:PyObject*::null: + +PyErr_NormalizeException:void::: +PyErr_NormalizeException:PyObject**:exc::??? +PyErr_NormalizeException:PyObject**:val::??? +PyErr_NormalizeException:PyObject**:tb::??? + +PyErr_Occurred:PyObject*::0: + +PyErr_Print:void::: + +PyErr_PrintEx:void::: +PyErr_PrintEx:int:set_sys_last_vars:: + +PyErr_ResourceWarning:int::: +PyErr_ResourceWarning:PyObject*:source:0: +PyErr_ResourceWarning:Py_ssize_t:stack_level:: +PyErr_ResourceWarning:const char*:format:: +PyErr_ResourceWarning::...:: + +PyErr_Restore:void::: +PyErr_Restore:PyObject*:type:-1: +PyErr_Restore:PyObject*:value:-1: +PyErr_Restore:PyObject*:traceback:-1: + +PyErr_SetExcFromWindowsErr:PyObject*::null: +PyErr_SetExcFromWindowsErr:PyObject*:type:+1: +PyErr_SetExcFromWindowsErr:int:ierr:: + +PyErr_SetExcFromWindowsErrWithFilename:PyObject*::null: +PyErr_SetExcFromWindowsErrWithFilename:PyObject*:type:+1: +PyErr_SetExcFromWindowsErrWithFilename:int:ierr:: +PyErr_SetExcFromWindowsErrWithFilename:const char*:filename:: + +PyErr_SetExcFromWindowsErrWithFilenameObject:PyObject*::null: +PyErr_SetExcFromWindowsErrWithFilenameObject:PyObject*:type:+1: +PyErr_SetExcFromWindowsErrWithFilenameObject:int:ierr:: +PyErr_SetExcFromWindowsErrWithFilenameObject:PyObject*:filename:+1: + +PyErr_SetExcFromWindowsErrWithFilenameObjects:PyObject*::null: +PyErr_SetExcFromWindowsErrWithFilenameObjects:PyObject*:type:+1: +PyErr_SetExcFromWindowsErrWithFilenameObjects:int:ierr:: +PyErr_SetExcFromWindowsErrWithFilenameObjects:PyObject*:filename:+1: +PyErr_SetExcFromWindowsErrWithFilenameObjects:PyObject*:filename2:+1: + +PyErr_SetExcInfo:void::: +PyErr_SetExcInfo:PyObject*:type:0: +PyErr_SetExcInfo:PyObject*:value:0: +PyErr_SetExcInfo:PyObject*:traceback:0: + +PyErr_SetFromErrno:PyObject*::null: +PyErr_SetFromErrno:PyObject*:type:+1: + +PyErr_SetFromErrnoWithFilename:PyObject*::null: +PyErr_SetFromErrnoWithFilename:PyObject*:type:+1: +PyErr_SetFromErrnoWithFilename:const char*:filename:: + +PyErr_SetFromErrnoWithFilenameObject:PyObject*::null: +PyErr_SetFromErrnoWithFilenameObject:PyObject*:type:+1: +PyErr_SetFromErrnoWithFilenameObject:PyObject*:filenameObject:+1: + +PyErr_SetFromErrnoWithFilenameObjects:PyObject*::null: +PyErr_SetFromErrnoWithFilenameObjects:PyObject*:type:+1: +PyErr_SetFromErrnoWithFilenameObjects:PyObject*:filenameObject:+1: +PyErr_SetFromErrnoWithFilenameObjects:PyObject*:filenameObject2:+1: + +PyErr_SetFromWindowsErr:PyObject*::null: +PyErr_SetFromWindowsErr:int:ierr:: + +PyErr_SetFromWindowsErrWithFilename:PyObject*::null: +PyErr_SetFromWindowsErrWithFilename:int:ierr:: +PyErr_SetFromWindowsErrWithFilename:const char*:filename:: + +PyErr_SetImportError:PyObject*::null: +PyErr_SetImportError:PyObject*:msg:+1: +PyErr_SetImportError:PyObject*:name:+1: +PyErr_SetImportError:PyObject*:path:+1: + +PyErr_SetImportErrorSubclass:PyObject*::null: +PyErr_SetImportErrorSubclass:PyObject*:msg:+1: +PyErr_SetImportErrorSubclass:PyObject*:name:+1: +PyErr_SetImportErrorSubclass:PyObject*:path:+1: + +PyErr_SetInterrupt:void::: + +PyErr_SetNone:void::: +PyErr_SetNone:PyObject*:type:+1: + +PyErr_SetObject:void::: +PyErr_SetObject:PyObject*:type:+1: +PyErr_SetObject:PyObject*:value:+1: + +PyErr_SetString:void::: +PyErr_SetString:PyObject*:type:+1: +PyErr_SetString:const char*:message:: + +PyErr_SyntaxLocation:void::: +PyErr_SyntaxLocation:const char*:filename:: +PyErr_SyntaxLocation:int:lineno:: + +PyErr_SyntaxLocationEx:void::: +PyErr_SyntaxLocationEx:const char*:filename:: +PyErr_SyntaxLocationEx:int:lineno:: +PyErr_SyntaxLocationEx:int:col_offset:: + +PyErr_SyntaxLocationObject:void::: +PyErr_SyntaxLocationObject:PyObject*:filename:+1: +PyErr_SyntaxLocationObject:int:lineno:: +PyErr_SyntaxLocationObject:int:col_offset:: + +PyErr_WarnEx:int::: +PyErr_WarnEx:PyObject*:category:0: +PyErr_WarnEx:const char*:message:: +PyErr_WarnEx:Py_ssize_t:stack_level:: + +PyErr_WarnExplicit:int::: +PyErr_WarnExplicit:PyObject*:category:0: +PyErr_WarnExplicit:const char*:message:: +PyErr_WarnExplicit:const char*:filename:: +PyErr_WarnExplicit:int:lineno:: +PyErr_WarnExplicit:const char*:module:: +PyErr_WarnExplicit:PyObject*:registry:0: + +PyErr_WarnExplicitObject:int::: +PyErr_WarnExplicitObject:PyObject*:category:0: +PyErr_WarnExplicitObject:PyObject*:message:0: +PyErr_WarnExplicitObject:PyObject*:filename:0: +PyErr_WarnExplicitObject:int:lineno:: +PyErr_WarnExplicitObject:PyObject*:module:0: +PyErr_WarnExplicitObject:PyObject*:registry:0: + +PyErr_WarnFormat:int::: +PyErr_WarnFormat:PyObject*:category:0: +PyErr_WarnFormat:Py_ssize_t:stack_level:: +PyErr_WarnFormat:const char*:format:: +PyErr_WarnFormat::...:: + +PyErr_WriteUnraisable:void::: +PyErr_WriteUnraisable:PyObject*:obj:0: + +PyEval_AcquireLock:void::: + +PyEval_AcquireThread:void::: +PyEval_AcquireThread:PyThreadState*:tstate:: + +PyEval_GetBuiltins:PyObject*::0: + +PyEval_GetLocals:PyObject*::0: + +PyEval_GetGlobals:PyObject*::0: + +PyEval_GetFrame:PyObject*::0: + +PyEval_GetFuncDesc:const char*::: +PyEval_GetFuncDesc:PyObject*:func:0: + +PyEval_GetFuncName:const char*::: +PyEval_GetFuncName:PyObject*:func:0: + +PyEval_InitThreads:void::: + +PyEval_ReleaseLock:void::: + +PyEval_ReleaseThread:void::: +PyEval_ReleaseThread:PyThreadState*:tstate:: + +PyEval_RestoreThread:void::: +PyEval_RestoreThread:PyThreadState*:tstate:: + +PyEval_SaveThread:PyThreadState*::: + +PyEval_SetProfile:void::: +PyEval_SetProfile:Py_tracefunc:func:: +PyEval_SetProfile:PyObject*:obj:+1: + +PyEval_SetTrace:void::: +PyEval_SetTrace:Py_tracefunc:func:: +PyEval_SetTrace:PyObject*:obj:+1: + +PyEval_EvalCode:PyObject*::+1: +PyEval_EvalCode:PyObject*:co:0: +PyEval_EvalCode:PyObject*:globals:0: +PyEval_EvalCode:PyObject*:locals:0: + +PyEval_EvalCodeEx:PyObject*::+1: +PyEval_EvalCodeEx:PyObject*:co:0: +PyEval_EvalCodeEx:PyObject*:globals:0: +PyEval_EvalCodeEx:PyObject*:locals:0: +PyEval_EvalCodeEx:PyObject*const*:args:: +PyEval_EvalCodeEx:int:argcount:: +PyEval_EvalCodeEx:PyObject*const*:kws:: +PyEval_EvalCodeEx:int:kwcount:: +PyEval_EvalCodeEx:PyObject*const*:defs:: +PyEval_EvalCodeEx:int:defcount:: +PyEval_EvalCodeEx:PyObject*:kwdefs:0: +PyEval_EvalCodeEx:PyObject*:closure:0: + +PyEval_EvalFrame:PyObject*::+1: +PyEval_EvalFrame:PyFrameObject*:f:0: + +PyEval_EvalFrameEx:PyObject*::+1: +PyEval_EvalFrameEx:PyFrameObject*:f:0: +PyEval_EvalFrameEx:int:throwflag:: + +PyEval_MergeCompilerFlags:int::: +PyEval_MergeCompilerFlags:PyCompilerFlags*:cf:: + +PyException_GetCause:PyObject*::+1: +PyException_GetCause:PyObject*:ex:0: + +PyException_GetContext:PyObject*::+1: +PyException_GetContext:PyObject*:ex:0: + +PyException_GetTraceback:PyObject*::+1: +PyException_GetTraceback:PyObject*:ex:0: + +PyException_SetCause:void::: +PyException_SetCause:PyObject*:ex:0: +PyException_SetCause:PyObject*:cause:+1: + +PyException_SetContext:void::: +PyException_SetContext:PyObject*:ex:0: +PyException_SetContext:PyObject*:ctx:+1: + +PyException_SetTraceback:int::: +PyException_SetTraceback:PyObject*:ex:0: +PyException_SetTraceback:PyObject*:tb:+1: + +PyFile_FromFd:PyObject*::+1: +PyFile_FromFd:int:fd:: +PyFile_FromFd:const char*:name:: +PyFile_FromFd:const char*:mode:: +PyFile_FromFd:int:buffering:: +PyFile_FromFd:const char*:encoding:: +PyFile_FromFd:const char*:errors:: +PyFile_FromFd:const char*:newline:: +PyFile_FromFd:int:closefd:: + +PyFile_GetLine:PyObject*::+1: +PyFile_GetLine:PyObject*:p:0: +PyFile_GetLine:int:n:: + +PyFile_WriteObject:int::: +PyFile_WriteObject:PyObject*:obj:0: +PyFile_WriteObject:PyObject*:p:0: +PyFile_WriteObject:int:flags:: + +PyFile_WriteString:int::: +PyFile_WriteString:const char*:s:: +PyFile_WriteString:PyObject*:p:0: +PyFile_WriteString:int:flags:: + +PyFloat_AS_DOUBLE:double::: +PyFloat_AS_DOUBLE:PyObject*:pyfloat:0: + +PyFloat_AsDouble:double::: +PyFloat_AsDouble:PyObject*:pyfloat:0: + +PyFloat_Check:int::: +PyFloat_Check:PyObject*:p:0: + +PyFloat_CheckExact:int::: +PyFloat_CheckExact:PyObject*:p:0: + +PyFloat_FromDouble:PyObject*::+1: +PyFloat_FromDouble:double:v:: + +PyFloat_FromString:PyObject*::+1: +PyFloat_FromString:PyObject*:str:0: + +PyFloat_GetInfo:PyObject*::+1: +PyFloat_GetInfo::void:: + +PyFrozenSet_Check:int::: +PyFrozenSet_Check:PyObject*:p:0: + +PyFrozenSet_CheckExact:int::: +PyFrozenSet_CheckExact:PyObject*:p:0: + +PyFrozenSet_New:PyObject*::+1: +PyFrozenSet_New:PyObject*:iterable:0: + +PyFunction_Check:int::: +PyFunction_Check:PyObject*:o:0: + +PyFunction_GetAnnotations:PyObject*::0: +PyFunction_GetAnnotations:PyObject*:op:0: + +PyFunction_GetClosure:PyObject*::0: +PyFunction_GetClosure:PyObject*:op:0: + +PyFunction_GetCode:PyObject*::0: +PyFunction_GetCode:PyObject*:op:0: + +PyFunction_GetDefaults:PyObject*::0: +PyFunction_GetDefaults:PyObject*:op:0: + +PyFunction_GetGlobals:PyObject*::0: +PyFunction_GetGlobals:PyObject*:op:0: + +PyFunction_GetModule:PyObject*::0: +PyFunction_GetModule:PyObject*:op:0: + +PyFunction_New:PyObject*::+1: +PyFunction_New:PyObject*:code:+1: +PyFunction_New:PyObject*:globals:+1: + +PyFunction_NewWithQualName:PyObject*::+1: +PyFunction_NewWithQualName:PyObject*:code:+1: +PyFunction_NewWithQualName:PyObject*:globals:+1: +PyFunction_NewWithQualName:PyObject*:qualname:+1: + +PyFunction_SetAnnotations:int::: +PyFunction_SetAnnotations:PyObject*:op:0: +PyFunction_SetAnnotations:PyObject*:annotations:+1: + +PyFunction_SetClosure:int::: +PyFunction_SetClosure:PyObject*:op:0: +PyFunction_SetClosure:PyObject*:closure:+1: + +PyFunction_SetDefaults:int::: +PyFunction_SetDefaults:PyObject*:op:0: +PyFunction_SetDefaults:PyObject*:defaults:+1: + +PyGen_Check:int::: +PyGen_Check:PyObject*:ob:0: + +PyGen_CheckExact:int::: +PyGen_CheckExact:PyObject*:ob:0: + +PyGen_New:PyObject*::+1: +PyGen_New:PyFrameObject*:frame:0: + +PyGen_NewWithQualName:PyObject*::+1: +PyGen_NewWithQualName:PyFrameObject*:frame:0: +PyGen_NewWithQualName:PyObject*:name:0: +PyGen_NewWithQualName:PyObject*:qualname:0: + +PyCoro_CheckExact:int::: +PyCoro_CheckExact:PyObject*:ob:0: + +PyCoro_New:PyObject*::+1: +PyCoro_New:PyFrameObject*:frame:0: +PyCoro_New:PyObject*:name:0: +PyCoro_New:PyObject*:qualname:0: + +PyImport_AddModule:PyObject*::0:reference borrowed from sys.modules +PyImport_AddModule:const char*:name:: + +PyImport_AddModuleObject:PyObject*::0:reference borrowed from sys.modules +PyImport_AddModuleObject:PyObject*:name:0: + +PyImport_Cleanup:void::: + +PyImport_ExecCodeModule:PyObject*::+1: +PyImport_ExecCodeModule:const char*:name:: +PyImport_ExecCodeModule:PyObject*:co:0: + +PyImport_ExecCodeModuleEx:PyObject*::+1: +PyImport_ExecCodeModuleEx:const char*:name:: +PyImport_ExecCodeModuleEx:PyObject*:co:0: +PyImport_ExecCodeModuleEx:const char*:pathname:: + +PyImport_ExecCodeModuleObject:PyObject*::+1: +PyImport_ExecCodeModuleObject:const char*:name:: +PyImport_ExecCodeModuleObject:PyObject*:co:0: +PyImport_ExecCodeModuleObject:PyObject*:pathname:0: +PyImport_ExecCodeModuleObject:PyObject*:cpathname:0: + +PyImport_ExecCodeModuleWithPathnames:PyObject*::+1: +PyImport_ExecCodeModuleWithPathnames:const char*:name:: +PyImport_ExecCodeModuleWithPathnames:PyObject*:co:0: +PyImport_ExecCodeModuleWithPathnames:const char*:pathname:: +PyImport_ExecCodeModuleWithPathnames:const char*:cpathname:: + +PyImport_GetImporter:PyObject*::+1: +PyImport_GetImporter:PyObject*:path:0: + +PyImport_GetMagicNumber:long::: + +PyImport_GetModule:PyObject*::+1: +PyImport_GetModule:PyObject*:name:0: + +PyImport_GetModuleDict:PyObject*::0: + +PyImport_Import:PyObject*::+1: +PyImport_Import:PyObject*:name:0: + +PyImport_ImportFrozenModule:int::: +PyImport_ImportFrozenModule:const char*::: + +PyImport_ImportFrozenModuleObject:int::: +PyImport_ImportFrozenModuleObject:PyObject*::+1: + +PyImport_ImportModule:PyObject*::+1: +PyImport_ImportModule:const char*:name:: + +PyImport_ImportModuleEx:PyObject*::+1: +PyImport_ImportModuleEx:const char*:name:: +PyImport_ImportModuleEx:PyObject*:globals:0:??? +PyImport_ImportModuleEx:PyObject*:locals:0:??? +PyImport_ImportModuleEx:PyObject*:fromlist:0:??? + +PyImport_ImportModuleLevel:PyObject*::+1: +PyImport_ImportModuleLevel:const char*:name:: +PyImport_ImportModuleLevel:PyObject*:globals:0:??? +PyImport_ImportModuleLevel:PyObject*:locals:0:??? +PyImport_ImportModuleLevel:PyObject*:fromlist:0:??? +PyImport_ImportModuleLevel:int:level:: + +PyImport_ImportModuleLevelObject:PyObject*::+1: +PyImport_ImportModuleLevelObject:PyObject*:name:0: +PyImport_ImportModuleLevelObject:PyObject*:globals:0:??? +PyImport_ImportModuleLevelObject:PyObject*:locals:0:??? +PyImport_ImportModuleLevelObject:PyObject*:fromlist:0:??? +PyImport_ImportModuleLevelObject:int:level:: + +PyImport_ImportModuleNoBlock:PyObject*::+1: +PyImport_ImportModuleNoBlock:const char*:name:: + +PyImport_ReloadModule:PyObject*::+1: +PyImport_ReloadModule:PyObject*:m:0: + +PyIndex_Check:int::: +PyIndex_Check:PyObject*:o:0: + +PyInstanceMethod_Check:int::: +PyInstanceMethod_Check:PyObject*:o:0: + +PyInstanceMethod_Function:PyObject*::0: +PyInstanceMethod_Function:PyObject*:im:0: + +PyInstanceMethod_GET_FUNCTION:PyObject*::0: +PyInstanceMethod_GET_FUNCTION:PyObject*:im:0: + +PyInstanceMethod_New:PyObject*::+1: +PyInstanceMethod_New:PyObject*:func:0: + +PyInterpreterState_Clear:void::: +PyInterpreterState_Clear:PyInterpreterState*:interp:: + +PyInterpreterState_Delete:void::: +PyInterpreterState_Delete:PyInterpreterState*:interp:: + +PyInterpreterState_GetID:int64_t::: +PyInterpreterState_GetID:PyInterpreterState*:interp:: + +PyInterpreterState_New:PyInterpreterState*::: + +PyIter_Check:int::: +PyIter_Check:PyObject*:o:0: + +PyIter_Next:PyObject*::+1: +PyIter_Next:PyObject*:o:0: + +PyList_Append:int::: +PyList_Append:PyObject*:list:0: +PyList_Append:PyObject*:item:+1: + +PyList_AsTuple:PyObject*::+1: +PyList_AsTuple:PyObject*:list:0: + +PyList_Check:int::: +PyList_Check:PyObject*:p:0: + +PyList_CheckExact:int::: +PyList_CheckExact:PyObject*:p:0: + +PyList_GET_ITEM:PyObject*::0: +PyList_GET_ITEM:PyObject*:list:0: +PyList_GET_ITEM:Py_ssize_t:i:: + +PyList_GET_SIZE:Py_ssize_t::: +PyList_GET_SIZE:PyObject*:list:0: + +PyList_GetItem:PyObject*::0: +PyList_GetItem:PyObject*:list:0: +PyList_GetItem:Py_ssize_t:index:: + +PyList_GetSlice:PyObject*::+1: +PyList_GetSlice:PyObject*:list:0: +PyList_GetSlice:Py_ssize_t:low:: +PyList_GetSlice:Py_ssize_t:high:: + +PyList_Insert:int::: +PyList_Insert:PyObject*:list:0: +PyList_Insert:Py_ssize_t:index:: +PyList_Insert:PyObject*:item:+1: + +PyList_New:PyObject*::+1: +PyList_New:Py_ssize_t:len:: + +PyList_Reverse:int::: +PyList_Reverse:PyObject*:list:0: + +PyList_SET_ITEM:void::: +PyList_SET_ITEM:PyObject*:list:0: +PyList_SET_ITEM:Py_ssize_t:i:: +PyList_SET_ITEM:PyObject*:o:0: + +PyList_SetItem:int::: +PyList_SetItem:PyObject*:list:0: +PyList_SetItem:Py_ssize_t:index:: +PyList_SetItem:PyObject*:item:0: + +PyList_SetSlice:int::: +PyList_SetSlice:PyObject*:list:0: +PyList_SetSlice:Py_ssize_t:low:: +PyList_SetSlice:Py_ssize_t:high:: +PyList_SetSlice:PyObject*:itemlist:0:but increfs its elements? + +PyList_Size:Py_ssize_t::: +PyList_Size:PyObject*:list:0: + +PyList_Sort:int::: +PyList_Sort:PyObject*:list:0: + +PyLong_AsDouble:double::: +PyLong_AsDouble:PyObject*:pylong:0: + +PyLong_AsLong:long::: +PyLong_AsLong:PyObject*:pylong:0: + +PyLong_AsLongAndOverflow:long::: +PyLong_AsLongAndOverflow:PyObject*:obj:0: +PyLong_AsLongAndOverflow:int*:overflow:: + +PyLong_AsLongLong:long long::: +PyLong_AsLongLong:PyObject*:obj:0: + +PyLong_AsLongLongAndOverflow:long long::: +PyLong_AsLongLongAndOverflow:PyObject*:obj:0: +PyLong_AsLongLongAndOverflow:int*:overflow:: + +PyLong_AsSize_t:size_t::: +PyLong_AsSize_t:PyObject*:pylong:0: + +PyLong_AsSsize_t:Py_ssize_t::: +PyLong_AsSsize_t:PyObject*:pylong:0: + +PyLong_AsUnsignedLong:unsigned long::: +PyLong_AsUnsignedLong:PyObject*:pylong:0: + +PyLong_AsUnsignedLongLong:unsigned long long::: +PyLong_AsUnsignedLongLong:PyObject*:pylong:0: + +PyLong_AsUnsignedLongMask:unsigned long::: +PyLong_AsUnsignedLongMask:PyObject*:obj:0: + +PyLong_AsUnsignedLongLongMask:unsigned long long::: +PyLong_AsUnsignedLongLongMask:PyObject*:obj:0: + +PyLong_AsVoidPtr:void*::: +PyLong_AsVoidPtr:PyObject*:pylong:0: + +PyLong_Check:int::: +PyLong_Check:PyObject*:p:0: + +PyLong_CheckExact:int::: +PyLong_CheckExact:PyObject*:p:0: + +PyLong_FromDouble:PyObject*::+1: +PyLong_FromDouble:double:v:: + +PyLong_FromLong:PyObject*::+1: +PyLong_FromLong:long:v:: + +PyLong_FromLongLong:PyObject*::+1: +PyLong_FromLongLong:long long:v:: + +PyLong_FromUnsignedLongLong:PyObject*::+1: +PyLong_FromUnsignedLongLong:unsigned long long:v:: + +PyLong_FromSize_t:PyObject*::+1: +PyLong_FromSize_t:size_t:v:: + +PyLong_FromSsize_t:PyObject*::+1: +PyLong_FromSsize_t:Py_ssize_t:v:: + +PyLong_FromString:PyObject*::+1: +PyLong_FromString:const char*:str:: +PyLong_FromString:char**:pend:: +PyLong_FromString:int:base:: + +PyLong_FromUnicode:PyObject*::+1: +PyLong_FromUnicode:Py_UNICODE*:u:: +PyLong_FromUnicode:Py_ssize_t:length:: +PyLong_FromUnicode:int:base:: + +PyLong_FromUnicodeObject:PyObject*::+1: +PyLong_FromUnicodeObject:PyObject*:u:0: +PyLong_FromUnicodeObject:int:base:: + +PyLong_FromUnsignedLong:PyObject*::+1: +PyLong_FromUnsignedLong:unsignedlong:v:: + +PyLong_FromVoidPtr:PyObject*::+1: +PyLong_FromVoidPtr:void*:p:: + +PyMapping_Check:int::: +PyMapping_Check:PyObject*:o:0: + +PyMapping_DelItem:int::: +PyMapping_DelItem:PyObject*:o:0: +PyMapping_DelItem:PyObject*:key:0: + +PyMapping_DelItemString:int::: +PyMapping_DelItemString:PyObject*:o:0: +PyMapping_DelItemString:const char*:key:: + +PyMapping_GetItemString:PyObject*::+1: +PyMapping_GetItemString:PyObject*:o:0: +PyMapping_GetItemString:const char*:key:: + +PyMapping_HasKey:int::: +PyMapping_HasKey:PyObject*:o:0: +PyMapping_HasKey:PyObject*:key:: + +PyMapping_HasKeyString:int::: +PyMapping_HasKeyString:PyObject*:o:0: +PyMapping_HasKeyString:const char*:key:: + +PyMapping_Items:PyObject*::+1: +PyMapping_Items:PyObject*:o:0: + +PyMapping_Keys:PyObject*::+1: +PyMapping_Keys:PyObject*:o:0: + +PyMapping_Length:Py_ssize_t::: +PyMapping_Length:PyObject*:o:0: + +PyMapping_SetItemString:int::: +PyMapping_SetItemString:PyObject*:o:0: +PyMapping_SetItemString:const char*:key:: +PyMapping_SetItemString:PyObject*:v:+1: + +PyMapping_Size:Py_ssize_t::: +PyMapping_Size:PyObject*:o:0: + +PyMapping_Values:PyObject*::+1: +PyMapping_Values:PyObject*:o:0: + +PyMarshal_ReadLastObjectFromFile:PyObject*::+1: +PyMarshal_ReadLastObjectFromFile:FILE*:file:: + +PyMarshal_ReadObjectFromFile:PyObject*::+1: +PyMarshal_ReadObjectFromFile:FILE*:file:: + +PyMarshal_ReadObjectFromString:PyObject*::+1: +PyMarshal_ReadObjectFromString:const char*:string:: +PyMarshal_ReadObjectFromString:Py_ssize_t:len:: + +PyMarshal_WriteObjectToString:PyObject*::+1: +PyMarshal_WriteObjectToString:PyObject*:value:0: +PyMarshal_WriteObjectToString:int:version:: + +PyMemoryView_Check:int::: +PyMemoryView_Check:PyObject*:obj:0: + +PyMemoryView_FromBuffer:PyObject*::+1: +PyMemoryView_FromBuffer:Py_buffer*:view:: + +PyMemoryView_FromMemory:PyObject*::+1: +PyMemoryView_FromMemory:char*:mem:: +PyMemoryView_FromMemory:Py_ssize_t:size:: +PyMemoryView_FromMemory:int:flags:: + +PyMemoryView_FromObject:PyObject*::+1: +PyMemoryView_FromObject:PyObject*:obj:0: + +PyMemoryView_GET_BASE:Py_buffer*::: +PyMemoryView_GET_BASE:PyObject*:mview:0: + +PyMemoryView_GET_BUFFER:Py_buffer*::: +PyMemoryView_GET_BUFFER:PyObject*:mview:0: + +PyMemoryView_GetContiguous:PyObject*::+1: +PyMemoryView_GetContiguous:PyObject*:obj:0: +PyMemoryView_GetContiguous:int:buffertype:: +PyMemoryView_GetContiguous:char:order:: + +PyMethod_Check:int::: +PyMethod_Check:PyObject*:o:0: + +PyMethod_Function:PyObject*::0: +PyMethod_Function:PyObject*:im:0: + +PyMethod_GET_FUNCTION:PyObject*::0: +PyMethod_GET_FUNCTION:PyObject*:im:0: + +PyMethod_GET_SELF:PyObject*::0: +PyMethod_GET_SELF:PyObject*:im:0: + +PyMethod_New:PyObject*::+1: +PyMethod_New:PyObject*:func:0: +PyMethod_New:PyObject*:self:0: +PyMethod_New:PyObject*:class:0: + +PyMethod_Self:PyObject*::0: +PyMethod_Self:PyObject*:im:0: + +PyModule_AddFunctions:int::: +PyModule_AddFunctions:PyObject*:module:0: +PyModule_AddFunctions:PyMethodDef*:functions:: + +PyModule_AddIntConstant:int::: +PyModule_AddIntConstant:PyObject*:module:0: +PyModule_AddIntConstant:const char*:name:: +PyModule_AddIntConstant:long:value:: + +PyModule_AddIntMacro:int::: +PyModule_AddIntMacro:PyObject*:module:0: +PyModule_AddIntMacro::macro:: + +PyModule_AddObject:int::: +PyModule_AddObject:PyObject*:module:0: +PyModule_AddObject:const char*:name:: +PyModule_AddObject:PyObject*:value:+1: + +PyModule_AddStringConstant:int::: +PyModule_AddStringConstant:PyObject*:module:0: +PyModule_AddStringConstant:const char*:name:: +PyModule_AddStringConstant:const char*:value:: + +PyModule_AddStringMacro:int::: +PyModule_AddStringMacro:PyObject*:module:0: +PyModule_AddStringMacro::macro:: + +PyModule_Check:int::: +PyModule_Check:PyObject*:p:0: + +PyModule_CheckExact:int::: +PyModule_CheckExact:PyObject*:p:0: + +PyModule_Create:PyObject*::+1: +PyModule_Create:PyModuleDef*:def:: + +PyModule_Create2:PyObject*::+1: +PyModule_Create2:PyModuleDef*:def:: +PyModule_Create2:int:module_api_version:: + +PyModule_ExecDef:int::: +PyModule_ExecDef:PyObject*:module:0: +PyModule_ExecDef:PyModuleDef*:def:: + +PyModule_FromDefAndSpec:PyObject*::+1: +PyModule_FromDefAndSpec:PyModuleDef*:def:: +PyModule_FromDefAndSpec:PyObject*:spec:0: + +PyModule_FromDefAndSpec2:PyObject*::+1: +PyModule_FromDefAndSpec2:PyModuleDef*:def:: +PyModule_FromDefAndSpec2:PyObject*:spec:0: +PyModule_FromDefAndSpec2:int:module_api_version:: + +PyModule_GetDef:PyModuleDef*::0: +PyModule_GetDef:PyObject*:module:0: + +PyModule_GetDict:PyObject*::0: +PyModule_GetDict:PyObject*:module:0: + +PyModule_GetFilename:const char*::: +PyModule_GetFilename:PyObject*:module:0: + +PyModule_GetFilenameObject:PyObject*::+1: +PyModule_GetFilenameObject:PyObject*:module:0: + +PyModule_GetName:const char*::: +PyModule_GetName:PyObject*:module:0: + +PyModule_GetNameObject:PyObject*::+1: +PyModule_GetNameObject:PyObject*:module:0: + +PyModule_GetState:void*::: +PyModule_GetState:PyObject*:module:0: + +PyModule_New:PyObject*::+1: +PyModule_New::char* name:: + +PyModule_NewObject:PyObject*::+1: +PyModule_NewObject:PyObject*:name:+1: + +PyModule_SetDocString:int::: +PyModule_SetDocString:PyObject*:module:0: +PyModule_SetDocString:const char*:docstring:: + +PyModuleDef_Init:PyObject*::0: +PyModuleDef_Init:PyModuleDef*:def:0: + +PyNumber_Absolute:PyObject*::+1: +PyNumber_Absolute:PyObject*:o:0: + +PyNumber_Add:PyObject*::+1: +PyNumber_Add:PyObject*:o1:0: +PyNumber_Add:PyObject*:o2:0: + +PyNumber_And:PyObject*::+1: +PyNumber_And:PyObject*:o1:0: +PyNumber_And:PyObject*:o2:0: + +PyNumber_AsSsize_t:Py_ssize_t::: +PyNumber_AsSsize_t:PyObject*:o:0: +PyNumber_AsSsize_t:PyObject*:exc:0: + +PyNumber_Check:int::: +PyNumber_Check:PyObject*:o:0: + +PyNumber_Divmod:PyObject*::+1: +PyNumber_Divmod:PyObject*:o1:0: +PyNumber_Divmod:PyObject*:o2:0: + +PyNumber_Float:PyObject*::+1: +PyNumber_Float:PyObject*:o:0: + +PyNumber_FloorDivide:PyObject*::+1: +PyNumber_FloorDivide:PyObject*:v:0: +PyNumber_FloorDivide:PyObject*:w:0: + +PyNumber_Index:PyObject*::+1: +PyNumber_Index:PyObject*:o:0: + +PyNumber_InPlaceAdd:PyObject*::+1: +PyNumber_InPlaceAdd:PyObject*:v:0: +PyNumber_InPlaceAdd:PyObject*:w:0: + +PyNumber_InPlaceAnd:PyObject*::+1: +PyNumber_InPlaceAnd:PyObject*:v:0: +PyNumber_InPlaceAnd:PyObject*:w:0: + +PyNumber_InPlaceFloorDivide:PyObject*::+1: +PyNumber_InPlaceFloorDivide:PyObject*:v:0: +PyNumber_InPlaceFloorDivide:PyObject*:w:0: + +PyNumber_InPlaceLshift:PyObject*::+1: +PyNumber_InPlaceLshift:PyObject*:v:0: +PyNumber_InPlaceLshift:PyObject*:w:0: + +PyNumber_InPlaceMatrixMultiply:PyObject*::+1: +PyNumber_InPlaceMatrixMultiply:PyObject*:o1:0: +PyNumber_InPlaceMatrixMultiply:PyObject*:o2:0: + +PyNumber_InPlaceMultiply:PyObject*::+1: +PyNumber_InPlaceMultiply:PyObject*:v:0: +PyNumber_InPlaceMultiply:PyObject*:w:0: + +PyNumber_InPlaceOr:PyObject*::+1: +PyNumber_InPlaceOr:PyObject*:v:0: +PyNumber_InPlaceOr:PyObject*:w:0: + +PyNumber_InPlacePower:PyObject*::+1: +PyNumber_InPlacePower:PyObject*:v:0: +PyNumber_InPlacePower:PyObject*:w:0: +PyNumber_InPlacePower:PyObject*:z:0: + +PyNumber_InPlaceRemainder:PyObject*::+1: +PyNumber_InPlaceRemainder:PyObject*:v:0: +PyNumber_InPlaceRemainder:PyObject*:w:0: + +PyNumber_InPlaceRshift:PyObject*::+1: +PyNumber_InPlaceRshift:PyObject*:v:0: +PyNumber_InPlaceRshift:PyObject*:w:0: + +PyNumber_InPlaceSubtract:PyObject*::+1: +PyNumber_InPlaceSubtract:PyObject*:v:0: +PyNumber_InPlaceSubtract:PyObject*:w:0: + +PyNumber_InPlaceTrueDivide:PyObject*::+1: +PyNumber_InPlaceTrueDivide:PyObject*:v:0: +PyNumber_InPlaceTrueDivide:PyObject*:w:0: + +PyNumber_InPlaceXor:PyObject*::+1: +PyNumber_InPlaceXor:PyObject*:v:0: +PyNumber_InPlaceXor:PyObject*:w:0: + +PyNumber_Invert:PyObject*::+1: +PyNumber_Invert:PyObject*:o:0: + +PyNumber_Long:PyObject*::+1: +PyNumber_Long:PyObject*:o:0: + +PyNumber_Lshift:PyObject*::+1: +PyNumber_Lshift:PyObject*:o1:0: +PyNumber_Lshift:PyObject*:o2:0: + +PyNumber_MatrixMultiply:PyObject*::+1: +PyNumber_MatrixMultiply:PyObject*:o1:0: +PyNumber_MatrixMultiply:PyObject*:o2:0: + +PyNumber_Multiply:PyObject*::+1: +PyNumber_Multiply:PyObject*:o1:0: +PyNumber_Multiply:PyObject*:o2:0: + +PyNumber_Negative:PyObject*::+1: +PyNumber_Negative:PyObject*:o:0: + +PyNumber_Or:PyObject*::+1: +PyNumber_Or:PyObject*:o1:0: +PyNumber_Or:PyObject*:o2:0: + +PyNumber_Positive:PyObject*::+1: +PyNumber_Positive:PyObject*:o:0: + +PyNumber_Power:PyObject*::+1: +PyNumber_Power:PyObject*:o1:0: +PyNumber_Power:PyObject*:o2:0: +PyNumber_Power:PyObject*:o3:0: + +PyNumber_Remainder:PyObject*::+1: +PyNumber_Remainder:PyObject*:o1:0: +PyNumber_Remainder:PyObject*:o2:0: + +PyNumber_Rshift:PyObject*::+1: +PyNumber_Rshift:PyObject*:o1:0: +PyNumber_Rshift:PyObject*:o2:0: + +PyNumber_Subtract:PyObject*::+1: +PyNumber_Subtract:PyObject*:o1:0: +PyNumber_Subtract:PyObject*:o2:0: + +PyNumber_ToBase:PyObject*::+1: +PyNumber_ToBase:PyObject*:n:0: +PyNumber_ToBase:int:base:: + +PyNumber_TrueDivide:PyObject*::+1: +PyNumber_TrueDivide:PyObject*:v:0: +PyNumber_TrueDivide:PyObject*:w:0: + +PyNumber_Xor:PyObject*::+1: +PyNumber_Xor:PyObject*:o1:0: +PyNumber_Xor:PyObject*:o2:0: + +PyObject_AsFileDescriptor:int::: +PyObject_AsFileDescriptor:PyObject*:o:0: + +PyOS_AfterFork:void::: + +PyOS_AfterFork_Child:void::: + +PyOS_AfterFork_Parent:void::: + +PyOS_BeforeFork:void::: + +PyOS_FSPath:PyObject*::+1: +PyOS_FSPath:PyObject*:path:0: + +PyObject_ASCII:PyObject*::+1: +PyObject_ASCII:PyObject*:o:0: + +PyObject_AsCharBuffer:int::: +PyObject_AsCharBuffer:PyObject*:obj:0: +PyObject_AsCharBuffer:const char**:buffer:: +PyObject_AsCharBuffer:Py_ssize_t*:buffer_len:: + +PyObject_AsReadBuffer:int::: +PyObject_AsReadBuffer:PyObject*:obj:0: +PyObject_AsReadBuffer:const void**:buffer:: +PyObject_AsReadBuffer:Py_ssize_t*:buffer_len:: + +PyObject_AsWriteBuffer:int::: +PyObject_AsWriteBuffer:PyObject*:obj:0: +PyObject_AsWriteBuffer:void**:buffer:: +PyObject_AsWriteBuffer:Py_ssize_t*:buffer_len:: + +PyObject_Bytes:PyObject*::+1: +PyObject_Bytes:PyObject*:o:0: + +PyObject_Call:PyObject*::+1: +PyObject_Call:PyObject*:callable_object:0: +PyObject_Call:PyObject*:args:0: +PyObject_Call:PyObject*:kw:0: + +PyObject_CallFunction:PyObject*::+1: +PyObject_CallFunction:PyObject*:callable_object:0: +PyObject_CallFunction:const char*:format:: +PyObject_CallFunction::...:: + +PyObject_CallFunctionObjArgs:PyObject*::+1: +PyObject_CallFunctionObjArgs:PyObject*:callable:0: +PyObject_CallFunctionObjArgs::...:: + +PyObject_CallMethod:PyObject*::+1: +PyObject_CallMethod:PyObject*:o:0: +PyObject_CallMethod:const char*:m:: +PyObject_CallMethod:const char*:format:: +PyObject_CallMethod::...:: + +PyObject_CallMethodObjArgs:PyObject*::+1: +PyObject_CallMethodObjArgs:PyObject*:o:0: +PyObject_CallMethodObjArgs:PyObject*:name:0: +PyObject_CallMethodObjArgs::...:: + +PyObject_CallObject:PyObject*::+1: +PyObject_CallObject:PyObject*:callable_object:0: +PyObject_CallObject:PyObject*:args:0: + +PyObject_CheckBuffer:int::: +PyObject_CheckBuffer:PyObject*:obj:0: + +PyObject_CheckReadBuffer:int::: +PyObject_CheckReadBuffer:PyObject*:o:0: + +PyObject_DelAttr:int::: +PyObject_DelAttr:PyObject*:o:0: +PyObject_DelAttr:PyObject*:attr_name:0: + +PyObject_DelAttrString:int::: +PyObject_DelAttrString:PyObject*:o:0: +PyObject_DelAttrString:const char*:attr_name:: + +PyObject_DelItem:int::: +PyObject_DelItem:PyObject*:o:0: +PyObject_DelItem:PyObject*:key:0: + +PyObject_Dir:PyObject*::+1: +PyObject_Dir:PyObject*:o:0: + +PyObject_GC_Del:void::: +PyObject_GC_Del:void*:op:: + +PyObject_GC_New:TYPE*::+1: +PyObject_GC_New::TYPE:: +PyObject_GC_New:PyTypeObject*:type:0: + +PyObject_GC_NewVar:TYPE*::+1: +PyObject_GC_NewVar::TYPE:: +PyObject_GC_NewVar:PyTypeObject*:type:0: +PyObject_GC_NewVar:Py_ssize_t:size:: + +PyObject_GC_Resize:TYPE*::0: +PyObject_GC_Resize::TYPE:: +PyObject_GC_Resize:PyVarObject*:op:0: +PyObject_GC_Resize:Py_ssize_t:newsize:: + +PyObject_GC_Track:void::: +PyObject_GC_Track:PyObject*:op:0: + +PyObject_GC_UnTrack:void::: +PyObject_GC_UnTrack:void*:op:: + +PyObject_GenericGetAttr:PyObject*::+1: +PyObject_GenericGetAttr:PyObject*:o:0: +PyObject_GenericGetAttr:PyObject*:name:0: + +PyObject_GenericGetDict:PyObject*::+1: +PyObject_GenericGetDict:PyObject*:o:0: +PyObject_GenericGetDict:void*:context:: + +PyObject_GenericSetAttr:int::: +PyObject_GenericSetAttr:PyObject*:o:0: +PyObject_GenericSetAttr:PyObject*:name:0: +PyObject_GenericSetAttr:PyObject*:value:+1: + +PyObject_GenericSetDict:int::: +PyObject_GenericSetDict:PyObject*:o:0: +PyObject_GenericSetDict:PyObject*:value:+1: +PyObject_GenericSetDict:void*:context:: + +PyObject_GetAttr:PyObject*::+1: +PyObject_GetAttr:PyObject*:o:0: +PyObject_GetAttr:PyObject*:attr_name:0: + +PyObject_GetAttrString:PyObject*::+1: +PyObject_GetAttrString:PyObject*:o:0: +PyObject_GetAttrString:const char*:attr_name:: + +PyObject_GetBuffer:int::: +PyObject_GetBuffer:PyObject*:exporter:0: +PyObject_GetBuffer:Py_buffer*:view:: +PyObject_GetBuffer:int:flags:: + +PyObject_GetItem:PyObject*::+1: +PyObject_GetItem:PyObject*:o:0: +PyObject_GetItem:PyObject*:key:0: + +PyObject_GetIter:PyObject*::+1: +PyObject_GetIter:PyObject*:o:0: + +PyObject_HasAttr:int::: +PyObject_HasAttr:PyObject*:o:0: +PyObject_HasAttr:PyObject*:attr_name:0: + +PyObject_HasAttrString:int::: +PyObject_HasAttrString:PyObject*:o:0: +PyObject_HasAttrString:const char*:attr_name:: + +PyObject_Hash:int::: +PyObject_Hash:PyObject*:o:0: + +PyObject_HashNotImplemented:Py_hash_t::: +PyObject_HashNotImplemented:PyObject*:o:0: + +PyObject_IsInstance:int::: +PyObject_IsInstance:PyObject*:inst:0: +PyObject_IsInstance:PyObject*:cls:0: + +PyObject_IsSubclass:int::: +PyObject_IsSubclass:PyObject*:derived:0: +PyObject_IsSubclass:PyObject*:cls:0: + +PyObject_IsTrue:int::: +PyObject_IsTrue:PyObject*:o:0: + +PyObject_Init:PyObject*::0: +PyObject_Init:PyObject*:op:0: +PyObject_Init:PyTypeObject*:type:0: + +PyObject_InitVar:PyVarObject*::0: +PyObject_InitVar:PyVarObject*:op:0: + +PyObject_Length:Py_ssize_t::: +PyObject_Length:PyObject*:o:0: + +PyObject_LengthHint:Py_ssize_t::: +PyObject_LengthHint:PyObject*:o:0: +PyObject_LengthHint:Py_ssize_t:default:: + +PyObject_NEW:PyObject*::+1: +PyObject_NEW::TYPE:: +PyObject_NEW:PyTypeObject*:type:0: + +PyObject_New:PyObject*::+1: +PyObject_New::TYPE:: +PyObject_New:PyTypeObject*:type:0: + +PyObject_NEW_VAR:PyObject*::+1: +PyObject_NEW_VAR::TYPE:: +PyObject_NEW_VAR:PyTypeObject*:type:0: +PyObject_NEW_VAR:Py_ssize_t:size:: + +PyObject_NewVar:PyObject*::+1: +PyObject_NewVar::TYPE:: +PyObject_NewVar:PyTypeObject*:type:0: +PyObject_NewVar:Py_ssize_t:size:: + +PyObject_Not:int::: +PyObject_Not:PyObject*:o:0: + +PyObject_Print:int::: +PyObject_Print:PyObject*:o:0: +PyObject_Print:FILE*:fp:: +PyObject_Print:int:flags:: + +PyObject_Repr:PyObject*::+1: +PyObject_Repr:PyObject*:o:0: + +PyObject_RichCompare:PyObject*::+1: +PyObject_RichCompare:PyObject*:o1:0: +PyObject_RichCompare:PyObject*:o2:0: +PyObject_RichCompare:int:opid:: + +PyObject_RichCompareBool:int::: +PyObject_RichCompareBool:PyObject*:o1:0: +PyObject_RichCompareBool:PyObject*:o2:0: +PyObject_RichCompareBool:int:opid:: + +PyObject_SetAttr:int::: +PyObject_SetAttr:PyObject*:o:0: +PyObject_SetAttr:PyObject*:attr_name:0: +PyObject_SetAttr:PyObject*:v:+1: + +PyObject_SetAttrString:int::: +PyObject_SetAttrString:PyObject*:o:0: +PyObject_SetAttrString:const char*:attr_name:: +PyObject_SetAttrString:PyObject*:v:+1: + +PyObject_SetItem:int::: +PyObject_SetItem:PyObject*:o:0: +PyObject_SetItem:PyObject*:key:0: +PyObject_SetItem:PyObject*:v:+1: + +PyObject_Size:Py_ssize_t::: +PyObject_Size:PyObject*:o:0: + +PyObject_Str:PyObject*::+1: +PyObject_Str:PyObject*:o:0: + +PyObject_Type:PyObject*::+1: +PyObject_Type:PyObject*:o:0: + +PyObject_TypeCheck:int::: +PyObject_TypeCheck:PyObject*:o:0: +PyObject_TypeCheck:PyTypeObject*:type:0: + +PyParser_SimpleParseFile:struct _node*::: +PyParser_SimpleParseFile:FILE*:fp:: +PyParser_SimpleParseFile:const char*:filename:: +PyParser_SimpleParseFile:int:start:: + +PyParser_SimpleParseFileFlags:struct _node*::: +PyParser_SimpleParseFileFlags:FILE*:fp:: +PyParser_SimpleParseFileFlags:const char*:filename:: +PyParser_SimpleParseFileFlags:int:start:: +PyParser_SimpleParseFileFlags:int:flags:: + +PyParser_SimpleParseString:struct _node*::: +PyParser_SimpleParseString:const char*:str:: +PyParser_SimpleParseString:int:start:: + +PyParser_SimpleParseStringFlags:struct _node*::: +PyParser_SimpleParseStringFlags:const char*:str:: +PyParser_SimpleParseStringFlags:int:start:: +PyParser_SimpleParseStringFlags:int:flags:: + +PyParser_SimpleParseStringFlagsFilename:struct _node*::: +PyParser_SimpleParseStringFlagsFilename:const char*:str:: +PyParser_SimpleParseStringFlagsFilename:const char*:filename:: +PyParser_SimpleParseStringFlagsFilename:int:start:: +PyParser_SimpleParseStringFlagsFilename:int:flags:: + +PyRun_AnyFile:int::: +PyRun_AnyFile:FILE*:fp:: +PyRun_AnyFile:const char*:filename:: + +PyRun_AnyFileFlags:int::: +PyRun_AnyFileFlags:FILE*:fp:: +PyRun_AnyFileFlags:const char*:filename:: +PyRun_AnyFileFlags:PyCompilerFlags*:flags:: + +PyRun_AnyFileEx:int::: +PyRun_AnyFileEx:FILE*:fp:: +PyRun_AnyFileEx:const char*:filename:: +PyRun_AnyFileEx:int:closeit:: + +PyRun_AnyFileExFlags:int::: +PyRun_AnyFileExFlags:FILE*:fp:: +PyRun_AnyFileExFlags:const char*:filename:: +PyRun_AnyFileExFlags:int:closeit:: +PyRun_AnyFileExFlags:PyCompilerFlags*:flags:: + +PyRun_File:PyObject*::+1:??? -- same as eval_code2() +PyRun_File:FILE*:fp:: +PyRun_File:const char*:filename:: +PyRun_File:int:start:: +PyRun_File:PyObject*:globals:0: +PyRun_File:PyObject*:locals:0: + +PyRun_FileEx:PyObject*::+1:??? -- same as eval_code2() +PyRun_FileEx:FILE*:fp:: +PyRun_FileEx:const char*:filename:: +PyRun_FileEx:int:start:: +PyRun_FileEx:PyObject*:globals:0: +PyRun_FileEx:PyObject*:locals:0: +PyRun_FileEx:int:closeit:: + +PyRun_FileFlags:PyObject*::+1:??? -- same as eval_code2() +PyRun_FileFlags:FILE*:fp:: +PyRun_FileFlags:const char*:filename:: +PyRun_FileFlags:int:start:: +PyRun_FileFlags:PyObject*:globals:0: +PyRun_FileFlags:PyObject*:locals:0: +PyRun_FileFlags:PyCompilerFlags*:flags:: + +PyRun_FileExFlags:PyObject*::+1:??? -- same as eval_code2() +PyRun_FileExFlags:FILE*:fp:: +PyRun_FileExFlags:const char*:filename:: +PyRun_FileExFlags:int:start:: +PyRun_FileExFlags:PyObject*:globals:0: +PyRun_FileExFlags:PyObject*:locals:0: +PyRun_FileExFlags:int:closeit:: +PyRun_FileExFlags:PyCompilerFlags*:flags:: + +PyRun_InteractiveLoop:int::: +PyRun_InteractiveLoop:FILE*:fp:: +PyRun_InteractiveLoop:const char*:filename:: + +PyRun_InteractiveLoopFlags:int::: +PyRun_InteractiveLoopFlags:FILE*:fp:: +PyRun_InteractiveLoopFlags:const char*:filename:: +PyRun_InteractiveLoopFlags:PyCompilerFlags*:flags:: + +PyRun_InteractiveOne:int::: +PyRun_InteractiveOne:FILE*:fp:: +PyRun_InteractiveOne:const char*:filename:: + +PyRun_InteractiveOneFlags:int::: +PyRun_InteractiveOneFlags:FILE*:fp:: +PyRun_InteractiveOneFlags:const char*:filename:: +PyRun_InteractiveOneFlags:PyCompilerFlags*:flags:: + +PyRun_SimpleFile:int::: +PyRun_SimpleFile:FILE*:fp:: +PyRun_SimpleFile:const char*:filename:: + +PyRun_SimpleFileEx:int::: +PyRun_SimpleFileEx:FILE*:fp:: +PyRun_SimpleFileEx:const char*:filename:: +PyRun_SimpleFileEx:int:closeit:: + +PyRun_SimpleFileExFlags:int::: +PyRun_SimpleFileExFlags:FILE*:fp:: +PyRun_SimpleFileExFlags:const char*:filename:: +PyRun_SimpleFileExFlags:int:closeit:: +PyRun_SimpleFileExFlags:PyCompilerFlags*:flags:: + +PyRun_SimpleString:int::: +PyRun_SimpleString:const char*:command:: + +PyRun_SimpleStringFlags:int::: +PyRun_SimpleStringFlags:const char*:command:: +PyRun_SimpleStringFlags:PyCompilerFlags*:flags:: + +PyRun_String:PyObject*::+1:??? -- same as eval_code2() +PyRun_String:const char*:str:: +PyRun_String:int:start:: +PyRun_String:PyObject*:globals:0: +PyRun_String:PyObject*:locals:0: + +PyRun_StringFlags:PyObject*::+1:??? -- same as eval_code2() +PyRun_StringFlags:const char*:str:: +PyRun_StringFlags:int:start:: +PyRun_StringFlags:PyObject*:globals:0: +PyRun_StringFlags:PyObject*:locals:0: +PyRun_StringFlags:PyCompilerFlags*:flags:: + +PySeqIter_Check:int::: +PySeqIter_Check::op:: + +PySeqIter_New:PyObject*::+1: +PySeqIter_New:PyObject*:seq:: + +PySequence_Check:int::: +PySequence_Check:PyObject*:o:0: + +PySequence_Concat:PyObject*::+1: +PySequence_Concat:PyObject*:o1:0: +PySequence_Concat:PyObject*:o2:0: + +PySequence_Contains:int::: +PySequence_Contains:PyObject*:o:0: +PySequence_Contains:PyObject*:value:0: + +PySequence_Count:Py_ssize_t::: +PySequence_Count:PyObject*:o:0: +PySequence_Count:PyObject*:value:0: + +PySequence_DelItem:int::: +PySequence_DelItem:PyObject*:o:0: +PySequence_DelItem:Py_ssize_t:i:: + +PySequence_DelSlice:int::: +PySequence_DelSlice:PyObject*:o:0: +PySequence_DelSlice:Py_ssize_t:i1:: +PySequence_DelSlice:Py_ssize_t:i2:: + +PySequence_Fast:PyObject*::+1: +PySequence_Fast:PyObject*:v:0: +PySequence_Fast:const char*:m:: + +PySequence_Fast_GET_ITEM:PyObject*::0: +PySequence_Fast_GET_ITEM:PyObject*:o:0: +PySequence_Fast_GET_ITEM:Py_ssize_t:i:: + +PySequence_Fast_GET_SIZE:Py_ssize_t::: +PySequence_Fast_GET_SIZE:PyObject*:o:0: + +PySequence_Fast_ITEMS:PyObject**::: +PySequence_Fast_ITEMS:PyObject*:o:0: + +PySequence_GetItem:PyObject*::+1: +PySequence_GetItem:PyObject*:o:0: +PySequence_GetItem:Py_ssize_t:i:: + +PySequence_GetSlice:PyObject*::+1: +PySequence_GetSlice:PyObject*:o:0: +PySequence_GetSlice:Py_ssize_t:i1:: +PySequence_GetSlice:Py_ssize_t:i2:: + +PySequence_In:int::: +PySequence_In:PyObject*:o:0: +PySequence_In:PyObject*:value:0: + +PySequence_Index:Py_ssize_t::: +PySequence_Index:PyObject*:o:0: +PySequence_Index:PyObject*:value:0: + +PySequence_InPlaceConcat:PyObject*::+1: +PySequence_InPlaceConcat:PyObject*:s:0: +PySequence_InPlaceConcat:PyObject*:o:0: + +PySequence_InPlaceRepeat:PyObject*::+1: +PySequence_InPlaceRepeat:PyObject*:s:0: +PySequence_InPlaceRepeat:PyObject*:o:0: + +PySequence_ITEM:PyObject*::+1: +PySequence_ITEM:PyObject*:o:0: +PySequence_ITEM:Py_ssize_t:i:: + +PySequence_Repeat:PyObject*::+1: +PySequence_Repeat:PyObject*:o:0: +PySequence_Repeat:Py_ssize_t:count:: + +PySequence_SetItem:int::: +PySequence_SetItem:PyObject*:o:0: +PySequence_SetItem:Py_ssize_t:i:: +PySequence_SetItem:PyObject*:v:+1: + +PySequence_SetSlice:int::: +PySequence_SetSlice:PyObject*:o:0: +PySequence_SetSlice:Py_ssize_t:i1:: +PySequence_SetSlice:Py_ssize_t:i2:: +PySequence_SetSlice:PyObject*:v:0: + +PySequence_Size:Py_ssize_t::: +PySequence_Size:PyObject*:o:0: + +PySequence_List:PyObject*::+1: +PySequence_List:PyObject*:o:0: + +PySequence_Tuple:PyObject*::+1: +PySequence_Tuple:PyObject*:o:0: + +PySet_Add:int::: +PySet_Add:PyObject*:set:0: +PySet_Add:PyObject*:key:+1: + +PySet_Check:int::: +PySet_Check:PyObject*:p:0: + +PySet_Clear:int::: +PySet_Clear:PyObject*:set:0: + +PySet_Contains:int::: +PySet_Contains:PyObject*:anyset:0: +PySet_Contains:PyObject*:key:0: + +PySet_Discard:int::: +PySet_Discard:PyObject*:set:0: +PySet_Discard:PyObject*:key:-1:no effect if key not found + +PySet_GET_SIZE:Py_ssize_t::: +PySet_GET_SIZE:PyObject*:anyset:0: + +PySet_New:PyObject*::+1: +PySet_New:PyObject*:iterable:0: + +PySet_Pop:PyObject*::+1:or returns NULL and raises KeyError if set is empty +PySet_Pop:PyObject*:set:0: + +PySet_Size:Py_ssize_t::: +PySet_Size:PyObject*:anyset:0: + +PySignal_SetWakeupFd:int::: +PySignal_SetWakeupFd:int:fd:: + +PySlice_AdjustIndices:Py_ssize_t::: +PySlice_AdjustIndices:Py_ssize_t:length:: +PySlice_AdjustIndices:Py_ssize_t*:start:: +PySlice_AdjustIndices:Py_ssize_t*:stop:: +PySlice_AdjustIndices:Py_ssize_t*:step:: + +PySlice_Check:int::: +PySlice_Check:PyObject*:ob:0: + +PySlice_GetIndices:int::: +PySlice_GetIndices:PyObject*:slice:0: +PySlice_GetIndices:Py_ssize_t:length:: +PySlice_GetIndices:Py_ssize_t*:start:: +PySlice_GetIndices:Py_ssize_t*:stop:: +PySlice_GetIndices:Py_ssize_t*:step:: + +PySlice_GetIndicesEx:int::: +PySlice_GetIndicesEx:PyObject*:slice:0: +PySlice_GetIndicesEx:Py_ssize_t:length:: +PySlice_GetIndicesEx:Py_ssize_t*:start:: +PySlice_GetIndicesEx:Py_ssize_t*:stop:: +PySlice_GetIndicesEx:Py_ssize_t*:step:: +PySlice_GetIndicesEx:Py_ssize_t*:slicelength:: + +PySlice_New:PyObject*::+1: +PySlice_New:PyObject*:start:0: +PySlice_New:PyObject*:stop:0: +PySlice_New:PyObject*:step:0: + +PySlice_Unpack:int::: +PySlice_Unpack:PyObject*:slice:0: +PySlice_Unpack:Py_ssize_t*:start:: +PySlice_Unpack:Py_ssize_t*:stop:: +PySlice_Unpack:Py_ssize_t*:step:: + +PyState_AddModule:int::: +PyState_AddModule:PyObject*:module:+1: +PyState_AddModule:PyModuleDef*:def:: + +PyState_FindModule:PyObject*::0: +PyState_FindModule:PyModuleDef*:def:: + +PyState_RemoveModule:int::: +PyState_RemoveModule:PyModuleDef*:def:: + +PyStructSequence_GET_ITEM:PyObject*::0: +PyStructSequence_GET_ITEM:PyObject*:p:0: +PyStructSequence_GET_ITEM:Py_ssize_t:pos:: + +PyStructSequence_GetItem:PyObject*::0: +PyStructSequence_GetItem:PyObject*:p:0: +PyStructSequence_GetItem:Py_ssize_t:pos:: + +PyStructSequence_InitType:void::: +PyStructSequence_InitType:PyTypeObject*:type:+1: +PyStructSequence_InitType:PyStructSequence_Desc*:desc:: + +PyStructSequence_InitType2:int::: +PyStructSequence_InitType2:PyTypeObject*:type:+1: +PyStructSequence_InitType2:PyStructSequence_Desc*:desc:: + +PyStructSequence_New:PyObject*::+1: +PyStructSequence_New:PyTypeObject*:type:0: + +PyStructSequence_NewType:PyTypeObject*::+1: +PyStructSequence_NewType:PyStructSequence_Desc*:desc:: + +PyStructSequence_SET_ITEM:void::: +PyStructSequence_SET_ITEM:PyObject*:p:0: +PyStructSequence_SET_ITEM:Py_ssize_t*:pos:: +PyStructSequence_SET_ITEM:PyObject*:o:0: + +PyStructSequence_SetItem:void::: +PyStructSequence_SetItem:PyObject*:p:0: +PyStructSequence_SetItem:Py_ssize_t:pos:: +PyStructSequence_SetItem:PyObject*:o:0: + +PySys_AddWarnOption:void::: +PySys_AddWarnOption:const wchar_t*:s:: + +PySys_AddWarnOptionUnicode:void::: +PySys_AddWarnOptionUnicode:PyObject*:unicode:0: + +PySys_AddXOption:void::: +PySys_AddXOption:const wchar_t*:s:: + +PySys_FormatStderr:void::: +PySys_FormatStderr:const char*:format:: +PySys_FormatStderr::...:: + +PySys_FormatStdout:void::: +PySys_FormatStdout:const char*:format:: +PySys_FormatStdout::...:: + +PySys_GetObject:PyObject*::0: +PySys_GetObject:const char*:name:: + +PySys_GetXOptions:PyObject*::0: + +PySys_SetArgv:void::: +PySys_SetArgv:int:argc:: +PySys_SetArgv:wchar_t**:argv:: + +PySys_SetArgvEx:void::: +PySys_SetArgvEx:int:argc:: +PySys_SetArgvEx:wchar_t**:argv:: +PySys_SetArgvEx:int:updatepath:: + +PySys_SetObject:int::: +PySys_SetObject:const char*:name:: +PySys_SetObject:PyObject*:v:+1: + +PySys_ResetWarnOptions:void::: + +PySys_WriteStdout:void::: +PySys_WriteStdout:const char*:format:: +PySys_WriteStdout::...:: + +PySys_WriteStderr:void::: +PySys_WriteStderr:const char*:format:: +PySys_WriteStderr::...:: + +PyThreadState_Clear:void::: +PyThreadState_Clear:PyThreadState*:tstate:: + +PyThreadState_Delete:void::: +PyThreadState_Delete:PyThreadState*:tstate:: + +PyThreadState_Get:PyThreadState*::: + +PyThreadState_GetDict:PyObject*::0: + +PyThreadState_New:PyThreadState*::: +PyThreadState_New:PyInterpreterState*:interp:: + +PyThreadState_SetAsyncExc:int::: +PyThreadState_SetAsyncExc:unsigned long:id:: +PyThreadState_SetAsyncExc:PyObject*:exc:+1: + +PyThreadState_Swap:PyThreadState*::: +PyThreadState_Swap:PyThreadState*:tstate:: + +PyThread_tss_alloc:Py_tss_t*::: + +PyThread_tss_create:int::: +PyThread_tss_create:Py_tss_t*:key:: + +PyThread_tss_delete:void::: +PyThread_tss_delete:Py_tss_t*:key:: + +PyThread_tss_free:void::: +PyThread_tss_free:Py_tss_t*:key:: + +PyThread_tss_get:void*::: +PyThread_tss_get:Py_tss_t*:key:: + +PyThread_tss_is_created:int::: +PyThread_tss_is_created:Py_tss_t*:key:: + +PyThread_tss_set:int::: +PyThread_tss_set:Py_tss_t*:key:: +PyThread_tss_set:void*:value:: + +PyTime_Check:int::: +PyTime_Check:PyObject*:ob:0: + +PyTime_CheckExact:int::: +PyTime_CheckExact:PyObject*:ob:0: + +PyTime_FromTime:PyObject*::+1: +PyTime_FromTime:int:hour:: +PyTime_FromTime:int:minute:: +PyTime_FromTime:int:second:: +PyTime_FromTime:int:usecond:: + +PyTime_FromTimeAndFold:PyObject*::+1: +PyTime_FromTimeAndFold:int:hour:: +PyTime_FromTimeAndFold:int:minute:: +PyTime_FromTimeAndFold:int:second:: +PyTime_FromTimeAndFold:int:usecond:: +PyTime_FromTimeAndFold:int:fold:: + +PyTraceMalloc_Track:int::: +PyTraceMalloc_Track:unsigned int:domain:: +PyTraceMalloc_Track:uintptr_t:ptr:: +PyTraceMalloc_Track:size_t:size:: + +PyTraceMalloc_Untrack:int::: +PyTraceMalloc_Untrack:unsigned int:domain:: +PyTraceMalloc_Untrack:uintptr_t:ptr:: + +PyTuple_Check:int::: +PyTuple_Check:PyObject*:p:0: + +PyTuple_CheckExact:int::: +PyTuple_CheckExact:PyObject*:p:0: + +PyTuple_GET_ITEM:PyObject*::0: +PyTuple_GET_ITEM:PyObject*:p:0: +PyTuple_GET_ITEM:Py_ssize_t:pos:: + +PyTuple_GetItem:PyObject*::0: +PyTuple_GetItem:PyObject*:p:0: +PyTuple_GetItem:Py_ssize_t:pos:: + +PyTuple_GET_SIZE:Py_ssize_t::: +PyTuple_GET_SIZE:PyObject*:p:0: + +PyTuple_GetSlice:PyObject*::+1: +PyTuple_GetSlice:PyObject*:p:0: +PyTuple_GetSlice:Py_ssize_t:low:: +PyTuple_GetSlice:Py_ssize_t:high:: + +PyTuple_New:PyObject*::+1: +PyTuple_New:Py_ssize_t:len:: + +PyTuple_Pack:PyObject*::+1: +PyTuple_Pack:Py_ssize_t:len:: +PyTuple_Pack:PyObject*:...:0: + +PyTuple_SET_ITEM:void::: +PyTuple_SET_ITEM:PyObject*:p:0: +PyTuple_SET_ITEM:Py_ssize_t:pos:: +PyTuple_SET_ITEM:PyObject*:o:0: + +PyTuple_SetItem:int::: +PyTuple_SetItem:PyObject*:p:0: +PyTuple_SetItem:Py_ssize_t:pos:: +PyTuple_SetItem:PyObject*:o:0: + +PyTuple_Size:Py_ssize_t::: +PyTuple_Size:PyObject*:p:0: + +PyType_Check:int::: +PyType_Check:PyObject*:o:0: + +PyType_CheckExact:int::: +PyType_CheckExact:PyObject*:o:0: + +PyType_FromSpec:PyObject*::+1: +PyType_FromSpec:PyType_Spec*:spec:: + +PyType_FromSpecWithBases:PyObject*::+1: +PyType_FromSpecWithBases:PyType_Spec*:spec:: +PyType_FromSpecWithBases:PyObject*:bases:0: + +PyType_GenericAlloc:PyObject*::+1: +PyType_GenericAlloc:PyObject*:type:0: +PyType_GenericAlloc:Py_ssize_t:nitems:: + +PyType_GenericNew:PyObject*::+1: +PyType_GenericNew:PyObject*:type:0: +PyType_GenericNew:PyObject*:args:0: +PyType_GenericNew:PyObject*:kwds:0: + +PyType_GetFlags:unsigned long::: +PyType_GetFlags:PyTypeObject*:type:0: + +PyType_GetSlot:void*::: +PyType_GetSlot:PyTypeObject*:type:0: +PyType_GetSlot:int:slot:: + +PyType_HasFeature:int::: +PyType_HasFeature:PyTypeObject*:o:0: +PyType_HasFeature:int:feature:: + +PyType_IS_GC:int::: +PyType_IS_GC:PyTypeObject*:o:0: + +PyType_IsSubtype:int::: +PyType_IsSubtype:PyTypeObject*:a:0: +PyType_IsSubtype:PyTypeObject*:b:0: + +PyType_Modified:void::: +PyType_Modified:PyTypeObject*:type:0: + +PyType_Ready:int::: +PyType_Ready:PyTypeObject*:type:0: + +PyUnicode_1BYTE_DATA:Py_UCS1*::: +PyUnicode_1BYTE_DATA:PyObject*:o:0: + +PyUnicode_Check:int::: +PyUnicode_Check:PyObject*:o:0: + +PyUnicode_CheckExact:int::: +PyUnicode_CheckExact:PyObject*:o:0: + +PyUnicode_DATA:void*::: +PyUnicode_DATA:PyObject*:o:0: + +PyUnicode_GET_LENGTH:Py_ssize_t::: +PyUnicode_GET_LENGTH:PyObject*:o:0: + +PyUnicode_GET_SIZE:Py_ssize_t::: +PyUnicode_GET_SIZE:PyObject*:o:0: + +PyUnicode_GET_DATA_SIZE:Py_ssize_t::: +PyUnicode_GET_DATA_SIZE:PyObject*:o:0: + +PyUnicode_KIND:int::: +PyUnicode_KIND:PyObject*:o:0: + +PyUnicode_MAX_CHAR_VALUE:::: +PyUnicode_MAX_CHAR_VALUE:PyObject*:o:0: + +PyUnicode_AS_UNICODE:Py_UNICODE*::: +PyUnicode_AS_UNICODE:PyObject*:o:0: + +PyUnicode_AS_DATA:const char*::: +PyUnicode_AS_DATA:PyObject*:o:0: + +Py_UNICODE_ISALNUM:int::: +Py_UNICODE_ISALNUM:Py_UNICODE:ch:: + +Py_UNICODE_ISALPHA:int::: +Py_UNICODE_ISALPHA:Py_UNICODE:ch:: + +Py_UNICODE_ISSPACE:int::: +Py_UNICODE_ISSPACE:Py_UNICODE:ch:: + +Py_UNICODE_ISLOWER:int::: +Py_UNICODE_ISLOWER:Py_UNICODE:ch:: + +Py_UNICODE_ISUPPER:int::: +Py_UNICODE_ISUPPER:Py_UNICODE:ch:: + +Py_UNICODE_ISTITLE:int::: +Py_UNICODE_ISTITLE:Py_UNICODE:ch:: + +Py_UNICODE_ISLINEBREAK:int::: +Py_UNICODE_ISLINEBREAK:Py_UNICODE:ch:: + +Py_UNICODE_ISDECIMAL:int::: +Py_UNICODE_ISDECIMAL:Py_UNICODE:ch:: + +Py_UNICODE_ISDIGIT:int::: +Py_UNICODE_ISDIGIT:Py_UNICODE:ch:: + +Py_UNICODE_ISNUMERIC:int::: +Py_UNICODE_ISNUMERIC:Py_UNICODE:ch:: + +Py_UNICODE_ISPRINTABLE:int::: +Py_UNICODE_ISPRINTABLE:Py_UNICODE:ch:: + +Py_UNICODE_TOLOWER:Py_UNICODE::: +Py_UNICODE_TOLOWER:Py_UNICODE:ch:: + +Py_UNICODE_TOUPPER:Py_UNICODE::: +Py_UNICODE_TOUPPER:Py_UNICODE:ch:: + +Py_UNICODE_TOTITLE:Py_UNICODE::: +Py_UNICODE_TOTITLE:Py_UNICODE:ch:: + +Py_UNICODE_TODECIMAL:int::: +Py_UNICODE_TODECIMAL:Py_UNICODE:ch:: + +Py_UNICODE_TODIGIT:int::: +Py_UNICODE_TODIGIT:Py_UNICODE:ch:: + +Py_UNICODE_TONUMERIC:double::: +Py_UNICODE_TONUMERIC:Py_UNICODE:ch:: + +PyUnicode_FromUnicode:PyObject*::+1: +PyUnicode_FromUnicode:const Py_UNICODE*:u:: +PyUnicode_FromUnicode:Py_ssize_t:size:: + +PyUnicode_AsUnicode:Py_UNICODE*::: +PyUnicode_AsUnicode:PyObject*:unicode:0: + +PyUnicode_TransformDecimalToASCII:PyObject*::+1: +PyUnicode_TransformDecimalToASCII:Py_UNICODE*:s:: +PyUnicode_TransformDecimalToASCII:Py_ssize_t:size:: + +PyUnicode_AsUnicodeAndSize:Py_UNICODE*::: +PyUnicode_AsUnicodeAndSize:PyObject*:unicode:0: +PyUnicode_AsUnicodeAndSize:Py_ssize_t*:size:: + +PyUnicode_AsUnicodeCopy:Py_UNICODE*::: +PyUnicode_AsUnicodeCopy:PyObject*:unicode:0: + +PyUnicode_GetSize:Py_ssize_t::: +PyUnicode_GetSize:PyObject*:unicode:0: + +PyUnicode_FromObject:PyObject*::+1: +PyUnicode_FromObject:PyObject*:obj:0: + +PyUnicode_FromEncodedObject:PyObject*::+1: +PyUnicode_FromEncodedObject:PyObject*:obj:0: +PyUnicode_FromEncodedObject:const char*:encoding:: +PyUnicode_FromEncodedObject:const char*:errors:: + +PyUnicode_FromWideChar:PyObject*::+1: +PyUnicode_FromWideChar:const wchar_t*:w:: +PyUnicode_FromWideChar:Py_ssize_t:size:: + +PyUnicode_AsWideChar:Py_ssize_t::: +PyUnicode_AsWideChar:PyObject*:*unicode:0: +PyUnicode_AsWideChar:wchar_t*:w:: +PyUnicode_AsWideChar:Py_ssize_t:size:: + +PyUnicode_AsWideCharString:wchar_t*::: +PyUnicode_AsWideCharString:PyObject*:unicode:0: +PyUnicode_AsWideCharString:Py_ssize_t*:size:: + +PyUnicode_Decode:PyObject*::+1: +PyUnicode_Decode:const char*:s:: +PyUnicode_Decode:Py_ssize_t:size:: +PyUnicode_Decode:const char*:encoding:: +PyUnicode_Decode:const char*:errors:: + +PyUnicode_DecodeUTF16Stateful:PyObject*::+1: +PyUnicode_DecodeUTF16Stateful:const char*:s:: +PyUnicode_DecodeUTF16Stateful:Py_ssize_t:size:: +PyUnicode_DecodeUTF16Stateful:const char*:errors:: +PyUnicode_DecodeUTF16Stateful:int*:byteorder:: +PyUnicode_DecodeUTF16Stateful:Py_ssize_t*:consumed:: + +PyUnicode_DecodeUTF8Stateful:PyObject*::+1: +PyUnicode_DecodeUTF8Stateful:const char*:s:: +PyUnicode_DecodeUTF8Stateful:Py_ssize_t:size:: +PyUnicode_DecodeUTF8Stateful:const char*:errors:: +PyUnicode_DecodeUTF8Stateful:Py_ssize_t*:consumed:: + +PyUnicode_Encode:PyObject*::+1: +PyUnicode_Encode:const Py_UNICODE*:s:: +PyUnicode_Encode:Py_ssize_t:size:: +PyUnicode_Encode:const char*:encoding:: +PyUnicode_Encode:const char*:errors:: + +PyUnicode_AsEncodedString:PyObject*::+1: +PyUnicode_AsEncodedString:PyObject*:unicode:0: +PyUnicode_AsEncodedString:const char*:encoding:: +PyUnicode_AsEncodedString:const char*:errors:: + +PyUnicode_DecodeUTF7:PyObject*::+1: +PyUnicode_DecodeUTF7:const char*:s:: +PyUnicode_DecodeUTF7:Py_ssize_t:size:: +PyUnicode_DecodeUTF7:const char*:errors:: + +PyUnicode_DecodeUTF7Stateful:PyObject*::+1: +PyUnicode_DecodeUTF7Stateful:const char*:s:: +PyUnicode_DecodeUTF7Stateful:Py_ssize_t:size:: +PyUnicode_DecodeUTF7Stateful:const char*:errors:: +PyUnicode_DecodeUTF7Stateful:Py_ssize_t*:consumed:: + +PyUnicode_EncodeUTF7:PyObject*::+1: +PyUnicode_EncodeUTF7:const Py_UNICODE*:s:: +PyUnicode_EncodeUTF7:Py_ssize_t:size:: +PyUnicode_EncodeUTF7:int:base64SetO:: +PyUnicode_EncodeUTF7:int:base64WhiteSpace:: +PyUnicode_EncodeUTF7:const char*:errors:: + +PyUnicode_DecodeUTF8:PyObject*::+1: +PyUnicode_DecodeUTF8:const char*:s:: +PyUnicode_DecodeUTF8:Py_ssize_t:size:: +PyUnicode_DecodeUTF8:const char*:errors:: + +PyUnicode_EncodeUTF8:PyObject*::+1: +PyUnicode_EncodeUTF8:const Py_UNICODE*:s:: +PyUnicode_EncodeUTF8:Py_ssize_t:size:: +PyUnicode_EncodeUTF8:const char*:errors:: + +PyUnicode_AsUTF8String:PyObject*::+1: +PyUnicode_AsUTF8String:PyObject*:unicode:0: + +PyUnicode_AsUTF8AndSize:const char*::: +PyUnicode_AsUTF8AndSize:PyObject*:unicode:0: +PyUnicode_AsUTF8AndSize:Py_ssize_t*:size:0: + +PyUnicode_AsUTF8:const char*::: +PyUnicode_AsUTF8:PyObject*:unicode:0: + +PyUnicode_DecodeUTF16:PyObject*::+1: +PyUnicode_DecodeUTF16:const char*:s:: +PyUnicode_DecodeUTF16:Py_ssize_t:size:: +PyUnicode_DecodeUTF16:const char*:errors:: +PyUnicode_DecodeUTF16:int*:byteorder:: + +PyUnicode_EncodeUTF16:PyObject*::+1: +PyUnicode_EncodeUTF16:const Py_UNICODE*:s:: +PyUnicode_EncodeUTF16:Py_ssize_t:size:: +PyUnicode_EncodeUTF16:const char*:errors:: +PyUnicode_EncodeUTF16:int:byteorder:: + +PyUnicode_AsUTF16String:PyObject*::+1: +PyUnicode_AsUTF16String:PyObject*:unicode:0: + +PyUnicode_DecodeUTF32:PyObject*::+1: +PyUnicode_DecodeUTF32:const char*:s:: +PyUnicode_DecodeUTF32:Py_ssize_t:size:: +PyUnicode_DecodeUTF32:const char*:errors:: +PyUnicode_DecodeUTF32:int*:byteorder:: + +PyUnicode_DecodeUTF32Stateful:PyObject*::+1: +PyUnicode_DecodeUTF32Stateful:const char*:s:: +PyUnicode_DecodeUTF32Stateful:Py_ssize_t:size:: +PyUnicode_DecodeUTF32Stateful:const char*:errors:: +PyUnicode_DecodeUTF32Stateful:int*:byteorder:: +PyUnicode_DecodeUTF32Stateful:Py_ssize_t*:consumed:: + +PyUnicode_AsUTF32String:PyObject*::+1: +PyUnicode_AsUTF32String:PyObject*:unicode:0: + +PyUnicode_EncodeUTF32:PyObject*::+1: +PyUnicode_EncodeUTF32:const Py_UNICODE*:s:: +PyUnicode_EncodeUTF32:Py_ssize_t:size:: +PyUnicode_EncodeUTF32:const char*:errors:: +PyUnicode_EncodeUTF32:int:byteorder:: + +PyUnicode_DecodeUnicodeEscape:PyObject*::+1: +PyUnicode_DecodeUnicodeEscape:const char*:s:: +PyUnicode_DecodeUnicodeEscape:Py_ssize_t:size:: +PyUnicode_DecodeUnicodeEscape:const char*:errors:: + +PyUnicode_EncodeUnicodeEscape:PyObject*::+1: +PyUnicode_EncodeUnicodeEscape:const Py_UNICODE*:s:: +PyUnicode_EncodeUnicodeEscape:Py_ssize_t:size:: + +PyUnicode_AsUnicodeEscapeString:PyObject*::+1: +PyUnicode_AsUnicodeEscapeString:PyObject*:unicode:0: + +PyUnicode_DecodeRawUnicodeEscape:PyObject*::+1: +PyUnicode_DecodeRawUnicodeEscape:const char*:s:: +PyUnicode_DecodeRawUnicodeEscape:Py_ssize_t:size:: +PyUnicode_DecodeRawUnicodeEscape:const char*:errors:: + +PyUnicode_EncodeRawUnicodeEscape:PyObject*::+1: +PyUnicode_EncodeRawUnicodeEscape:const Py_UNICODE*:s:: +PyUnicode_EncodeRawUnicodeEscape:Py_ssize_t:size:: + +PyUnicode_AsRawUnicodeEscapeString:PyObject*::+1: +PyUnicode_AsRawUnicodeEscapeString:PyObject*:unicode:0: + +PyUnicode_DecodeLatin1:PyObject*::+1: +PyUnicode_DecodeLatin1:const char*:s:: +PyUnicode_DecodeLatin1:Py_ssize_t:size:: +PyUnicode_DecodeLatin1:const char*:errors:: + +PyUnicode_EncodeLatin1:PyObject*::+1: +PyUnicode_EncodeLatin1:const Py_UNICODE*:s:: +PyUnicode_EncodeLatin1:Py_ssize_t:size:: +PyUnicode_EncodeLatin1:const char*:errors:: + +PyUnicode_AsLatin1String:PyObject*::+1: +PyUnicode_AsLatin1String:PyObject*:unicode:0: + +PyUnicode_DecodeASCII:PyObject*::+1: +PyUnicode_DecodeASCII:const char*:s:: +PyUnicode_DecodeASCII:Py_ssize_t:size:: +PyUnicode_DecodeASCII:const char*:errors:: + +PyUnicode_EncodeASCII:PyObject*::+1: +PyUnicode_EncodeASCII:const Py_UNICODE*:s:: +PyUnicode_EncodeASCII:Py_ssize_t:size:: +PyUnicode_EncodeASCII:const char*:errors:: + +PyUnicode_AsASCIIString:PyObject*::+1: +PyUnicode_AsASCIIString:PyObject*:unicode:0: + +PyUnicode_DecodeCharmap:PyObject*::+1: +PyUnicode_DecodeCharmap:const char*:s:: +PyUnicode_DecodeCharmap:Py_ssize_t:size:: +PyUnicode_DecodeCharmap:PyObject*:mapping:0: +PyUnicode_DecodeCharmap:const char*:errors:: + +PyUnicode_EncodeCharmap:PyObject*::+1: +PyUnicode_EncodeCharmap:const Py_UNICODE*:s:: +PyUnicode_EncodeCharmap:Py_ssize_t:size:: +PyUnicode_EncodeCharmap:PyObject*:mapping:0: +PyUnicode_EncodeCharmap:const char*:errors:: + +PyUnicode_AsCharmapString:PyObject*::+1: +PyUnicode_AsCharmapString:PyObject*:unicode:0: +PyUnicode_AsCharmapString:PyObject*:mapping:0: + +PyUnicode_TranslateCharmap:PyObject*::+1: +PyUnicode_TranslateCharmap:const Py_UNICODE*:s:: +PyUnicode_TranslateCharmap:Py_ssize_t:size:: +PyUnicode_TranslateCharmap:PyObject*:mapping:0: +PyUnicode_TranslateCharmap:const char*:errors:: + +PyUnicode_DecodeMBCS:PyObject*::+1: +PyUnicode_DecodeMBCS:const char*:s:: +PyUnicode_DecodeMBCS:Py_ssize_t:size:: +PyUnicode_DecodeMBCS:const char*:errors:: + +PyUnicode_DecodeMBCSStateful:PyObject*::+1: +PyUnicode_DecodeMBCSStateful:const char*:s:: +PyUnicode_DecodeMBCSStateful:Py_ssize_t:size:: +PyUnicode_DecodeMBCSStateful:const char*:errors:: +PyUnicode_DecodeMBCSStateful:Py_ssize_t*:consumed:: + +PyUnicode_EncodeCodePage:PyObject*::+1: +PyUnicode_EncodeCodePage:int:code_page:: +PyUnicode_EncodeCodePage:PyObject*:unicode:0: +PyUnicode_EncodeCodePage:const char*:errors:: + +PyUnicode_EncodeMBCS:PyObject*::+1: +PyUnicode_EncodeMBCS:const Py_UNICODE*:s:: +PyUnicode_EncodeMBCS:Py_ssize_t:size:: +PyUnicode_EncodeMBCS:const char*:errors:: + +PyUnicode_AsMBCSString:PyObject*::+1: +PyUnicode_AsMBCSString:PyObject*:unicode:0: + +PyUnicode_Concat:PyObject*::+1: +PyUnicode_Concat:PyObject*:left:0: +PyUnicode_Concat:PyObject*:right:0: + +PyUnicode_Split:PyObject*::+1: +PyUnicode_Split:PyObject*:left:0: +PyUnicode_Split:PyObject*:right:0: +PyUnicode_Split:Py_ssize_t:maxsplit:: + +PyUnicode_Splitlines:PyObject*::+1: +PyUnicode_Splitlines:PyObject*:s:0: +PyUnicode_Splitlines:int:keepend:: + +PyUnicode_Translate:PyObject*::+1: +PyUnicode_Translate:PyObject*:str:0: +PyUnicode_Translate:PyObject*:table:0: +PyUnicode_Translate:const char*:errors:: + +PyUnicode_Join:PyObject*::+1: +PyUnicode_Join:PyObject*:separator:0: +PyUnicode_Join:PyObject*:seq:0: + +PyUnicode_Tailmatch:Py_ssize_t::: +PyUnicode_Tailmatch:PyObject*:str:0: +PyUnicode_Tailmatch:PyObject*:substr:0: +PyUnicode_Tailmatch:Py_ssize_t:start:: +PyUnicode_Tailmatch:Py_ssize_t:end:: +PyUnicode_Tailmatch:int:direction:: + +PyUnicode_Find:Py_ssize_t::: +PyUnicode_Find:PyObject*:str:0: +PyUnicode_Find:PyObject*:substr:0: +PyUnicode_Find:Py_ssize_t:start:: +PyUnicode_Find:Py_ssize_t:end:: +PyUnicode_Find:int:direction:: + +PyUnicode_FindChar:Py_ssize_t::: +PyUnicode_FindChar:PyObject*:str:0: +PyUnicode_FindChar:Py_UCS4:ch:: +PyUnicode_FindChar:Py_ssize_t:start:: +PyUnicode_FindChar:Py_ssize_t:end:: +PyUnicode_FindChar:int:direction:: + +PyUnicode_Count:Py_ssize_t::: +PyUnicode_Count:PyObject*:str:0: +PyUnicode_Count:PyObject*:substr:0: +PyUnicode_Count:Py_ssize_t:start:: +PyUnicode_Count:Py_ssize_t:end:: + +PyUnicode_Replace:PyObject*::+1: +PyUnicode_Replace:PyObject*:str:0: +PyUnicode_Replace:PyObject*:substr:0: +PyUnicode_Replace:PyObject*:replstr:0: +PyUnicode_Replace:Py_ssize_t:maxcount:: + +PyUnicode_Compare:int::: +PyUnicode_Compare:PyObject*:left:0: +PyUnicode_Compare:PyObject*:right:0: + +PyUnicode_CompareWithASCIIString:int::: +PyUnicode_CompareWithASCIIString:PyObject*:uni:0: +PyUnicode_CompareWithASCIIString:const char*:string:: + +PyUnicode_RichCompare:PyObject*::+1: +PyUnicode_RichCompare:PyObject*:left:0: +PyUnicode_RichCompare:PyObject*:right:0: +PyUnicode_RichCompare:int:op:: + +PyUnicode_Format:PyObject*::+1: +PyUnicode_Format:PyObject*:format:0: +PyUnicode_Format:PyObject*:args:0: + +PyUnicode_Contains:int::: +PyUnicode_Contains:PyObject*:container:0: +PyUnicode_Contains:PyObject*:element:0: + +PyUnicode_InternInPlace:void::: +PyUnicode_InternInPlace:PyObject**:string:+1: + +PyUnicode_InternFromString:PyObject*::+1: +PyUnicode_InternFromString:const char*:v:: + +PyUnicode_New:PyObject*::+1: +PyUnicode_New:Py_ssize_t:size:: +PyUnicode_New:Py_UCS4:maxchar:: + +PyUnicode_FromKindAndData:PyObject*::+1: +PyUnicode_FromKindAndData:int:kind:: +PyUnicode_FromKindAndData:const void*:buffer:: +PyUnicode_FromKindAndData:Py_ssize_t:size:: + +PyUnicode_FromStringAndSize:PyObject*::+1: +PyUnicode_FromStringAndSize:const char*:u:: +PyUnicode_FromStringAndSize:Py_ssize_t:size:: + +PyUnicode_FromString:PyObject*::+1: +PyUnicode_FromString:const char*:u:: + +PyUnicode_FromFormat:PyObject*::+1: +PyUnicode_FromFormat:const char*:format:: +PyUnicode_FromFormat::...:: + +PyUnicode_FromFormatV:PyObject*::+1: +PyUnicode_FromFormatV:const char*:format:: +PyUnicode_FromFormatV:va_list:args:: + +PyUnicode_GetLength:Py_ssize_t::: +PyUnicode_GetLength:PyObject*:unicode:0: + +PyUnicode_CopyCharacters:Py_ssize_t::: +PyUnicode_CopyCharacters:PyObject*:to:0: +PyUnicode_CopyCharacters:Py_ssize_t:to_start:: +PyUnicode_CopyCharacters:PyObject*:from:0: +PyUnicode_CopyCharacters:Py_ssize_t:from_start:: +PyUnicode_CopyCharacters:Py_ssize_t:how_many:: + +PyUnicode_Fill:Py_ssize_t::: +PyUnicode_Fill:PyObject*:unicode:0: +PyUnicode_Fill:Py_ssize_t:start:: +PyUnicode_Fill:Py_ssize_t:length:: +PyUnicode_Fill:Py_UCS4:fill_char:: + +PyUnicode_READ:Py_UCS4::: +PyUnicode_READ:int:kind:: +PyUnicode_READ:void*:data:: +PyUnicode_READ:Py_ssize_t:index:: + +PyUnicode_READ_CHAR:Py_UCS4::: +PyUnicode_READ_CHAR:PyObject*:o:0: +PyUnicode_READ_CHAR:Py_ssize_t:index:: + +PyUnicode_ReadChar:Py_UCS4::: +PyUnicode_ReadChar:PyObject*:unicode:0: +PyUnicode_ReadChar:Py_ssize_t:index:: + +PyUnicode_WRITE:void::: +PyUnicode_WRITE:int:kind:: +PyUnicode_WRITE:void*:data:: +PyUnicode_WRITE:Py_ssize_t:index:: +PyUnicode_WRITE:Py_UCS4:value:: + +PyUnicode_WriteChar:int::: +PyUnicode_WriteChar:PyObject*:unicode:0: +PyUnicode_WriteChar:Py_ssize_t:index:: +PyUnicode_WriteChar:Py_UCS4:character:: + +PyUnicode_READY:int::: +PyUnicode_READY:PyObject*:o:0: + +PyUnicode_Substring:PyObject*::+1: +PyUnicode_Substring:PyObject*:str:0: +PyUnicode_Substring:Py_ssize_t:start:: +PyUnicode_Substring:Py_ssize_t:end:: + +PyUnicode_AsUCS4:Py_UCS4*::: +PyUnicode_AsUCS4:PyObject*:u:0: +PyUnicode_AsUCS4:Py_UCS4*:buffer:: +PyUnicode_AsUCS4:Py_ssize_t:buflen:: +PyUnicode_AsUCS4:int:copy_null:: + +PyUnicode_AsUCS4Copy:Py_UCS4*::: +PyUnicode_AsUCS4Copy:PyObject*:u:0: + +PyUnicode_DecodeLocaleAndSize:PyObject*::+1: +PyUnicode_DecodeLocaleAndSize:const char*:str:: +PyUnicode_DecodeLocaleAndSize:Py_ssize_t:len:: +PyUnicode_DecodeLocaleAndSize:const char*:errors:: + +PyUnicode_DecodeLocale:PyObject*::+1: +PyUnicode_DecodeLocale:const char*:str:: +PyUnicode_DecodeLocale:const char*:errors:: + +PyUnicode_EncodeLocale:PyObject*::+1: +PyUnicode_EncodeLocale:PyObject*:unicode:0: +PyUnicode_EncodeLocale:const char*:errors:: + +PyUnicode_FSConverter:int::: +PyUnicode_FSConverter:PyObject*:obj:0: +PyUnicode_FSConverter:void*:result:: + +PyUnicode_FSDecoder:int::: +PyUnicode_FSDecoder:PyObject*:obj:0: +PyUnicode_FSDecoder:void*:result:: + +PyUnicode_DecodeFSDefaultAndSize:PyObject*::+1: +PyUnicode_DecodeFSDefaultAndSize:const char*:s:: +PyUnicode_DecodeFSDefaultAndSize:Py_ssize_t:size:: + +PyUnicode_DecodeFSDefault:PyObject*::+1: +PyUnicode_DecodeFSDefault:const char*:s:: + +PyUnicode_EncodeFSDefault:PyObject*::+1: +PyUnicode_EncodeFSDefault:PyObject*:unicode:0: + +PyUnicodeDecodeError_Create:PyObject*::+1: +PyUnicodeDecodeError_Create:const char*:encoding:: +PyUnicodeDecodeError_Create:const char*:object:: +PyUnicodeDecodeError_Create:Py_ssize_t:length:: +PyUnicodeDecodeError_Create:Py_ssize_t:start:: +PyUnicodeDecodeError_Create:Py_ssize_t:end:: +PyUnicodeDecodeError_Create:const char*:reason:: + +PyUnicodeDecodeError_GetEncoding:PyObject*::+1: +PyUnicodeDecodeError_GetEncoding:PyObject*:exc:0: + +PyUnicodeDecodeError_GetEnd:Py_ssize_t::: +PyUnicodeDecodeError_GetEnd:PyObject*:exc:0: +PyUnicodeDecodeError_GetEnd:Py_ssize_t*:end:: + +PyUnicodeDecodeError_GetObject:PyObject*::+1: +PyUnicodeDecodeError_GetObject:PyObject*:exc:0: + +PyUnicodeDecodeError_GetReason:PyObject*::+1: +PyUnicodeDecodeError_GetReason:PyObject*:exc:0: + +PyUnicodeDecodeError_GetStart:Py_ssize_t::: +PyUnicodeDecodeError_GetStart:PyObject*:exc:0: +PyUnicodeDecodeError_GetStart:Py_ssize_t*:start:: + +PyUnicodeDecodeError_SetEnd:int::: +PyUnicodeDecodeError_SetEnd:PyObject*:exc:0: +PyUnicodeDecodeError_SetEnd:Py_ssize_t:end:: + +PyUnicodeDecodeError_SetReason:int::: +PyUnicodeDecodeError_SetReason:PyObject*:exc:0: +PyUnicodeDecodeError_SetReason:const char*:reason:: + +PyUnicodeDecodeError_SetStart:int::: +PyUnicodeDecodeError_SetStart:PyObject*:exc:0: +PyUnicodeDecodeError_SetStart:Py_ssize_t:start:: + +PyUnicodeEncodeError_Create:PyObject*::+1: +PyUnicodeEncodeError_Create:const char*:encoding:: +PyUnicodeEncodeError_Create:const Py_UNICODE*:object:: +PyUnicodeEncodeError_Create:Py_ssize_t:length:: +PyUnicodeEncodeError_Create:Py_ssize_t:start:: +PyUnicodeEncodeError_Create:Py_ssize_t:end:: +PyUnicodeEncodeError_Create:const char*:reason:: + +PyUnicodeTranslateError_Create:PyObject*::+1: +PyUnicodeTranslateError_Create:const Py_UNICODE*:object:: +PyUnicodeTranslateError_Create:Py_ssize_t:length:: +PyUnicodeTranslateError_Create:Py_ssize_t:start:: +PyUnicodeTranslateError_Create:Py_ssize_t:end:: +PyUnicodeTranslateError_Create:const char*:reason:: + +PyWeakref_Check:int::: +PyWeakref_Check:PyObject*:ob:: + +PyWeakref_CheckProxy:int::: +PyWeakref_CheckProxy:PyObject*:ob:: + +PyWeakref_CheckRef:int::: +PyWeakref_CheckRef:PyObject*:ob:: + +PyWeakref_GET_OBJECT:PyObject*::0: +PyWeakref_GET_OBJECT:PyObject*:ref:0: + +PyWeakref_GetObject:PyObject*::0: +PyWeakref_GetObject:PyObject*:ref:0: + +PyWeakref_NewProxy:PyObject*::+1: +PyWeakref_NewProxy:PyObject*:ob:0: +PyWeakref_NewProxy:PyObject*:callback:0: + +PyWeakref_NewRef:PyObject*::+1: +PyWeakref_NewRef:PyObject*:ob:0: +PyWeakref_NewRef:PyObject*:callback:0: + +PyWrapper_New:PyObject*::+1: +PyWrapper_New:PyObject*:d:0: +PyWrapper_New:PyObject*:self:0: + +Py_AtExit:int::: +Py_AtExit:void (*)():func:: + +Py_BuildValue:PyObject*::+1: +Py_BuildValue:const char*:format:: +Py_BuildValue::...:: + +Py_VaBuildValue:PyObject*::+1: +Py_VaBuildValue:const char*:format:: +Py_VaBuildValue:va_list:vargs:: + +Py_CLEAR:void::: +Py_CLEAR:PyObject*:o:-1: + +Py_CompileString:PyObject*::+1: +Py_CompileString:const char*:str:: +Py_CompileString:const char*:filename:: +Py_CompileString:int:start:: + +Py_CompileStringExFlags:PyObject*::+1: +Py_CompileStringExFlags:const char*:str:: +Py_CompileStringExFlags:const char*:filename:: +Py_CompileStringExFlags:int:start:: +Py_CompileStringExFlags:PyCompilerFlags*:flags:: +Py_CompileStringExFlags:int:optimize:: + +Py_CompileStringFlags:PyObject*::+1: +Py_CompileStringFlags:const char*:str:: +Py_CompileStringFlags:const char*:filename:: +Py_CompileStringFlags:int:start:: +Py_CompileStringFlags:PyCompilerFlags*:flags:: + +Py_CompileStringObject:PyObject*::+1: +Py_CompileStringObject:const char*:str:: +Py_CompileStringObject:PyObject*:filename:0: +Py_CompileStringObject:int:start:: +Py_CompileStringObject:PyCompilerFlags*:flags:: +Py_CompileStringObject:int:optimize:: + +Py_DECREF:void::: +Py_DECREF:PyObject*:o:-1: + +Py_EndInterpreter:void::: +Py_EndInterpreter:PyThreadState*:tstate:: + +Py_Exit:void::: +Py_Exit:int:status:: + +Py_FatalError:void::: +Py_FatalError:const char*:message:: + +Py_FdIsInteractive:int::: +Py_FdIsInteractive:FILE*:fp:: +Py_FdIsInteractive:const char*:filename:: + +Py_Finalize:void::: + +Py_GetBuildInfo:const char*::: + +Py_GetCompiler:const char*::: + +Py_GetCopyright:const char*::: + +Py_GetExecPrefix:wchar_t*::: + +Py_GetPath:wchar_t*::: + +Py_GetPlatform:const char*::: + +Py_GetPrefix:wchar_t*::: + +Py_GetProgramFullPath:wchar_t*::: + +Py_GetProgramName:wchar_t*::: + +Py_GetVersion:const char*::: + +Py_INCREF:void::: +Py_INCREF:PyObject*:o:+1: + +Py_Initialize:void::: + +Py_IsInitialized:int::: + +Py_NewInterpreter:PyThreadState*::: + +Py_ReprEnter:int::: +Py_ReprEnter:PyObject*:object:+1: + +Py_ReprLeave:void::: +Py_ReprLeave:PyObject*:object:-1: + +Py_SetProgramName:void::: +Py_SetProgramName:const wchar_t*:name:: + +Py_XDECREF:void::: +Py_XDECREF:PyObject*:o:-1:if o is not NULL + +Py_XINCREF:void::: +Py_XINCREF:PyObject*:o:+1:if o is not NULL + +_PyImport_Fini:void::: + +_PyObject_New:PyObject*::+1: +_PyObject_New:PyTypeObject*:type:0: + +_PyObject_NewVar:PyVarObject*::+1: +_PyObject_NewVar:PyTypeObject*:type:0: +_PyObject_NewVar:Py_ssize_t:size:: + +_PyBytes_Resize:int::: +_PyBytes_Resize:PyObject**:bytes:0: +_PyBytes_Resize:Py_ssize_t:newsize:: + +_PyTuple_Resize:int::: +_PyTuple_Resize:PyObject**:p:0: +_PyTuple_Resize:Py_ssize_t:new:: + +_Py_c_diff:Py_complex::: +_Py_c_diff:Py_complex:left:: +_Py_c_diff:Py_complex:right:: + +_Py_c_neg:Py_complex::: +_Py_c_neg:Py_complex:complex:: + +_Py_c_pow:Py_complex::: +_Py_c_pow:Py_complex:num:: +_Py_c_pow:Py_complex:exp:: + +_Py_c_prod:Py_complex::: +_Py_c_prod:Py_complex:left:: +_Py_c_prod:Py_complex:right:: + +_Py_c_quot:Py_complex::: +_Py_c_quot:Py_complex:dividend:: +_Py_c_quot:Py_complex:divisor:: + +_Py_c_sum:Py_complex::: +_Py_c_sum:Py_complex:left:: +_Py_c_sum:Py_complex:right:: diff --git a/cpython_2/environment/repo/Doc/distributing/index.rst b/cpython_2/environment/repo/Doc/distributing/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..5f7b3bbc4f9174a4b8bab95b446a05cbb329d3c7 --- /dev/null +++ b/cpython_2/environment/repo/Doc/distributing/index.rst @@ -0,0 +1,176 @@ +.. _distributing-index: + +############################### + Distributing Python Modules +############################### + +:Email: distutils-sig@python.org + + +As a popular open source development project, Python has an active +supporting community of contributors and users that also make their software +available for other Python developers to use under open source license terms. + +This allows Python users to share and collaborate effectively, benefiting +from the solutions others have already created to common (and sometimes +even rare!) problems, as well as potentially contributing their own +solutions to the common pool. + +This guide covers the distribution part of the process. For a guide to +installing other Python projects, refer to the +:ref:`installation guide <installing-index>`. + +.. note:: + + For corporate and other institutional users, be aware that many + organisations have their own policies around using and contributing to + open source software. Please take such policies into account when making + use of the distribution and installation tools provided with Python. + + +Key terms +========= + +* the `Python Packaging Index <https://pypi.org>`__ is a public + repository of open source licensed packages made available for use by + other Python users +* the `Python Packaging Authority + <https://www.pypa.io/>`__ are the group of + developers and documentation authors responsible for the maintenance and + evolution of the standard packaging tools and the associated metadata and + file format standards. They maintain a variety of tools, documentation + and issue trackers on both `GitHub <https://github.com/pypa>`__ and + `Bitbucket <https://bitbucket.org/pypa/>`__. +* :mod:`distutils` is the original build and distribution system first added + to the Python standard library in 1998. While direct use of :mod:`distutils` + is being phased out, it still laid the foundation for the current packaging + and distribution infrastructure, and it not only remains part of the + standard library, but its name lives on in other ways (such as the name + of the mailing list used to coordinate Python packaging standards + development). +* `setuptools`_ is a (largely) drop-in replacement for :mod:`distutils` first + published in 2004. Its most notable addition over the unmodified + :mod:`distutils` tools was the ability to declare dependencies on other + packages. It is currently recommended as a more regularly updated + alternative to :mod:`distutils` that offers consistent support for more + recent packaging standards across a wide range of Python versions. +* `wheel`_ (in this context) is a project that adds the ``bdist_wheel`` + command to :mod:`distutils`/`setuptools`_. This produces a cross platform + binary packaging format (called "wheels" or "wheel files" and defined in + :pep:`427`) that allows Python libraries, even those including binary + extensions, to be installed on a system without needing to be built + locally. + +.. _setuptools: https://setuptools.readthedocs.io/en/latest/ +.. _wheel: https://wheel.readthedocs.io/ + +Open source licensing and collaboration +======================================= + +In most parts of the world, software is automatically covered by copyright. +This means that other developers require explicit permission to copy, use, +modify and redistribute the software. + +Open source licensing is a way of explicitly granting such permission in a +relatively consistent way, allowing developers to share and collaborate +efficiently by making common solutions to various problems freely available. +This leaves many developers free to spend more time focusing on the problems +that are relatively unique to their specific situation. + +The distribution tools provided with Python are designed to make it +reasonably straightforward for developers to make their own contributions +back to that common pool of software if they choose to do so. + +The same distribution tools can also be used to distribute software within +an organisation, regardless of whether that software is published as open +source software or not. + + +Installing the tools +==================== + +The standard library does not include build tools that support modern +Python packaging standards, as the core development team has found that it +is important to have standard tools that work consistently, even on older +versions of Python. + +The currently recommended build and distribution tools can be installed +by invoking the ``pip`` module at the command line:: + + python -m pip install setuptools wheel twine + +.. note:: + + For POSIX users (including Mac OS X and Linux users), these instructions + assume the use of a :term:`virtual environment`. + + For Windows users, these instructions assume that the option to + adjust the system PATH environment variable was selected when installing + Python. + +The Python Packaging User Guide includes more details on the `currently +recommended tools`_. + +.. _currently recommended tools: https://packaging.python.org/guides/tool-recommendations/#packaging-tool-recommendations + +.. index:: + single: Python Package Index (PyPI) + single: PyPI; (see Python Package Index (PyPI)) + +.. _publishing-python-packages: + +Reading the Python Packaging User Guide +======================================= + +The Python Packaging User Guide covers the various key steps and elements +involved in creating and publishing a project: + +* `Project structure`_ +* `Building and packaging the project`_ +* `Uploading the project to the Python Packaging Index`_ + +.. _Project structure: \ + https://packaging.python.org/tutorials/distributing-packages/ +.. _Building and packaging the project: \ + https://packaging.python.org/tutorials/distributing-packages/#packaging-your-project +.. _Uploading the project to the Python Packaging Index: \ + https://packaging.python.org/tutorials/distributing-packages/#uploading-your-project-to-pypi + + +How do I...? +============ + +These are quick answers or links for some common tasks. + +... choose a name for my project? +--------------------------------- + +This isn't an easy topic, but here are a few tips: + +* check the Python Packaging Index to see if the name is already in use +* check popular hosting sites like GitHub, Bitbucket, etc to see if there + is already a project with that name +* check what comes up in a web search for the name you're considering +* avoid particularly common words, especially ones with multiple meanings, + as they can make it difficult for users to find your software when + searching for it + + +... create and distribute binary extensions? +-------------------------------------------- + +This is actually quite a complex topic, with a variety of alternatives +available depending on exactly what you're aiming to achieve. See the +Python Packaging User Guide for more information and recommendations. + +.. seealso:: + + `Python Packaging User Guide: Binary Extensions + <https://packaging.python.org/guides/packaging-binary-extensions/>`__ + +.. other topics: + + Once the Development & Deployment part of PPUG is fleshed out, some of + those sections should be linked from new questions here (most notably, + we should have a question about avoiding depending on PyPI that links to + https://packaging.python.org/en/latest/mirrors/) diff --git a/cpython_2/environment/repo/Doc/distutils/_setuptools_disclaimer.rst b/cpython_2/environment/repo/Doc/distutils/_setuptools_disclaimer.rst new file mode 100644 index 0000000000000000000000000000000000000000..cc75858326d44d988c90df0e6c11b48bc57579a8 --- /dev/null +++ b/cpython_2/environment/repo/Doc/distutils/_setuptools_disclaimer.rst @@ -0,0 +1,5 @@ +.. note:: + + This document is being retained solely until the ``setuptools`` documentation + at https://setuptools.readthedocs.io/en/latest/setuptools.html + independently covers all of the relevant information currently included here. diff --git a/cpython_2/environment/repo/Doc/distutils/apiref.rst b/cpython_2/environment/repo/Doc/distutils/apiref.rst new file mode 100644 index 0000000000000000000000000000000000000000..b14197c2f94dbabfb57884a6b29dc009f2dae896 --- /dev/null +++ b/cpython_2/environment/repo/Doc/distutils/apiref.rst @@ -0,0 +1,2070 @@ +.. _api-reference: + +************* +API Reference +************* + +.. seealso:: + + `New and changed setup.py arguments in setuptools`_ + The ``setuptools`` project adds new capabilities to the ``setup`` function + and other APIs, makes the API consistent across different Python versions, + and is hence recommended over using ``distutils`` directly. + +.. _New and changed setup.py arguments in setuptools: https://setuptools.readthedocs.io/en/latest/setuptools.html#new-and-changed-setup-keywords + +.. include:: ./_setuptools_disclaimer.rst + +:mod:`distutils.core` --- Core Distutils functionality +====================================================== + +.. module:: distutils.core + :synopsis: The core Distutils functionality + + +The :mod:`distutils.core` module is the only module that needs to be installed +to use the Distutils. It provides the :func:`setup` (which is called from the +setup script). Indirectly provides the :class:`distutils.dist.Distribution` and +:class:`distutils.cmd.Command` class. + + +.. function:: setup(arguments) + + The basic do-everything function that does most everything you could ever ask + for from a Distutils method. + + The setup function takes a large number of arguments. These are laid out in the + following table. + + .. tabularcolumns:: |l|L|L| + + +--------------------+--------------------------------+-------------------------------------------------------------+ + | argument name | value | type | + +====================+================================+=============================================================+ + | *name* | The name of the package | a string | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *version* | The version number of the | a string | + | | package; see | | + | | :mod:`distutils.version` | | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *description* | A single line describing the | a string | + | | package | | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *long_description* | Longer description of the | a string | + | | package | | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *author* | The name of the package author | a string | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *author_email* | The email address of the | a string | + | | package author | | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *maintainer* | The name of the current | a string | + | | maintainer, if different from | | + | | the author. Note that if | | + | | the maintainer is provided, | | + | | distutils will use it as the | | + | | author in :file:`PKG-INFO` | | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *maintainer_email* | The email address of the | a string | + | | current maintainer, if | | + | | different from the author | | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *url* | A URL for the package | a string | + | | (homepage) | | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *download_url* | A URL to download the package | a string | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *packages* | A list of Python packages that | a list of strings | + | | distutils will manipulate | | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *py_modules* | A list of Python modules that | a list of strings | + | | distutils will manipulate | | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *scripts* | A list of standalone script | a list of strings | + | | files to be built and | | + | | installed | | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *ext_modules* | A list of Python extensions to | a list of instances of | + | | be built | :class:`distutils.core.Extension` | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *classifiers* | A list of categories for the | a list of strings; valid classifiers are listed on `PyPI | + | | package | <https://pypi.org/classifiers>`_. | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *distclass* | the :class:`Distribution` | a subclass of | + | | class to use | :class:`distutils.core.Distribution` | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *script_name* | The name of the setup.py | a string | + | | script - defaults to | | + | | ``sys.argv[0]`` | | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *script_args* | Arguments to supply to the | a list of strings | + | | setup script | | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *options* | default options for the setup | a dictionary | + | | script | | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *license* | The license for the package | a string | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *keywords* | Descriptive meta-data, see | a list of strings or a comma-separated string | + | | :pep:`314` | | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *platforms* | | a list of strings or a comma-separated string | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *cmdclass* | A mapping of command names to | a dictionary | + | | :class:`Command` subclasses | | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *data_files* | A list of data files to | a list | + | | install | | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *package_dir* | A mapping of package to | a dictionary | + | | directory names | | + +--------------------+--------------------------------+-------------------------------------------------------------+ + + + +.. function:: run_setup(script_name[, script_args=None, stop_after='run']) + + Run a setup script in a somewhat controlled environment, and return the + :class:`distutils.dist.Distribution` instance that drives things. This is + useful if you need to find out the distribution meta-data (passed as keyword + args from *script* to :func:`setup`), or the contents of the config files or + command-line. + + *script_name* is a file that will be read and run with :func:`exec`. ``sys.argv[0]`` + will be replaced with *script* for the duration of the call. *script_args* is a + list of strings; if supplied, ``sys.argv[1:]`` will be replaced by *script_args* + for the duration of the call. + + *stop_after* tells :func:`setup` when to stop processing; possible values: + + .. tabularcolumns:: |l|L| + + +---------------+---------------------------------------------+ + | value | description | + +===============+=============================================+ + | *init* | Stop after the :class:`Distribution` | + | | instance has been created and populated | + | | with the keyword arguments to :func:`setup` | + +---------------+---------------------------------------------+ + | *config* | Stop after config files have been parsed | + | | (and their data stored in the | + | | :class:`Distribution` instance) | + +---------------+---------------------------------------------+ + | *commandline* | Stop after the command-line | + | | (``sys.argv[1:]`` or *script_args*) have | + | | been parsed (and the data stored in the | + | | :class:`Distribution` instance.) | + +---------------+---------------------------------------------+ + | *run* | Stop after all commands have been run (the | + | | same as if :func:`setup` had been called | + | | in the usual way). This is the default | + | | value. | + +---------------+---------------------------------------------+ + +In addition, the :mod:`distutils.core` module exposed a number of classes that +live elsewhere. + +* :class:`~distutils.extension.Extension` from :mod:`distutils.extension` + +* :class:`~distutils.cmd.Command` from :mod:`distutils.cmd` + +* :class:`~distutils.dist.Distribution` from :mod:`distutils.dist` + +A short description of each of these follows, but see the relevant module for +the full reference. + + +.. class:: Extension + + The Extension class describes a single C or C++ extension module in a setup + script. It accepts the following keyword arguments in its constructor: + + .. tabularcolumns:: |l|L|l| + + +------------------------+--------------------------------+---------------------------+ + | argument name | value | type | + +========================+================================+===========================+ + | *name* | the full name of the | a string | + | | extension, including any | | + | | packages --- ie. *not* a | | + | | filename or pathname, but | | + | | Python dotted name | | + +------------------------+--------------------------------+---------------------------+ + | *sources* | list of source filenames, | a list of strings | + | | relative to the distribution | | + | | root (where the setup script | | + | | lives), in Unix form | | + | | (slash-separated) for | | + | | portability. | | + | | Source files may be C, C++, | | + | | SWIG (.i), platform-specific | | + | | resource files, or whatever | | + | | else is recognized by the | | + | | :command:`build_ext` command | | + | | as source for a Python | | + | | extension. | | + +------------------------+--------------------------------+---------------------------+ + | *include_dirs* | list of directories to search | a list of strings | + | | for C/C++ header files (in | | + | | Unix form for portability) | | + +------------------------+--------------------------------+---------------------------+ + | *define_macros* | list of macros to define; each | a list of tuples | + | | macro is defined using a | | + | | 2-tuple ``(name, value)``, | | + | | where *value* is | | + | | either the string to define it | | + | | to or ``None`` to define it | | + | | without a particular value | | + | | (equivalent of ``#define FOO`` | | + | | in source or :option:`!-DFOO` | | + | | on Unix C compiler command | | + | | line) | | + +------------------------+--------------------------------+---------------------------+ + | *undef_macros* | list of macros to undefine | a list of strings | + | | explicitly | | + +------------------------+--------------------------------+---------------------------+ + | *library_dirs* | list of directories to search | a list of strings | + | | for C/C++ libraries at link | | + | | time | | + +------------------------+--------------------------------+---------------------------+ + | *libraries* | list of library names (not | a list of strings | + | | filenames or paths) to link | | + | | against | | + +------------------------+--------------------------------+---------------------------+ + | *runtime_library_dirs* | list of directories to search | a list of strings | + | | for C/C++ libraries at run | | + | | time (for shared extensions, | | + | | this is when the extension is | | + | | loaded) | | + +------------------------+--------------------------------+---------------------------+ + | *extra_objects* | list of extra files to link | a list of strings | + | | with (eg. object files not | | + | | implied by 'sources', static | | + | | library that must be | | + | | explicitly specified, binary | | + | | resource files, etc.) | | + +------------------------+--------------------------------+---------------------------+ + | *extra_compile_args* | any extra platform- and | a list of strings | + | | compiler-specific information | | + | | to use when compiling the | | + | | source files in 'sources'. For | | + | | platforms and compilers where | | + | | a command line makes sense, | | + | | this is typically a list of | | + | | command-line arguments, but | | + | | for other platforms it could | | + | | be anything. | | + +------------------------+--------------------------------+---------------------------+ + | *extra_link_args* | any extra platform- and | a list of strings | + | | compiler-specific information | | + | | to use when linking object | | + | | files together to create the | | + | | extension (or to create a new | | + | | static Python interpreter). | | + | | Similar interpretation as for | | + | | 'extra_compile_args'. | | + +------------------------+--------------------------------+---------------------------+ + | *export_symbols* | list of symbols to be exported | a list of strings | + | | from a shared extension. Not | | + | | used on all platforms, and not | | + | | generally necessary for Python | | + | | extensions, which typically | | + | | export exactly one symbol: | | + | | ``init`` + extension_name. | | + +------------------------+--------------------------------+---------------------------+ + | *depends* | list of files that the | a list of strings | + | | extension depends on | | + +------------------------+--------------------------------+---------------------------+ + | *language* | extension language (i.e. | a string | + | | ``'c'``, ``'c++'``, | | + | | ``'objc'``). Will be detected | | + | | from the source extensions if | | + | | not provided. | | + +------------------------+--------------------------------+---------------------------+ + | *optional* | specifies that a build failure | a boolean | + | | in the extension should not | | + | | abort the build process, but | | + | | simply skip the extension. | | + +------------------------+--------------------------------+---------------------------+ + + .. versionchanged:: 3.8 + + On Unix, C extensions are no longer linked to libpython except on + Android and Cygwin. + + +.. class:: Distribution + + A :class:`Distribution` describes how to build, install and package up a Python + software package. + + See the :func:`setup` function for a list of keyword arguments accepted by the + Distribution constructor. :func:`setup` creates a Distribution instance. + + .. versionchanged:: 3.7 + :class:`~distutils.core.Distribution` now warns if ``classifiers``, + ``keywords`` and ``platforms`` fields are not specified as a list or + a string. + +.. class:: Command + + A :class:`Command` class (or rather, an instance of one of its subclasses) + implement a single distutils command. + + +:mod:`distutils.ccompiler` --- CCompiler base class +=================================================== + +.. module:: distutils.ccompiler + :synopsis: Abstract CCompiler class + + +This module provides the abstract base class for the :class:`CCompiler` +classes. A :class:`CCompiler` instance can be used for all the compile and +link steps needed to build a single project. Methods are provided to set +options for the compiler --- macro definitions, include directories, link path, +libraries and the like. + +This module provides the following functions. + + +.. function:: gen_lib_options(compiler, library_dirs, runtime_library_dirs, libraries) + + Generate linker options for searching library directories and linking with + specific libraries. *libraries* and *library_dirs* are, respectively, lists of + library names (not filenames!) and search directories. Returns a list of + command-line options suitable for use with some compiler (depending on the two + format strings passed in). + + +.. function:: gen_preprocess_options(macros, include_dirs) + + Generate C pre-processor options (:option:`!-D`, :option:`!-U`, :option:`!-I`) as + used by at least two types of compilers: the typical Unix compiler and Visual + C++. *macros* is the usual thing, a list of 1- or 2-tuples, where ``(name,)`` + means undefine (:option:`!-U`) macro *name*, and ``(name, value)`` means define + (:option:`!-D`) macro *name* to *value*. *include_dirs* is just a list of + directory names to be added to the header file search path (:option:`!-I`). + Returns a list of command-line options suitable for either Unix compilers or + Visual C++. + + +.. function:: get_default_compiler(osname, platform) + + Determine the default compiler to use for the given platform. + + *osname* should be one of the standard Python OS names (i.e. the ones returned + by ``os.name``) and *platform* the common value returned by ``sys.platform`` for + the platform in question. + + The default values are ``os.name`` and ``sys.platform`` in case the parameters + are not given. + + +.. function:: new_compiler(plat=None, compiler=None, verbose=0, dry_run=0, force=0) + + Factory function to generate an instance of some CCompiler subclass for the + supplied platform/compiler combination. *plat* defaults to ``os.name`` (eg. + ``'posix'``, ``'nt'``), and *compiler* defaults to the default compiler for + that platform. Currently only ``'posix'`` and ``'nt'`` are supported, and the + default compilers are "traditional Unix interface" (:class:`UnixCCompiler` + class) and Visual C++ (:class:`MSVCCompiler` class). Note that it's perfectly + possible to ask for a Unix compiler object under Windows, and a Microsoft + compiler object under Unix---if you supply a value for *compiler*, *plat* is + ignored. + + .. % Is the posix/nt only thing still true? Mac OS X seems to work, and + .. % returns a UnixCCompiler instance. How to document this... hmm. + + +.. function:: show_compilers() + + Print list of available compilers (used by the :option:`!--help-compiler` options + to :command:`build`, :command:`build_ext`, :command:`build_clib`). + + +.. class:: CCompiler([verbose=0, dry_run=0, force=0]) + + The abstract base class :class:`CCompiler` defines the interface that must be + implemented by real compiler classes. The class also has some utility methods + used by several compiler classes. + + The basic idea behind a compiler abstraction class is that each instance can be + used for all the compile/link steps in building a single project. Thus, + attributes common to all of those compile and link steps --- include + directories, macros to define, libraries to link against, etc. --- are + attributes of the compiler instance. To allow for variability in how individual + files are treated, most of those attributes may be varied on a per-compilation + or per-link basis. + + The constructor for each subclass creates an instance of the Compiler object. + Flags are *verbose* (show verbose output), *dry_run* (don't actually execute the + steps) and *force* (rebuild everything, regardless of dependencies). All of + these flags default to ``0`` (off). Note that you probably don't want to + instantiate :class:`CCompiler` or one of its subclasses directly - use the + :func:`distutils.CCompiler.new_compiler` factory function instead. + + The following methods allow you to manually alter compiler options for the + instance of the Compiler class. + + + .. method:: CCompiler.add_include_dir(dir) + + Add *dir* to the list of directories that will be searched for header files. + The compiler is instructed to search directories in the order in which they are + supplied by successive calls to :meth:`add_include_dir`. + + + .. method:: CCompiler.set_include_dirs(dirs) + + Set the list of directories that will be searched to *dirs* (a list of strings). + Overrides any preceding calls to :meth:`add_include_dir`; subsequent calls to + :meth:`add_include_dir` add to the list passed to :meth:`set_include_dirs`. + This does not affect any list of standard include directories that the compiler + may search by default. + + + .. method:: CCompiler.add_library(libname) + + Add *libname* to the list of libraries that will be included in all links driven + by this compiler object. Note that *libname* should \*not\* be the name of a + file containing a library, but the name of the library itself: the actual + filename will be inferred by the linker, the compiler, or the compiler class + (depending on the platform). + + The linker will be instructed to link against libraries in the order they were + supplied to :meth:`add_library` and/or :meth:`set_libraries`. It is perfectly + valid to duplicate library names; the linker will be instructed to link against + libraries as many times as they are mentioned. + + + .. method:: CCompiler.set_libraries(libnames) + + Set the list of libraries to be included in all links driven by this compiler + object to *libnames* (a list of strings). This does not affect any standard + system libraries that the linker may include by default. + + + .. method:: CCompiler.add_library_dir(dir) + + Add *dir* to the list of directories that will be searched for libraries + specified to :meth:`add_library` and :meth:`set_libraries`. The linker will be + instructed to search for libraries in the order they are supplied to + :meth:`add_library_dir` and/or :meth:`set_library_dirs`. + + + .. method:: CCompiler.set_library_dirs(dirs) + + Set the list of library search directories to *dirs* (a list of strings). This + does not affect any standard library search path that the linker may search by + default. + + + .. method:: CCompiler.add_runtime_library_dir(dir) + + Add *dir* to the list of directories that will be searched for shared libraries + at runtime. + + + .. method:: CCompiler.set_runtime_library_dirs(dirs) + + Set the list of directories to search for shared libraries at runtime to *dirs* + (a list of strings). This does not affect any standard search path that the + runtime linker may search by default. + + + .. method:: CCompiler.define_macro(name[, value=None]) + + Define a preprocessor macro for all compilations driven by this compiler object. + The optional parameter *value* should be a string; if it is not supplied, then + the macro will be defined without an explicit value and the exact outcome + depends on the compiler used. + + .. XXX true? does ANSI say anything about this? + + + .. method:: CCompiler.undefine_macro(name) + + Undefine a preprocessor macro for all compilations driven by this compiler + object. If the same macro is defined by :meth:`define_macro` and + undefined by :meth:`undefine_macro` the last call takes precedence + (including multiple redefinitions or undefinitions). If the macro is + redefined/undefined on a per-compilation basis (ie. in the call to + :meth:`compile`), then that takes precedence. + + + .. method:: CCompiler.add_link_object(object) + + Add *object* to the list of object files (or analogues, such as explicitly named + library files or the output of "resource compilers") to be included in every + link driven by this compiler object. + + + .. method:: CCompiler.set_link_objects(objects) + + Set the list of object files (or analogues) to be included in every link to + *objects*. This does not affect any standard object files that the linker may + include by default (such as system libraries). + + The following methods implement methods for autodetection of compiler options, + providing some functionality similar to GNU :program:`autoconf`. + + + .. method:: CCompiler.detect_language(sources) + + Detect the language of a given file, or list of files. Uses the instance + attributes :attr:`language_map` (a dictionary), and :attr:`language_order` (a + list) to do the job. + + + .. method:: CCompiler.find_library_file(dirs, lib[, debug=0]) + + Search the specified list of directories for a static or shared library file + *lib* and return the full path to that file. If *debug* is true, look for a + debugging version (if that makes sense on the current platform). Return + ``None`` if *lib* wasn't found in any of the specified directories. + + + .. method:: CCompiler.has_function(funcname [, includes=None, include_dirs=None, libraries=None, library_dirs=None]) + + Return a boolean indicating whether *funcname* is supported on the current + platform. The optional arguments can be used to augment the compilation + environment by providing additional include files and paths and libraries and + paths. + + + .. method:: CCompiler.library_dir_option(dir) + + Return the compiler option to add *dir* to the list of directories searched for + libraries. + + + .. method:: CCompiler.library_option(lib) + + Return the compiler option to add *lib* to the list of libraries linked into the + shared library or executable. + + + .. method:: CCompiler.runtime_library_dir_option(dir) + + Return the compiler option to add *dir* to the list of directories searched for + runtime libraries. + + + .. method:: CCompiler.set_executables(**args) + + Define the executables (and options for them) that will be run to perform the + various stages of compilation. The exact set of executables that may be + specified here depends on the compiler class (via the 'executables' class + attribute), but most will have: + + +--------------+------------------------------------------+ + | attribute | description | + +==============+==========================================+ + | *compiler* | the C/C++ compiler | + +--------------+------------------------------------------+ + | *linker_so* | linker used to create shared objects and | + | | libraries | + +--------------+------------------------------------------+ + | *linker_exe* | linker used to create binary executables | + +--------------+------------------------------------------+ + | *archiver* | static library creator | + +--------------+------------------------------------------+ + + On platforms with a command-line (Unix, DOS/Windows), each of these is a string + that will be split into executable name and (optional) list of arguments. + (Splitting the string is done similarly to how Unix shells operate: words are + delimited by spaces, but quotes and backslashes can override this. See + :func:`distutils.util.split_quoted`.) + + The following methods invoke stages in the build process. + + + .. method:: CCompiler.compile(sources[, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, depends=None]) + + Compile one or more source files. Generates object files (e.g. transforms a + :file:`.c` file to a :file:`.o` file.) + + *sources* must be a list of filenames, most likely C/C++ files, but in reality + anything that can be handled by a particular compiler and compiler class (eg. + :class:`MSVCCompiler` can handle resource files in *sources*). Return a list of + object filenames, one per source filename in *sources*. Depending on the + implementation, not all source files will necessarily be compiled, but all + corresponding object filenames will be returned. + + If *output_dir* is given, object files will be put under it, while retaining + their original path component. That is, :file:`foo/bar.c` normally compiles to + :file:`foo/bar.o` (for a Unix implementation); if *output_dir* is *build*, then + it would compile to :file:`build/foo/bar.o`. + + *macros*, if given, must be a list of macro definitions. A macro definition is + either a ``(name, value)`` 2-tuple or a ``(name,)`` 1-tuple. The former defines + a macro; if the value is ``None``, the macro is defined without an explicit + value. The 1-tuple case undefines a macro. Later + definitions/redefinitions/undefinitions take precedence. + + *include_dirs*, if given, must be a list of strings, the directories to add to + the default include file search path for this compilation only. + + *debug* is a boolean; if true, the compiler will be instructed to output debug + symbols in (or alongside) the object file(s). + + *extra_preargs* and *extra_postargs* are implementation-dependent. On platforms + that have the notion of a command-line (e.g. Unix, DOS/Windows), they are most + likely lists of strings: extra command-line arguments to prepend/append to the + compiler command line. On other platforms, consult the implementation class + documentation. In any event, they are intended as an escape hatch for those + occasions when the abstract compiler framework doesn't cut the mustard. + + *depends*, if given, is a list of filenames that all targets depend on. If a + source file is older than any file in depends, then the source file will be + recompiled. This supports dependency tracking, but only at a coarse + granularity. + + Raises :exc:`CompileError` on failure. + + + .. method:: CCompiler.create_static_lib(objects, output_libname[, output_dir=None, debug=0, target_lang=None]) + + Link a bunch of stuff together to create a static library file. The "bunch of + stuff" consists of the list of object files supplied as *objects*, the extra + object files supplied to :meth:`add_link_object` and/or + :meth:`set_link_objects`, the libraries supplied to :meth:`add_library` and/or + :meth:`set_libraries`, and the libraries supplied as *libraries* (if any). + + *output_libname* should be a library name, not a filename; the filename will be + inferred from the library name. *output_dir* is the directory where the library + file will be put. + + .. XXX defaults to what? + + *debug* is a boolean; if true, debugging information will be included in the + library (note that on most platforms, it is the compile step where this matters: + the *debug* flag is included here just for consistency). + + *target_lang* is the target language for which the given objects are being + compiled. This allows specific linkage time treatment of certain languages. + + Raises :exc:`LibError` on failure. + + + .. method:: CCompiler.link(target_desc, objects, output_filename[, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None]) + + Link a bunch of stuff together to create an executable or shared library file. + + The "bunch of stuff" consists of the list of object files supplied as *objects*. + *output_filename* should be a filename. If *output_dir* is supplied, + *output_filename* is relative to it (i.e. *output_filename* can provide + directory components if needed). + + *libraries* is a list of libraries to link against. These are library names, + not filenames, since they're translated into filenames in a platform-specific + way (eg. *foo* becomes :file:`libfoo.a` on Unix and :file:`foo.lib` on + DOS/Windows). However, they can include a directory component, which means the + linker will look in that specific directory rather than searching all the normal + locations. + + *library_dirs*, if supplied, should be a list of directories to search for + libraries that were specified as bare library names (ie. no directory + component). These are on top of the system default and those supplied to + :meth:`add_library_dir` and/or :meth:`set_library_dirs`. *runtime_library_dirs* + is a list of directories that will be embedded into the shared library and used + to search for other shared libraries that \*it\* depends on at run-time. (This + may only be relevant on Unix.) + + *export_symbols* is a list of symbols that the shared library will export. + (This appears to be relevant only on Windows.) + + *debug* is as for :meth:`compile` and :meth:`create_static_lib`, with the + slight distinction that it actually matters on most platforms (as opposed to + :meth:`create_static_lib`, which includes a *debug* flag mostly for form's + sake). + + *extra_preargs* and *extra_postargs* are as for :meth:`compile` (except of + course that they supply command-line arguments for the particular linker being + used). + + *target_lang* is the target language for which the given objects are being + compiled. This allows specific linkage time treatment of certain languages. + + Raises :exc:`LinkError` on failure. + + + .. method:: CCompiler.link_executable(objects, output_progname[, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, target_lang=None]) + + Link an executable. *output_progname* is the name of the file executable, while + *objects* are a list of object filenames to link in. Other arguments are as for + the :meth:`link` method. + + + .. method:: CCompiler.link_shared_lib(objects, output_libname[, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None]) + + Link a shared library. *output_libname* is the name of the output library, + while *objects* is a list of object filenames to link in. Other arguments are + as for the :meth:`link` method. + + + .. method:: CCompiler.link_shared_object(objects, output_filename[, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None]) + + Link a shared object. *output_filename* is the name of the shared object that + will be created, while *objects* is a list of object filenames to link in. + Other arguments are as for the :meth:`link` method. + + + .. method:: CCompiler.preprocess(source[, output_file=None, macros=None, include_dirs=None, extra_preargs=None, extra_postargs=None]) + + Preprocess a single C/C++ source file, named in *source*. Output will be written + to file named *output_file*, or *stdout* if *output_file* not supplied. + *macros* is a list of macro definitions as for :meth:`compile`, which will + augment the macros set with :meth:`define_macro` and :meth:`undefine_macro`. + *include_dirs* is a list of directory names that will be added to the default + list, in the same way as :meth:`add_include_dir`. + + Raises :exc:`PreprocessError` on failure. + + The following utility methods are defined by the :class:`CCompiler` class, for + use by the various concrete subclasses. + + + .. method:: CCompiler.executable_filename(basename[, strip_dir=0, output_dir='']) + + Returns the filename of the executable for the given *basename*. Typically for + non-Windows platforms this is the same as the basename, while Windows will get + a :file:`.exe` added. + + + .. method:: CCompiler.library_filename(libname[, lib_type='static', strip_dir=0, output_dir='']) + + Returns the filename for the given library name on the current platform. On Unix + a library with *lib_type* of ``'static'`` will typically be of the form + :file:`liblibname.a`, while a *lib_type* of ``'dynamic'`` will be of the form + :file:`liblibname.so`. + + + .. method:: CCompiler.object_filenames(source_filenames[, strip_dir=0, output_dir='']) + + Returns the name of the object files for the given source files. + *source_filenames* should be a list of filenames. + + + .. method:: CCompiler.shared_object_filename(basename[, strip_dir=0, output_dir='']) + + Returns the name of a shared object file for the given file name *basename*. + + + .. method:: CCompiler.execute(func, args[, msg=None, level=1]) + + Invokes :func:`distutils.util.execute`. This method invokes a Python function + *func* with the given arguments *args*, after logging and taking into account + the *dry_run* flag. + + + .. method:: CCompiler.spawn(cmd) + + Invokes :func:`distutils.util.spawn`. This invokes an external process to run + the given command. + + + .. method:: CCompiler.mkpath(name[, mode=511]) + + Invokes :func:`distutils.dir_util.mkpath`. This creates a directory and any + missing ancestor directories. + + + .. method:: CCompiler.move_file(src, dst) + + Invokes :meth:`distutils.file_util.move_file`. Renames *src* to *dst*. + + + .. method:: CCompiler.announce(msg[, level=1]) + + Write a message using :func:`distutils.log.debug`. + + + .. method:: CCompiler.warn(msg) + + Write a warning message *msg* to standard error. + + + .. method:: CCompiler.debug_print(msg) + + If the *debug* flag is set on this :class:`CCompiler` instance, print *msg* to + standard output, otherwise do nothing. + +.. % \subsection{Compiler-specific modules} +.. % +.. % The following modules implement concrete subclasses of the abstract +.. % \class{CCompiler} class. They should not be instantiated directly, but should +.. % be created using \function{distutils.ccompiler.new_compiler()} factory +.. % function. + + +:mod:`distutils.unixccompiler` --- Unix C Compiler +================================================== + +.. module:: distutils.unixccompiler + :synopsis: UNIX C Compiler + + +This module provides the :class:`UnixCCompiler` class, a subclass of +:class:`CCompiler` that handles the typical Unix-style command-line C compiler: + +* macros defined with :option:`!-Dname[=value]` + +* macros undefined with :option:`!-Uname` + +* include search directories specified with :option:`!-Idir` + +* libraries specified with :option:`!-llib` + +* library search directories specified with :option:`!-Ldir` + +* compile handled by :program:`cc` (or similar) executable with :option:`!-c` + option: compiles :file:`.c` to :file:`.o` + +* link static library handled by :program:`ar` command (possibly with + :program:`ranlib`) + +* link shared library handled by :program:`cc` :option:`!-shared` + + +:mod:`distutils.msvccompiler` --- Microsoft Compiler +==================================================== + +.. module:: distutils.msvccompiler + :synopsis: Microsoft Compiler + +.. XXX: This is *waaaaay* out of date! + +This module provides :class:`MSVCCompiler`, an implementation of the abstract +:class:`CCompiler` class for Microsoft Visual Studio. Typically, extension +modules need to be compiled with the same compiler that was used to compile +Python. For Python 2.3 and earlier, the compiler was Visual Studio 6. For Python +2.4 and 2.5, the compiler is Visual Studio .NET 2003. + +:class:`MSVCCompiler` will normally choose the right compiler, linker etc. on +its own. To override this choice, the environment variables *DISTUTILS_USE_SDK* +and *MSSdk* must be both set. *MSSdk* indicates that the current environment has +been setup by the SDK's ``SetEnv.Cmd`` script, or that the environment variables +had been registered when the SDK was installed; *DISTUTILS_USE_SDK* indicates +that the distutils user has made an explicit choice to override the compiler +selection by :class:`MSVCCompiler`. + + +:mod:`distutils.bcppcompiler` --- Borland Compiler +================================================== + +.. module:: distutils.bcppcompiler + + +This module provides :class:`BorlandCCompiler`, a subclass of the abstract +:class:`CCompiler` class for the Borland C++ compiler. + + +:mod:`distutils.cygwincompiler` --- Cygwin Compiler +=================================================== + +.. module:: distutils.cygwinccompiler + + +This module provides the :class:`CygwinCCompiler` class, a subclass of +:class:`UnixCCompiler` that handles the Cygwin port of the GNU C compiler to +Windows. It also contains the Mingw32CCompiler class which handles the mingw32 +port of GCC (same as cygwin in no-cygwin mode). + + +:mod:`distutils.archive_util` --- Archiving utilities +====================================================== + +.. module:: distutils.archive_util + :synopsis: Utility functions for creating archive files (tarballs, zip files, ...) + + +This module provides a few functions for creating archive files, such as +tarballs or zipfiles. + + +.. function:: make_archive(base_name, format[, root_dir=None, base_dir=None, verbose=0, dry_run=0]) + + Create an archive file (eg. ``zip`` or ``tar``). *base_name* is the name of + the file to create, minus any format-specific extension; *format* is the + archive format: one of ``zip``, ``tar``, ``gztar``, ``bztar``, ``xztar``, or + ``ztar``. *root_dir* is a directory that will be the root directory of the + archive; ie. we typically ``chdir`` into *root_dir* before creating the + archive. *base_dir* is the directory where we start archiving from; ie. + *base_dir* will be the common prefix of all files and directories in the + archive. *root_dir* and *base_dir* both default to the current directory. + Returns the name of the archive file. + + .. versionchanged:: 3.5 + Added support for the ``xztar`` format. + + +.. function:: make_tarball(base_name, base_dir[, compress='gzip', verbose=0, dry_run=0]) + + 'Create an (optional compressed) archive as a tar file from all files in and + under *base_dir*. *compress* must be ``'gzip'`` (the default), + ``'bzip2'``, ``'xz'``, ``'compress'``, or ``None``. For the ``'compress'`` + method the compression utility named by :program:`compress` must be on the + default program search path, so this is probably Unix-specific. The output + tar file will be named :file:`base_dir.tar`, possibly plus the appropriate + compression extension (``.gz``, ``.bz2``, ``.xz`` or ``.Z``). Return the + output filename. + + .. versionchanged:: 3.5 + Added support for the ``xz`` compression. + + +.. function:: make_zipfile(base_name, base_dir[, verbose=0, dry_run=0]) + + Create a zip file from all files in and under *base_dir*. The output zip file + will be named *base_name* + :file:`.zip`. Uses either the :mod:`zipfile` Python + module (if available) or the InfoZIP :file:`zip` utility (if installed and + found on the default search path). If neither tool is available, raises + :exc:`DistutilsExecError`. Returns the name of the output zip file. + + +:mod:`distutils.dep_util` --- Dependency checking +================================================= + +.. module:: distutils.dep_util + :synopsis: Utility functions for simple dependency checking + + +This module provides functions for performing simple, timestamp-based +dependency of files and groups of files; also, functions based entirely on such +timestamp dependency analysis. + + +.. function:: newer(source, target) + + Return true if *source* exists and is more recently modified than *target*, or + if *source* exists and *target* doesn't. Return false if both exist and *target* + is the same age or newer than *source*. Raise :exc:`DistutilsFileError` if + *source* does not exist. + + +.. function:: newer_pairwise(sources, targets) + + Walk two filename lists in parallel, testing if each source is newer than its + corresponding target. Return a pair of lists (*sources*, *targets*) where + source is newer than target, according to the semantics of :func:`newer`. + + .. % % equivalent to a listcomp... + + +.. function:: newer_group(sources, target[, missing='error']) + + Return true if *target* is out-of-date with respect to any file listed in + *sources*. In other words, if *target* exists and is newer than every file in + *sources*, return false; otherwise return true. *missing* controls what we do + when a source file is missing; the default (``'error'``) is to blow up with an + :exc:`OSError` from inside :func:`os.stat`; if it is ``'ignore'``, we silently + drop any missing source files; if it is ``'newer'``, any missing source files + make us assume that *target* is out-of-date (this is handy in "dry-run" mode: + it'll make you pretend to carry out commands that wouldn't work because inputs + are missing, but that doesn't matter because you're not actually going to run + the commands). + + +:mod:`distutils.dir_util` --- Directory tree operations +======================================================= + +.. module:: distutils.dir_util + :synopsis: Utility functions for operating on directories and directory trees + + +This module provides functions for operating on directories and trees of +directories. + + +.. function:: mkpath(name[, mode=0o777, verbose=0, dry_run=0]) + + Create a directory and any missing ancestor directories. If the directory + already exists (or if *name* is the empty string, which means the current + directory, which of course exists), then do nothing. Raise + :exc:`DistutilsFileError` if unable to create some directory along the way (eg. + some sub-path exists, but is a file rather than a directory). If *verbose* is + true, print a one-line summary of each mkdir to stdout. Return the list of + directories actually created. + + +.. function:: create_tree(base_dir, files[, mode=0o777, verbose=0, dry_run=0]) + + Create all the empty directories under *base_dir* needed to put *files* there. + *base_dir* is just the name of a directory which doesn't necessarily exist + yet; *files* is a list of filenames to be interpreted relative to *base_dir*. + *base_dir* + the directory portion of every file in *files* will be created if + it doesn't already exist. *mode*, *verbose* and *dry_run* flags are as for + :func:`mkpath`. + + +.. function:: copy_tree(src, dst[, preserve_mode=1, preserve_times=1, preserve_symlinks=0, update=0, verbose=0, dry_run=0]) + + Copy an entire directory tree *src* to a new location *dst*. Both *src* and + *dst* must be directory names. If *src* is not a directory, raise + :exc:`DistutilsFileError`. If *dst* does not exist, it is created with + :func:`mkpath`. The end result of the copy is that every file in *src* is + copied to *dst*, and directories under *src* are recursively copied to *dst*. + Return the list of files that were copied or might have been copied, using their + output name. The return value is unaffected by *update* or *dry_run*: it is + simply the list of all files under *src*, with the names changed to be under + *dst*. + + *preserve_mode* and *preserve_times* are the same as for + :func:`distutils.file_util.copy_file`; note that they only apply to + regular files, not to + directories. If *preserve_symlinks* is true, symlinks will be copied as + symlinks (on platforms that support them!); otherwise (the default), the + destination of the symlink will be copied. *update* and *verbose* are the same + as for :func:`copy_file`. + + Files in *src* that begin with :file:`.nfs` are skipped (more information on + these files is available in answer D2 of the `NFS FAQ page + <http://nfs.sourceforge.net/#section_d>`_). + + .. versionchanged:: 3.3.1 + NFS files are ignored. + +.. function:: remove_tree(directory[, verbose=0, dry_run=0]) + + Recursively remove *directory* and all files and directories underneath it. Any + errors are ignored (apart from being reported to ``sys.stdout`` if *verbose* is + true). + + +:mod:`distutils.file_util` --- Single file operations +===================================================== + +.. module:: distutils.file_util + :synopsis: Utility functions for operating on single files + + +This module contains some utility functions for operating on individual files. + + +.. function:: copy_file(src, dst[, preserve_mode=1, preserve_times=1, update=0, link=None, verbose=0, dry_run=0]) + + Copy file *src* to *dst*. If *dst* is a directory, then *src* is copied there + with the same name; otherwise, it must be a filename. (If the file exists, it + will be ruthlessly clobbered.) If *preserve_mode* is true (the default), the + file's mode (type and permission bits, or whatever is analogous on the + current platform) is copied. If *preserve_times* is true (the default), the + last-modified and last-access times are copied as well. If *update* is true, + *src* will only be copied if *dst* does not exist, or if *dst* does exist but + is older than *src*. + + *link* allows you to make hard links (using :func:`os.link`) or symbolic links + (using :func:`os.symlink`) instead of copying: set it to ``'hard'`` or + ``'sym'``; if it is ``None`` (the default), files are copied. Don't set *link* + on systems that don't support it: :func:`copy_file` doesn't check if hard or + symbolic linking is available. It uses :func:`_copy_file_contents` to copy file + contents. + + Return a tuple ``(dest_name, copied)``: *dest_name* is the actual name of the + output file, and *copied* is true if the file was copied (or would have been + copied, if *dry_run* true). + + .. % XXX if the destination file already exists, we clobber it if + .. % copying, but blow up if linking. Hmmm. And I don't know what + .. % macostools.copyfile() does. Should definitely be consistent, and + .. % should probably blow up if destination exists and we would be + .. % changing it (ie. it's not already a hard/soft link to src OR + .. % (not update) and (src newer than dst)). + + +.. function:: move_file(src, dst[, verbose, dry_run]) + + Move file *src* to *dst*. If *dst* is a directory, the file will be moved into + it with the same name; otherwise, *src* is just renamed to *dst*. Returns the + new full name of the file. + + .. warning:: + + Handles cross-device moves on Unix using :func:`copy_file`. What about + other systems? + + +.. function:: write_file(filename, contents) + + Create a file called *filename* and write *contents* (a sequence of strings + without line terminators) to it. + + +:mod:`distutils.util` --- Miscellaneous other utility functions +=============================================================== + +.. module:: distutils.util + :synopsis: Miscellaneous other utility functions + + +This module contains other assorted bits and pieces that don't fit into any +other utility module. + + +.. function:: get_platform() + + Return a string that identifies the current platform. This is used mainly to + distinguish platform-specific build directories and platform-specific built + distributions. Typically includes the OS name and version and the + architecture (as supplied by 'os.uname()'), although the exact information + included depends on the OS; e.g., on Linux, the kernel version isn't + particularly important. + + Examples of returned values: + + * ``linux-i586`` + * ``linux-alpha`` + * ``solaris-2.6-sun4u`` + + For non-POSIX platforms, currently just returns ``sys.platform``. + + For Mac OS X systems the OS version reflects the minimal version on which + binaries will run (that is, the value of ``MACOSX_DEPLOYMENT_TARGET`` + during the build of Python), not the OS version of the current system. + + For universal binary builds on Mac OS X the architecture value reflects + the universal binary status instead of the architecture of the current + processor. For 32-bit universal binaries the architecture is ``fat``, + for 64-bit universal binaries the architecture is ``fat64``, and + for 4-way universal binaries the architecture is ``universal``. Starting + from Python 2.7 and Python 3.2 the architecture ``fat3`` is used for + a 3-way universal build (ppc, i386, x86_64) and ``intel`` is used for + a universal build with the i386 and x86_64 architectures + + Examples of returned values on Mac OS X: + + * ``macosx-10.3-ppc`` + + * ``macosx-10.3-fat`` + + * ``macosx-10.5-universal`` + + * ``macosx-10.6-intel`` + + For AIX, Python 3.9 and later return a string starting with "aix", followed + by additional fields (separated by ``'-'``) that represent the combined + values of AIX Version, Release and Technology Level (first field), Build Date + (second field), and bit-size (third field). Python 3.8 and earlier returned + only a single additional field with the AIX Version and Release. + + Examples of returned values on AIX: + + * ``aix-5307-0747-32`` # 32-bit build on AIX ``oslevel -s``: 5300-07-00-0000 + + * ``aix-7105-1731-64`` # 64-bit build on AIX ``oslevel -s``: 7100-05-01-1731 + + * ``aix-7.2`` # Legacy form reported in Python 3.8 and earlier + + .. versionchanged:: 3.9 + The AIX platform string format now also includes the technology level, + build date, and ABI bit-size. + + +.. function:: convert_path(pathname) + + Return 'pathname' as a name that will work on the native filesystem, i.e. split + it on '/' and put it back together again using the current directory separator. + Needed because filenames in the setup script are always supplied in Unix style, + and have to be converted to the local convention before we can actually use them + in the filesystem. Raises :exc:`ValueError` on non-Unix-ish systems if + *pathname* either starts or ends with a slash. + + +.. function:: change_root(new_root, pathname) + + Return *pathname* with *new_root* prepended. If *pathname* is relative, this is + equivalent to ``os.path.join(new_root,pathname)`` Otherwise, it requires making + *pathname* relative and then joining the two, which is tricky on DOS/Windows. + + +.. function:: check_environ() + + Ensure that 'os.environ' has all the environment variables we guarantee that + users can use in config files, command-line options, etc. Currently this + includes: + + * :envvar:`HOME` - user's home directory (Unix only) + * :envvar:`PLAT` - description of the current platform, including hardware and + OS (see :func:`get_platform`) + + +.. function:: subst_vars(s, local_vars) + + Perform shell/Perl-style variable substitution on *s*. Every occurrence of + ``$`` followed by a name is considered a variable, and variable is substituted + by the value found in the *local_vars* dictionary, or in ``os.environ`` if it's + not in *local_vars*. *os.environ* is first checked/augmented to guarantee that + it contains certain values: see :func:`check_environ`. Raise :exc:`ValueError` + for any variables not found in either *local_vars* or ``os.environ``. + + Note that this is not a fully-fledged string interpolation function. A valid + ``$variable`` can consist only of upper and lower case letters, numbers and an + underscore. No { } or ( ) style quoting is available. + + +.. function:: split_quoted(s) + + Split a string up according to Unix shell-like rules for quotes and backslashes. + In short: words are delimited by spaces, as long as those spaces are not escaped + by a backslash, or inside a quoted string. Single and double quotes are + equivalent, and the quote characters can be backslash-escaped. The backslash is + stripped from any two-character escape sequence, leaving only the escaped + character. The quote characters are stripped from any quoted string. Returns a + list of words. + + .. % Should probably be moved into the standard library. + + +.. function:: execute(func, args[, msg=None, verbose=0, dry_run=0]) + + Perform some action that affects the outside world (for instance, writing to the + filesystem). Such actions are special because they are disabled by the + *dry_run* flag. This method takes care of all that bureaucracy for you; all + you have to do is supply the function to call and an argument tuple for it (to + embody the "external action" being performed), and an optional message to print. + + +.. function:: strtobool(val) + + Convert a string representation of truth to true (1) or false (0). + + True values are ``y``, ``yes``, ``t``, ``true``, ``on`` and ``1``; false values + are ``n``, ``no``, ``f``, ``false``, ``off`` and ``0``. Raises + :exc:`ValueError` if *val* is anything else. + + +.. function:: byte_compile(py_files[, optimize=0, force=0, prefix=None, base_dir=None, verbose=1, dry_run=0, direct=None]) + + Byte-compile a collection of Python source files to :file:`.pyc` files in a + :file:`__pycache__` subdirectory (see :pep:`3147` and :pep:`488`). + *py_files* is a list of files to compile; any files that don't end in + :file:`.py` are silently skipped. *optimize* must be one of the following: + + * ``0`` - don't optimize + * ``1`` - normal optimization (like ``python -O``) + * ``2`` - extra optimization (like ``python -OO``) + + If *force* is true, all files are recompiled regardless of timestamps. + + The source filename encoded in each :term:`bytecode` file defaults to the filenames + listed in *py_files*; you can modify these with *prefix* and *basedir*. + *prefix* is a string that will be stripped off of each source filename, and + *base_dir* is a directory name that will be prepended (after *prefix* is + stripped). You can supply either or both (or neither) of *prefix* and + *base_dir*, as you wish. + + If *dry_run* is true, doesn't actually do anything that would affect the + filesystem. + + Byte-compilation is either done directly in this interpreter process with the + standard :mod:`py_compile` module, or indirectly by writing a temporary script + and executing it. Normally, you should let :func:`byte_compile` figure out to + use direct compilation or not (see the source for details). The *direct* flag + is used by the script generated in indirect mode; unless you know what you're + doing, leave it set to ``None``. + + .. versionchanged:: 3.2.3 + Create ``.pyc`` files with an :func:`import magic tag + <imp.get_tag>` in their name, in a :file:`__pycache__` subdirectory + instead of files without tag in the current directory. + + .. versionchanged:: 3.5 + Create ``.pyc`` files according to :pep:`488`. + + +.. function:: rfc822_escape(header) + + Return a version of *header* escaped for inclusion in an :rfc:`822` header, by + ensuring there are 8 spaces space after each newline. Note that it does no other + modification of the string. + + .. % this _can_ be replaced + +.. % \subsection{Distutils objects} + + +:mod:`distutils.dist` --- The Distribution class +================================================ + +.. module:: distutils.dist + :synopsis: Provides the Distribution class, which represents the module distribution being + built/installed/distributed + + +This module provides the :class:`~distutils.core.Distribution` class, which +represents the module distribution being built/installed/distributed. + + +:mod:`distutils.extension` --- The Extension class +================================================== + +.. module:: distutils.extension + :synopsis: Provides the Extension class, used to describe C/C++ extension modules in setup + scripts + + +This module provides the :class:`Extension` class, used to describe C/C++ +extension modules in setup scripts. + +.. % \subsection{Ungrouped modules} +.. % The following haven't been moved into a more appropriate section yet. + + +:mod:`distutils.debug` --- Distutils debug mode +=============================================== + +.. module:: distutils.debug + :synopsis: Provides the debug flag for distutils + + +This module provides the DEBUG flag. + + +:mod:`distutils.errors` --- Distutils exceptions +================================================ + +.. module:: distutils.errors + :synopsis: Provides standard distutils exceptions + + +Provides exceptions used by the Distutils modules. Note that Distutils modules +may raise standard exceptions; in particular, SystemExit is usually raised for +errors that are obviously the end-user's fault (eg. bad command-line arguments). + +This module is safe to use in ``from ... import *`` mode; it only exports +symbols whose names start with ``Distutils`` and end with ``Error``. + + +:mod:`distutils.fancy_getopt` --- Wrapper around the standard getopt module +=========================================================================== + +.. module:: distutils.fancy_getopt + :synopsis: Additional getopt functionality + + +This module provides a wrapper around the standard :mod:`getopt` module that +provides the following additional features: + +* short and long options are tied together + +* options have help strings, so :func:`fancy_getopt` could potentially create a + complete usage summary + +* options set attributes of a passed-in object + +* boolean options can have "negative aliases" --- eg. if :option:`!--quiet` is + the "negative alias" of :option:`!--verbose`, then :option:`!--quiet` on the + command line sets *verbose* to false. + +.. function:: fancy_getopt(options, negative_opt, object, args) + + Wrapper function. *options* is a list of ``(long_option, short_option, + help_string)`` 3-tuples as described in the constructor for + :class:`FancyGetopt`. *negative_opt* should be a dictionary mapping option names + to option names, both the key and value should be in the *options* list. + *object* is an object which will be used to store values (see the :meth:`getopt` + method of the :class:`FancyGetopt` class). *args* is the argument list. Will use + ``sys.argv[1:]`` if you pass ``None`` as *args*. + + +.. function:: wrap_text(text, width) + + Wraps *text* to less than *width* wide. + + +.. class:: FancyGetopt([option_table=None]) + + The option_table is a list of 3-tuples: ``(long_option, short_option, + help_string)`` + + If an option takes an argument, its *long_option* should have ``'='`` appended; + *short_option* should just be a single character, no ``':'`` in any case. + *short_option* should be ``None`` if a *long_option* doesn't have a + corresponding *short_option*. All option tuples must have long options. + +The :class:`FancyGetopt` class provides the following methods: + + +.. method:: FancyGetopt.getopt([args=None, object=None]) + + Parse command-line options in args. Store as attributes on *object*. + + If *args* is ``None`` or not supplied, uses ``sys.argv[1:]``. If *object* is + ``None`` or not supplied, creates a new :class:`OptionDummy` instance, stores + option values there, and returns a tuple ``(args, object)``. If *object* is + supplied, it is modified in place and :func:`getopt` just returns *args*; in + both cases, the returned *args* is a modified copy of the passed-in *args* list, + which is left untouched. + + .. % and args returned are? + + +.. method:: FancyGetopt.get_option_order() + + Returns the list of ``(option, value)`` tuples processed by the previous run of + :meth:`getopt` Raises :exc:`RuntimeError` if :meth:`getopt` hasn't been called + yet. + + +.. method:: FancyGetopt.generate_help([header=None]) + + Generate help text (a list of strings, one per suggested line of output) from + the option table for this :class:`FancyGetopt` object. + + If supplied, prints the supplied *header* at the top of the help. + + +:mod:`distutils.filelist` --- The FileList class +================================================ + +.. module:: distutils.filelist + :synopsis: The FileList class, used for poking about the file system and + building lists of files. + + +This module provides the :class:`FileList` class, used for poking about the +filesystem and building lists of files. + + +:mod:`distutils.log` --- Simple :pep:`282`-style logging +======================================================== + +.. module:: distutils.log + :synopsis: A simple logging mechanism, :pep:`282`-style + + +:mod:`distutils.spawn` --- Spawn a sub-process +============================================== + +.. module:: distutils.spawn + :synopsis: Provides the spawn() function + + +This module provides the :func:`spawn` function, a front-end to various +platform-specific functions for launching another program in a sub-process. +Also provides :func:`find_executable` to search the path for a given executable +name. + + +:mod:`distutils.sysconfig` --- System configuration information +=============================================================== + +.. module:: distutils.sysconfig + :synopsis: Low-level access to configuration information of the Python interpreter. +.. moduleauthor:: Fred L. Drake, Jr. <fdrake@acm.org> +.. moduleauthor:: Greg Ward <gward@python.net> +.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org> + + +The :mod:`distutils.sysconfig` module provides access to Python's low-level +configuration information. The specific configuration variables available +depend heavily on the platform and configuration. The specific variables depend +on the build process for the specific version of Python being run; the variables +are those found in the :file:`Makefile` and configuration header that are +installed with Python on Unix systems. The configuration header is called +:file:`pyconfig.h` for Python versions starting with 2.2, and :file:`config.h` +for earlier versions of Python. + +Some additional functions are provided which perform some useful manipulations +for other parts of the :mod:`distutils` package. + + +.. data:: PREFIX + + The result of ``os.path.normpath(sys.prefix)``. + + +.. data:: EXEC_PREFIX + + The result of ``os.path.normpath(sys.exec_prefix)``. + + +.. function:: get_config_var(name) + + Return the value of a single variable. This is equivalent to + ``get_config_vars().get(name)``. + + +.. function:: get_config_vars(...) + + Return a set of variable definitions. If there are no arguments, this returns a + dictionary mapping names of configuration variables to values. If arguments are + provided, they should be strings, and the return value will be a sequence giving + the associated values. If a given name does not have a corresponding value, + ``None`` will be included for that variable. + + +.. function:: get_config_h_filename() + + Return the full path name of the configuration header. For Unix, this will be + the header generated by the :program:`configure` script; for other platforms the + header will have been supplied directly by the Python source distribution. The + file is a platform-specific text file. + + +.. function:: get_makefile_filename() + + Return the full path name of the :file:`Makefile` used to build Python. For + Unix, this will be a file generated by the :program:`configure` script; the + meaning for other platforms will vary. The file is a platform-specific text + file, if it exists. This function is only useful on POSIX platforms. + + +.. function:: get_python_inc([plat_specific[, prefix]]) + + Return the directory for either the general or platform-dependent C include + files. If *plat_specific* is true, the platform-dependent include directory is + returned; if false or omitted, the platform-independent directory is returned. + If *prefix* is given, it is used as either the prefix instead of + :const:`PREFIX`, or as the exec-prefix instead of :const:`EXEC_PREFIX` if + *plat_specific* is true. + + +.. function:: get_python_lib([plat_specific[, standard_lib[, prefix]]]) + + Return the directory for either the general or platform-dependent library + installation. If *plat_specific* is true, the platform-dependent include + directory is returned; if false or omitted, the platform-independent directory + is returned. If *prefix* is given, it is used as either the prefix instead of + :const:`PREFIX`, or as the exec-prefix instead of :const:`EXEC_PREFIX` if + *plat_specific* is true. If *standard_lib* is true, the directory for the + standard library is returned rather than the directory for the installation of + third-party extensions. + +The following function is only intended for use within the :mod:`distutils` +package. + + +.. function:: customize_compiler(compiler) + + Do any platform-specific customization of a + :class:`distutils.ccompiler.CCompiler` instance. + + This function is only needed on Unix at this time, but should be called + consistently to support forward-compatibility. It inserts the information that + varies across Unix flavors and is stored in Python's :file:`Makefile`. This + information includes the selected compiler, compiler and linker options, and the + extension used by the linker for shared objects. + +This function is even more special-purpose, and should only be used from +Python's own build procedures. + + +.. function:: set_python_build() + + Inform the :mod:`distutils.sysconfig` module that it is being used as part of + the build process for Python. This changes a lot of relative locations for + files, allowing them to be located in the build area rather than in an installed + Python. + + +:mod:`distutils.text_file` --- The TextFile class +================================================= + +.. module:: distutils.text_file + :synopsis: Provides the TextFile class, a simple interface to text files + + +This module provides the :class:`TextFile` class, which gives an interface to +text files that (optionally) takes care of stripping comments, ignoring blank +lines, and joining lines with backslashes. + + +.. class:: TextFile([filename=None, file=None, **options]) + + This class provides a file-like object that takes care of all the things you + commonly want to do when processing a text file that has some line-by-line + syntax: strip comments (as long as ``#`` is your comment character), skip blank + lines, join adjacent lines by escaping the newline (ie. backslash at end of + line), strip leading and/or trailing whitespace. All of these are optional and + independently controllable. + + The class provides a :meth:`warn` method so you can generate warning messages + that report physical line number, even if the logical line in question spans + multiple physical lines. Also provides :meth:`unreadline` for implementing + line-at-a-time lookahead. + + :class:`TextFile` instances are create with either *filename*, *file*, or both. + :exc:`RuntimeError` is raised if both are ``None``. *filename* should be a + string, and *file* a file object (or something that provides :meth:`readline` + and :meth:`close` methods). It is recommended that you supply at least + *filename*, so that :class:`TextFile` can include it in warning messages. If + *file* is not supplied, :class:`TextFile` creates its own using the + :func:`open` built-in function. + + The options are all boolean, and affect the values returned by :meth:`readline` + + .. tabularcolumns:: |l|L|l| + + +------------------+--------------------------------+---------+ + | option name | description | default | + +==================+================================+=========+ + | *strip_comments* | strip from ``'#'`` to | true | + | | end-of-line, as well as any | | + | | whitespace leading up to the | | + | | ``'#'``\ ---unless it is | | + | | escaped by a backslash | | + +------------------+--------------------------------+---------+ + | *lstrip_ws* | strip leading whitespace from | false | + | | each line before returning it | | + +------------------+--------------------------------+---------+ + | *rstrip_ws* | strip trailing whitespace | true | + | | (including line terminator!) | | + | | from each line before | | + | | returning it. | | + +------------------+--------------------------------+---------+ + | *skip_blanks* | skip lines that are empty | true | + | | \*after\* stripping comments | | + | | and whitespace. (If both | | + | | lstrip_ws and rstrip_ws are | | + | | false, then some lines may | | + | | consist of solely whitespace: | | + | | these will \*not\* be skipped, | | + | | even if *skip_blanks* is | | + | | true.) | | + +------------------+--------------------------------+---------+ + | *join_lines* | if a backslash is the last | false | + | | non-newline character on a | | + | | line after stripping comments | | + | | and whitespace, join the | | + | | following line to it to form | | + | | one logical line; if N | | + | | consecutive lines end with a | | + | | backslash, then N+1 physical | | + | | lines will be joined to form | | + | | one logical line. | | + +------------------+--------------------------------+---------+ + | *collapse_join* | strip leading whitespace from | false | + | | lines that are joined to their | | + | | predecessor; only matters if | | + | | ``(join_lines and not | | + | | lstrip_ws)`` | | + +------------------+--------------------------------+---------+ + + Note that since *rstrip_ws* can strip the trailing newline, the semantics of + :meth:`readline` must differ from those of the built-in file object's + :meth:`readline` method! In particular, :meth:`readline` returns ``None`` for + end-of-file: an empty string might just be a blank line (or an all-whitespace + line), if *rstrip_ws* is true but *skip_blanks* is not. + + + .. method:: TextFile.open(filename) + + Open a new file *filename*. This overrides any *file* or *filename* + constructor arguments. + + + .. method:: TextFile.close() + + Close the current file and forget everything we know about it (including the + filename and the current line number). + + + .. method:: TextFile.warn(msg[,line=None]) + + Print (to stderr) a warning message tied to the current logical line in the + current file. If the current logical line in the file spans multiple physical + lines, the warning refers to the whole range, such as ``"lines 3-5"``. If + *line* is supplied, it overrides the current line number; it may be a list or + tuple to indicate a range of physical lines, or an integer for a single + physical line. + + + .. method:: TextFile.readline() + + Read and return a single logical line from the current file (or from an internal + buffer if lines have previously been "unread" with :meth:`unreadline`). If the + *join_lines* option is true, this may involve reading multiple physical lines + concatenated into a single string. Updates the current line number, so calling + :meth:`warn` after :meth:`readline` emits a warning about the physical line(s) + just read. Returns ``None`` on end-of-file, since the empty string can occur + if *rstrip_ws* is true but *strip_blanks* is not. + + + .. method:: TextFile.readlines() + + Read and return the list of all logical lines remaining in the current file. + This updates the current line number to the last line of the file. + + + .. method:: TextFile.unreadline(line) + + Push *line* (a string) onto an internal buffer that will be checked by future + :meth:`readline` calls. Handy for implementing a parser with line-at-a-time + lookahead. Note that lines that are "unread" with :meth:`unreadline` are not + subsequently re-cleansed (whitespace stripped, or whatever) when read with + :meth:`readline`. If multiple calls are made to :meth:`unreadline` before a call + to :meth:`readline`, the lines will be returned most in most recent first order. + + +:mod:`distutils.version` --- Version number classes +=================================================== + +.. module:: distutils.version + :synopsis: Implements classes that represent module version numbers. + + +.. % todo +.. % \section{Distutils Commands} +.. % +.. % This part of Distutils implements the various Distutils commands, such +.. % as \code{build}, \code{install} \&c. Each command is implemented as a +.. % separate module, with the command name as the name of the module. + + +:mod:`distutils.cmd` --- Abstract base class for Distutils commands +=================================================================== + +.. module:: distutils.cmd + :synopsis: Provides the abstract base class :class:`~distutils.cmd.Command`. This class + is subclassed by the modules in the distutils.command subpackage. + + +This module supplies the abstract base class :class:`Command`. + + +.. class:: Command(dist) + + Abstract base class for defining command classes, the "worker bees" of the + Distutils. A useful analogy for command classes is to think of them as + subroutines with local variables called *options*. The options are declared + in :meth:`initialize_options` and defined (given their final values) in + :meth:`finalize_options`, both of which must be defined by every command + class. The distinction between the two is necessary because option values + might come from the outside world (command line, config file, ...), and any + options dependent on other options must be computed after these outside + influences have been processed --- hence :meth:`finalize_options`. The body + of the subroutine, where it does all its work based on the values of its + options, is the :meth:`run` method, which must also be implemented by every + command class. + + The class constructor takes a single argument *dist*, a + :class:`~distutils.core.Distribution` instance. + + +Creating a new Distutils command +================================ + +This section outlines the steps to create a new Distutils command. + +A new command lives in a module in the :mod:`distutils.command` package. There +is a sample template in that directory called :file:`command_template`. Copy +this file to a new module with the same name as the new command you're +implementing. This module should implement a class with the same name as the +module (and the command). So, for instance, to create the command +``peel_banana`` (so that users can run ``setup.py peel_banana``), you'd copy +:file:`command_template` to :file:`distutils/command/peel_banana.py`, then edit +it so that it's implementing the class :class:`peel_banana`, a subclass of +:class:`distutils.cmd.Command`. + +Subclasses of :class:`Command` must define the following methods. + +.. method:: Command.initialize_options() + + Set default values for all the options that this command supports. Note that + these defaults may be overridden by other commands, by the setup script, by + config files, or by the command-line. Thus, this is not the place to code + dependencies between options; generally, :meth:`initialize_options` + implementations are just a bunch of ``self.foo = None`` assignments. + + +.. method:: Command.finalize_options() + + Set final values for all the options that this command supports. This is + always called as late as possible, ie. after any option assignments from the + command-line or from other commands have been done. Thus, this is the place + to code option dependencies: if *foo* depends on *bar*, then it is safe to + set *foo* from *bar* as long as *foo* still has the same value it was + assigned in :meth:`initialize_options`. + + +.. method:: Command.run() + + A command's raison d'etre: carry out the action it exists to perform, controlled + by the options initialized in :meth:`initialize_options`, customized by other + commands, the setup script, the command-line, and config files, and finalized in + :meth:`finalize_options`. All terminal output and filesystem interaction should + be done by :meth:`run`. + + +.. attribute:: Command.sub_commands + + *sub_commands* formalizes the notion of a "family" of commands, + e.g. ``install`` as the parent with sub-commands ``install_lib``, + ``install_headers``, etc. The parent of a family of commands defines + *sub_commands* as a class attribute; it's a list of 2-tuples ``(command_name, + predicate)``, with *command_name* a string and *predicate* a function, a + string or ``None``. *predicate* is a method of the parent command that + determines whether the corresponding command is applicable in the current + situation. (E.g. ``install_headers`` is only applicable if we have any C + header files to install.) If *predicate* is ``None``, that command is always + applicable. + + *sub_commands* is usually defined at the *end* of a class, because + predicates can be methods of the class, so they must already have been + defined. The canonical example is the :command:`install` command. + + +:mod:`distutils.command` --- Individual Distutils commands +========================================================== + +.. module:: distutils.command + :synopsis: Contains one module for each standard Distutils command. + + +.. % \subsubsection{Individual Distutils commands} +.. % todo + + +:mod:`distutils.command.bdist` --- Build a binary installer +=========================================================== + +.. module:: distutils.command.bdist + :synopsis: Build a binary installer for a package + + +.. % todo + + +:mod:`distutils.command.bdist_packager` --- Abstract base class for packagers +============================================================================= + +.. module:: distutils.command.bdist_packager + :synopsis: Abstract base class for packagers + + +.. % todo + + +:mod:`distutils.command.bdist_dumb` --- Build a "dumb" installer +================================================================ + +.. module:: distutils.command.bdist_dumb + :synopsis: Build a "dumb" installer - a simple archive of files + + +.. % todo + + +:mod:`distutils.command.bdist_msi` --- Build a Microsoft Installer binary package +================================================================================= + +.. module:: distutils.command.bdist_msi + :synopsis: Build a binary distribution as a Windows MSI file + +.. class:: bdist_msi + +.. deprecated:: 3.9 + Use bdist_wheel (wheel packages) instead. + + Builds a `Windows Installer`_ (.msi) binary package. + + .. _Windows Installer: https://msdn.microsoft.com/en-us/library/cc185688(VS.85).aspx + + In most cases, the ``bdist_msi`` installer is a better choice than the + ``bdist_wininst`` installer, because it provides better support for + Win64 platforms, allows administrators to perform non-interactive + installations, and allows installation through group policies. + + +:mod:`distutils.command.bdist_rpm` --- Build a binary distribution as a Redhat RPM and SRPM +=========================================================================================== + +.. module:: distutils.command.bdist_rpm + :synopsis: Build a binary distribution as a Redhat RPM and SRPM + + +.. % todo + + +:mod:`distutils.command.bdist_wininst` --- Build a Windows installer +==================================================================== + +.. module:: distutils.command.bdist_wininst + :synopsis: Build a Windows installer + +.. deprecated:: 3.8 + Use bdist_wheel (wheel packages) instead. + + +.. % todo + + +:mod:`distutils.command.sdist` --- Build a source distribution +============================================================== + +.. module:: distutils.command.sdist + :synopsis: Build a source distribution + + +.. % todo + + +:mod:`distutils.command.build` --- Build all files of a package +=============================================================== + +.. module:: distutils.command.build + :synopsis: Build all files of a package + + +.. % todo + + +:mod:`distutils.command.build_clib` --- Build any C libraries in a package +========================================================================== + +.. module:: distutils.command.build_clib + :synopsis: Build any C libraries in a package + + +.. % todo + + +:mod:`distutils.command.build_ext` --- Build any extensions in a package +======================================================================== + +.. module:: distutils.command.build_ext + :synopsis: Build any extensions in a package + + +.. % todo + + +:mod:`distutils.command.build_py` --- Build the .py/.pyc files of a package +=========================================================================== + +.. module:: distutils.command.build_py + :synopsis: Build the .py/.pyc files of a package + + +.. class:: build_py + +.. class:: build_py_2to3 + + Alternative implementation of build_py which also runs the + 2to3 conversion library on each .py file that is going to be + installed. To use this in a setup.py file for a distribution + that is designed to run with both Python 2.x and 3.x, add:: + + try: + from distutils.command.build_py import build_py_2to3 as build_py + except ImportError: + from distutils.command.build_py import build_py + + to your setup.py, and later:: + + cmdclass = {'build_py': build_py} + + to the invocation of setup(). + + +:mod:`distutils.command.build_scripts` --- Build the scripts of a package +========================================================================= + +.. module:: distutils.command.build_scripts + :synopsis: Build the scripts of a package + + +.. % todo + + +:mod:`distutils.command.clean` --- Clean a package build area +============================================================= + +.. module:: distutils.command.clean + :synopsis: Clean a package build area + +This command removes the temporary files created by :command:`build` +and its subcommands, like intermediary compiled object files. With +the ``--all`` option, the complete build directory will be removed. + +Extension modules built :ref:`in place <distutils-build-ext-inplace>` +will not be cleaned, as they are not in the build directory. + + +:mod:`distutils.command.config` --- Perform package configuration +================================================================= + +.. module:: distutils.command.config + :synopsis: Perform package configuration + + +.. % todo + + +:mod:`distutils.command.install` --- Install a package +====================================================== + +.. module:: distutils.command.install + :synopsis: Install a package + + +.. % todo + + +:mod:`distutils.command.install_data` --- Install data files from a package +=========================================================================== + +.. module:: distutils.command.install_data + :synopsis: Install data files from a package + + +.. % todo + + +:mod:`distutils.command.install_headers` --- Install C/C++ header files from a package +====================================================================================== + +.. module:: distutils.command.install_headers + :synopsis: Install C/C++ header files from a package + + +.. % todo + + +:mod:`distutils.command.install_lib` --- Install library files from a package +============================================================================= + +.. module:: distutils.command.install_lib + :synopsis: Install library files from a package + + +.. % todo + + +:mod:`distutils.command.install_scripts` --- Install script files from a package +================================================================================ + +.. module:: distutils.command.install_scripts + :synopsis: Install script files from a package + + +.. % todo + + +:mod:`distutils.command.register` --- Register a module with the Python Package Index +===================================================================================== + +.. module:: distutils.command.register + :synopsis: Register a module with the Python Package Index + + +The ``register`` command registers the package with the Python Package Index. +This is described in more detail in :pep:`301`. + +.. % todo + + +:mod:`distutils.command.check` --- Check the meta-data of a package +=================================================================== + +.. module:: distutils.command.check + :synopsis: Check the meta-data of a package + + +The ``check`` command performs some tests on the meta-data of a package. +For example, it verifies that all required meta-data are provided as +the arguments passed to the :func:`setup` function. + +.. % todo diff --git a/cpython_2/environment/repo/Doc/distutils/builtdist.rst b/cpython_2/environment/repo/Doc/distutils/builtdist.rst new file mode 100644 index 0000000000000000000000000000000000000000..e032c03e229a5cbca6a789c27fab6903ff15638e --- /dev/null +++ b/cpython_2/environment/repo/Doc/distutils/builtdist.rst @@ -0,0 +1,479 @@ +.. _built-dist: + +**************************** +Creating Built Distributions +**************************** + +.. include:: ./_setuptools_disclaimer.rst + +A "built distribution" is what you're probably used to thinking of either as a +"binary package" or an "installer" (depending on your background). It's not +necessarily binary, though, because it might contain only Python source code +and/or byte-code; and we don't call it a package, because that word is already +spoken for in Python. (And "installer" is a term specific to the world of +mainstream desktop systems.) + +A built distribution is how you make life as easy as possible for installers of +your module distribution: for users of RPM-based Linux systems, it's a binary +RPM; for Windows users, it's an executable installer; for Debian-based Linux +users, it's a Debian package; and so forth. Obviously, no one person will be +able to create built distributions for every platform under the sun, so the +Distutils are designed to enable module developers to concentrate on their +specialty---writing code and creating source distributions---while an +intermediary species called *packagers* springs up to turn source distributions +into built distributions for as many platforms as there are packagers. + +Of course, the module developer could be their own packager; or the packager could +be a volunteer "out there" somewhere who has access to a platform which the +original developer does not; or it could be software periodically grabbing new +source distributions and turning them into built distributions for as many +platforms as the software has access to. Regardless of who they are, a packager +uses the setup script and the :command:`bdist` command family to generate built +distributions. + +As a simple example, if I run the following command in the Distutils source +tree:: + + python setup.py bdist + +then the Distutils builds my module distribution (the Distutils itself in this +case), does a "fake" installation (also in the :file:`build` directory), and +creates the default type of built distribution for my platform. The default +format for built distributions is a "dumb" tar file on Unix, and a simple +executable installer on Windows. (That tar file is considered "dumb" because it +has to be unpacked in a specific location to work.) + +Thus, the above command on a Unix system creates +:file:`Distutils-1.0.{plat}.tar.gz`; unpacking this tarball from the right place +installs the Distutils just as though you had downloaded the source distribution +and run ``python setup.py install``. (The "right place" is either the root of +the filesystem or Python's :file:`{prefix}` directory, depending on the options +given to the :command:`bdist_dumb` command; the default is to make dumb +distributions relative to :file:`{prefix}`.) + +Obviously, for pure Python distributions, this isn't any simpler than just +running ``python setup.py install``\ ---but for non-pure distributions, which +include extensions that would need to be compiled, it can mean the difference +between someone being able to use your extensions or not. And creating "smart" +built distributions, such as an RPM package or an executable installer for +Windows, is far more convenient for users even if your distribution doesn't +include any extensions. + +The :command:`bdist` command has a :option:`!--formats` option, similar to the +:command:`sdist` command, which you can use to select the types of built +distribution to generate: for example, :: + + python setup.py bdist --format=zip + +would, when run on a Unix system, create +:file:`Distutils-1.0.{plat}.zip`\ ---again, this archive would be unpacked +from the root directory to install the Distutils. + +The available formats for built distributions are: + ++-------------+------------------------------+---------+ +| Format | Description | Notes | ++=============+==============================+=========+ +| ``gztar`` | gzipped tar file | \(1) | +| | (:file:`.tar.gz`) | | ++-------------+------------------------------+---------+ +| ``bztar`` | bzipped tar file | | +| | (:file:`.tar.bz2`) | | ++-------------+------------------------------+---------+ +| ``xztar`` | xzipped tar file | | +| | (:file:`.tar.xz`) | | ++-------------+------------------------------+---------+ +| ``ztar`` | compressed tar file | \(3) | +| | (:file:`.tar.Z`) | | ++-------------+------------------------------+---------+ +| ``tar`` | tar file (:file:`.tar`) | | ++-------------+------------------------------+---------+ +| ``zip`` | zip file (:file:`.zip`) | (2),(4) | ++-------------+------------------------------+---------+ +| ``rpm`` | RPM | \(5) | ++-------------+------------------------------+---------+ +| ``pkgtool`` | Solaris :program:`pkgtool` | | ++-------------+------------------------------+---------+ +| ``sdux`` | HP-UX :program:`swinstall` | | ++-------------+------------------------------+---------+ +| ``wininst`` | self-extracting ZIP file for | \(4) | +| | Windows | | ++-------------+------------------------------+---------+ +| ``msi`` | Microsoft Installer. | | ++-------------+------------------------------+---------+ + +.. versionchanged:: 3.5 + Added support for the ``xztar`` format. + + +Notes: + +(1) + default on Unix + +(2) + default on Windows + +(3) + requires external :program:`compress` utility. + +(4) + requires either external :program:`zip` utility or :mod:`zipfile` module (part + of the standard Python library since Python 1.6) + +(5) + requires external :program:`rpm` utility, version 3.0.4 or better (use ``rpm + --version`` to find out which version you have) + +You don't have to use the :command:`bdist` command with the :option:`!--formats` +option; you can also use the command that directly implements the format you're +interested in. Some of these :command:`bdist` "sub-commands" actually generate +several similar formats; for instance, the :command:`bdist_dumb` command +generates all the "dumb" archive formats (``tar``, ``gztar``, ``bztar``, +``xztar``, ``ztar``, and ``zip``), and :command:`bdist_rpm` generates both +binary and source RPMs. The :command:`bdist` sub-commands, and the formats +generated by each, are: + ++--------------------------+-------------------------------------+ +| Command | Formats | ++==========================+=====================================+ +| :command:`bdist_dumb` | tar, gztar, bztar, xztar, ztar, zip | ++--------------------------+-------------------------------------+ +| :command:`bdist_rpm` | rpm, srpm | ++--------------------------+-------------------------------------+ +| :command:`bdist_wininst` | wininst | ++--------------------------+-------------------------------------+ +| :command:`bdist_msi` | msi | ++--------------------------+-------------------------------------+ + +.. note:: + bdist_wininst is deprecated since Python 3.8. + +.. note:: + bdist_msi is deprecated since Python 3.9. + +The following sections give details on the individual :command:`bdist_\*` +commands. + + +.. .. _creating-dumb: + +.. Creating dumb built distributions +.. ================================= + +.. XXX Need to document absolute vs. prefix-relative packages here, but first + I have to implement it! + + +.. _creating-rpms: + +Creating RPM packages +===================== + +The RPM format is used by many popular Linux distributions, including Red Hat, +SuSE, and Mandrake. If one of these (or any of the other RPM-based Linux +distributions) is your usual environment, creating RPM packages for other users +of that same distribution is trivial. Depending on the complexity of your module +distribution and differences between Linux distributions, you may also be able +to create RPMs that work on different RPM-based distributions. + +The usual way to create an RPM of your module distribution is to run the +:command:`bdist_rpm` command:: + + python setup.py bdist_rpm + +or the :command:`bdist` command with the :option:`!--format` option:: + + python setup.py bdist --formats=rpm + +The former allows you to specify RPM-specific options; the latter allows you to +easily specify multiple formats in one run. If you need to do both, you can +explicitly specify multiple :command:`bdist_\*` commands and their options:: + + python setup.py bdist_rpm --packager="John Doe <jdoe@example.org>" \ + bdist_wininst --target-version="2.0" + +Creating RPM packages is driven by a :file:`.spec` file, much as using the +Distutils is driven by the setup script. To make your life easier, the +:command:`bdist_rpm` command normally creates a :file:`.spec` file based on the +information you supply in the setup script, on the command line, and in any +Distutils configuration files. Various options and sections in the +:file:`.spec` file are derived from options in the setup script as follows: + ++------------------------------------------+----------------------------------------------+ +| RPM :file:`.spec` file option or section | Distutils setup script option | ++==========================================+==============================================+ +| Name | ``name`` | ++------------------------------------------+----------------------------------------------+ +| Summary (in preamble) | ``description`` | ++------------------------------------------+----------------------------------------------+ +| Version | ``version`` | ++------------------------------------------+----------------------------------------------+ +| Vendor | ``author`` and ``author_email``, | +| | or --- & ``maintainer`` and | +| | ``maintainer_email`` | ++------------------------------------------+----------------------------------------------+ +| Copyright | ``license`` | ++------------------------------------------+----------------------------------------------+ +| Url | ``url`` | ++------------------------------------------+----------------------------------------------+ +| %description (section) | ``long_description`` | ++------------------------------------------+----------------------------------------------+ + +Additionally, there are many options in :file:`.spec` files that don't have +corresponding options in the setup script. Most of these are handled through +options to the :command:`bdist_rpm` command as follows: + ++-------------------------------+-----------------------------+-------------------------+ +| RPM :file:`.spec` file option | :command:`bdist_rpm` option | default value | +| or section | | | ++===============================+=============================+=========================+ +| Release | ``release`` | "1" | ++-------------------------------+-----------------------------+-------------------------+ +| Group | ``group`` | "Development/Libraries" | ++-------------------------------+-----------------------------+-------------------------+ +| Vendor | ``vendor`` | (see above) | ++-------------------------------+-----------------------------+-------------------------+ +| Packager | ``packager`` | (none) | ++-------------------------------+-----------------------------+-------------------------+ +| Provides | ``provides`` | (none) | ++-------------------------------+-----------------------------+-------------------------+ +| Requires | ``requires`` | (none) | ++-------------------------------+-----------------------------+-------------------------+ +| Conflicts | ``conflicts`` | (none) | ++-------------------------------+-----------------------------+-------------------------+ +| Obsoletes | ``obsoletes`` | (none) | ++-------------------------------+-----------------------------+-------------------------+ +| Distribution | ``distribution_name`` | (none) | ++-------------------------------+-----------------------------+-------------------------+ +| BuildRequires | ``build_requires`` | (none) | ++-------------------------------+-----------------------------+-------------------------+ +| Icon | ``icon`` | (none) | ++-------------------------------+-----------------------------+-------------------------+ + +Obviously, supplying even a few of these options on the command-line would be +tedious and error-prone, so it's usually best to put them in the setup +configuration file, :file:`setup.cfg`\ ---see section :ref:`setup-config`. If +you distribute or package many Python module distributions, you might want to +put options that apply to all of them in your personal Distutils configuration +file (:file:`~/.pydistutils.cfg`). If you want to temporarily disable +this file, you can pass the :option:`!--no-user-cfg` option to :file:`setup.py`. + +There are three steps to building a binary RPM package, all of which are +handled automatically by the Distutils: + +#. create a :file:`.spec` file, which describes the package (analogous to the + Distutils setup script; in fact, much of the information in the setup script + winds up in the :file:`.spec` file) + +#. create the source RPM + +#. create the "binary" RPM (which may or may not contain binary code, depending + on whether your module distribution contains Python extensions) + +Normally, RPM bundles the last two steps together; when you use the Distutils, +all three steps are typically bundled together. + +If you wish, you can separate these three steps. You can use the +:option:`!--spec-only` option to make :command:`bdist_rpm` just create the +:file:`.spec` file and exit; in this case, the :file:`.spec` file will be +written to the "distribution directory"---normally :file:`dist/`, but +customizable with the :option:`!--dist-dir` option. (Normally, the :file:`.spec` +file winds up deep in the "build tree," in a temporary directory created by +:command:`bdist_rpm`.) + +.. % \XXX{this isn't implemented yet---is it needed?!} +.. % You can also specify a custom \file{.spec} file with the +.. % \longprogramopt{spec-file} option; used in conjunction with +.. % \longprogramopt{spec-only}, this gives you an opportunity to customize +.. % the \file{.spec} file manually: +.. % +.. % \ begin{verbatim} +.. % > python setup.py bdist_rpm --spec-only +.. % # ...edit dist/FooBar-1.0.spec +.. % > python setup.py bdist_rpm --spec-file=dist/FooBar-1.0.spec +.. % \ end{verbatim} +.. % +.. % (Although a better way to do this is probably to override the standard +.. % \command{bdist\_rpm} command with one that writes whatever else you want +.. % to the \file{.spec} file.) + + +.. _creating-wininst: + +Creating Windows Installers +=========================== + +.. warning:: + bdist_wininst is deprecated since Python 3.8. + +.. warning:: + bdist_msi is deprecated since Python 3.9. + +Executable installers are the natural format for binary distributions on +Windows. They display a nice graphical user interface, display some information +about the module distribution to be installed taken from the metadata in the +setup script, let the user select a few options, and start or cancel the +installation. + +Since the metadata is taken from the setup script, creating Windows installers +is usually as easy as running:: + + python setup.py bdist_wininst + +or the :command:`bdist` command with the :option:`!--formats` option:: + + python setup.py bdist --formats=wininst + +If you have a pure module distribution (only containing pure Python modules and +packages), the resulting installer will be version independent and have a name +like :file:`foo-1.0.win32.exe`. Note that creating ``wininst`` binary +distributions in only supported on Windows systems. + +If you have a non-pure distribution, the extensions can only be created on a +Windows platform, and will be Python version dependent. The installer filename +will reflect this and now has the form :file:`foo-1.0.win32-py2.0.exe`. You +have to create a separate installer for every Python version you want to +support. + +The installer will try to compile pure modules into :term:`bytecode` after installation +on the target system in normal and optimizing mode. If you don't want this to +happen for some reason, you can run the :command:`bdist_wininst` command with +the :option:`!--no-target-compile` and/or the :option:`!--no-target-optimize` +option. + +By default the installer will display the cool "Python Powered" logo when it is +run, but you can also supply your own 152x261 bitmap which must be a Windows +:file:`.bmp` file with the :option:`!--bitmap` option. + +The installer will also display a large title on the desktop background window +when it is run, which is constructed from the name of your distribution and the +version number. This can be changed to another text by using the +:option:`!--title` option. + +The installer file will be written to the "distribution directory" --- normally +:file:`dist/`, but customizable with the :option:`!--dist-dir` option. + +.. _cross-compile-windows: + +Cross-compiling on Windows +========================== + +Starting with Python 2.6, distutils is capable of cross-compiling between +Windows platforms. In practice, this means that with the correct tools +installed, you can use a 32bit version of Windows to create 64bit extensions +and vice-versa. + +To build for an alternate platform, specify the :option:`!--plat-name` option +to the build command. Valid values are currently 'win32', and 'win-amd64'. +For example, on a 32bit version of Windows, you could execute:: + + python setup.py build --plat-name=win-amd64 + +to build a 64bit version of your extension. The Windows Installers also +support this option, so the command:: + + python setup.py build --plat-name=win-amd64 bdist_wininst + +would create a 64bit installation executable on your 32bit version of Windows. + +To cross-compile, you must download the Python source code and cross-compile +Python itself for the platform you are targeting - it is not possible from a +binary installation of Python (as the .lib etc file for other platforms are +not included.) In practice, this means the user of a 32 bit operating +system will need to use Visual Studio 2008 to open the +:file:`PCbuild/PCbuild.sln` solution in the Python source tree and build the +"x64" configuration of the 'pythoncore' project before cross-compiling +extensions is possible. + +Note that by default, Visual Studio 2008 does not install 64bit compilers or +tools. You may need to reexecute the Visual Studio setup process and select +these tools (using Control Panel->[Add/Remove] Programs is a convenient way to +check or modify your existing install.) + +.. _postinstallation-script: + +The Postinstallation script +--------------------------- + +Starting with Python 2.3, a postinstallation script can be specified with the +:option:`!--install-script` option. The basename of the script must be +specified, and the script filename must also be listed in the scripts argument +to the setup function. + +This script will be run at installation time on the target system after all the +files have been copied, with ``argv[1]`` set to :option:`!-install`, and again at +uninstallation time before the files are removed with ``argv[1]`` set to +:option:`!-remove`. + +The installation script runs embedded in the windows installer, every output +(``sys.stdout``, ``sys.stderr``) is redirected into a buffer and will be +displayed in the GUI after the script has finished. + +Some functions especially useful in this context are available as additional +built-in functions in the installation script. + + +.. function:: directory_created(path) + file_created(path) + + These functions should be called when a directory or file is created by the + postinstall script at installation time. It will register *path* with the + uninstaller, so that it will be removed when the distribution is uninstalled. + To be safe, directories are only removed if they are empty. + + +.. function:: get_special_folder_path(csidl_string) + + This function can be used to retrieve special folder locations on Windows like + the Start Menu or the Desktop. It returns the full path to the folder. + *csidl_string* must be one of the following strings:: + + "CSIDL_APPDATA" + + "CSIDL_COMMON_STARTMENU" + "CSIDL_STARTMENU" + + "CSIDL_COMMON_DESKTOPDIRECTORY" + "CSIDL_DESKTOPDIRECTORY" + + "CSIDL_COMMON_STARTUP" + "CSIDL_STARTUP" + + "CSIDL_COMMON_PROGRAMS" + "CSIDL_PROGRAMS" + + "CSIDL_FONTS" + + If the folder cannot be retrieved, :exc:`OSError` is raised. + + Which folders are available depends on the exact Windows version, and probably + also the configuration. For details refer to Microsoft's documentation of the + :c:func:`SHGetSpecialFolderPath` function. + + +.. function:: create_shortcut(target, description, filename[, arguments[, workdir[, iconpath[, iconindex]]]]) + + This function creates a shortcut. *target* is the path to the program to be + started by the shortcut. *description* is the description of the shortcut. + *filename* is the title of the shortcut that the user will see. *arguments* + specifies the command line arguments, if any. *workdir* is the working directory + for the program. *iconpath* is the file containing the icon for the shortcut, + and *iconindex* is the index of the icon in the file *iconpath*. Again, for + details consult the Microsoft documentation for the :class:`IShellLink` + interface. + + +Vista User Access Control (UAC) +=============================== + +Starting with Python 2.6, bdist_wininst supports a :option:`!--user-access-control` +option. The default is 'none' (meaning no UAC handling is done), and other +valid values are 'auto' (meaning prompt for UAC elevation if Python was +installed for all users) and 'force' (meaning always prompt for elevation). + +.. note:: + bdist_wininst is deprecated since Python 3.8. + +.. note:: + bdist_msi is deprecated since Python 3.9. diff --git a/cpython_2/environment/repo/Doc/distutils/commandref.rst b/cpython_2/environment/repo/Doc/distutils/commandref.rst new file mode 100644 index 0000000000000000000000000000000000000000..0f6fe2aba865f819edf8914ba0148a93ee7398fc --- /dev/null +++ b/cpython_2/environment/repo/Doc/distutils/commandref.rst @@ -0,0 +1,106 @@ +.. _reference: + +***************** +Command Reference +***************** + +.. include:: ./_setuptools_disclaimer.rst + +.. % \section{Building modules: the \protect\command{build} command family} +.. % \label{build-cmds} +.. % \subsubsection{\protect\command{build}} +.. % \label{build-cmd} +.. % \subsubsection{\protect\command{build\_py}} +.. % \label{build-py-cmd} +.. % \subsubsection{\protect\command{build\_ext}} +.. % \label{build-ext-cmd} +.. % \subsubsection{\protect\command{build\_clib}} +.. % \label{build-clib-cmd} + + +.. _install-cmd: + +Installing modules: the :command:`install` command family +========================================================= + +The install command ensures that the build commands have been run and then runs +the subcommands :command:`install_lib`, :command:`install_data` and +:command:`install_scripts`. + +.. % \subsubsection{\protect\command{install\_lib}} +.. % \label{install-lib-cmd} + + +.. _install-data-cmd: + +:command:`install_data` +----------------------- + +This command installs all data files provided with the distribution. + + +.. _install-scripts-cmd: + +:command:`install_scripts` +-------------------------- + +This command installs all (Python) scripts in the distribution. + +.. % \subsection{Cleaning up: the \protect\command{clean} command} +.. % \label{clean-cmd} + + +.. _sdist-cmd: + +Creating a source distribution: the :command:`sdist` command +============================================================ + +.. XXX fragment moved down from above: needs context! + +The manifest template commands are: + ++-------------------------------------------+-----------------------------------------------+ +| Command | Description | ++===========================================+===============================================+ +| :command:`include pat1 pat2 ...` | include all files matching any of the listed | +| | patterns | ++-------------------------------------------+-----------------------------------------------+ +| :command:`exclude pat1 pat2 ...` | exclude all files matching any of the listed | +| | patterns | ++-------------------------------------------+-----------------------------------------------+ +| :command:`recursive-include dir pat1 pat2 | include all files under *dir* matching any of | +| ...` | the listed patterns | ++-------------------------------------------+-----------------------------------------------+ +| :command:`recursive-exclude dir pat1 pat2 | exclude all files under *dir* matching any of | +| ...` | the listed patterns | ++-------------------------------------------+-----------------------------------------------+ +| :command:`global-include pat1 pat2 ...` | include all files anywhere in the source tree | +| | matching --- & any of the listed patterns | ++-------------------------------------------+-----------------------------------------------+ +| :command:`global-exclude pat1 pat2 ...` | exclude all files anywhere in the source tree | +| | matching --- & any of the listed patterns | ++-------------------------------------------+-----------------------------------------------+ +| :command:`prune dir` | exclude all files under *dir* | ++-------------------------------------------+-----------------------------------------------+ +| :command:`graft dir` | include all files under *dir* | ++-------------------------------------------+-----------------------------------------------+ + +The patterns here are Unix-style "glob" patterns: ``*`` matches any sequence of +regular filename characters, ``?`` matches any single regular filename +character, and ``[range]`` matches any of the characters in *range* (e.g., +``a-z``, ``a-zA-Z``, ``a-f0-9_.``). The definition of "regular filename +character" is platform-specific: on Unix it is anything except slash; on Windows +anything except backslash or colon. + +.. XXX Windows support not there yet + +.. % \section{Creating a built distribution: the +.. % \protect\command{bdist} command family} +.. % \label{bdist-cmds} + +.. % \subsection{\protect\command{bdist}} +.. % \subsection{\protect\command{bdist\_dumb}} +.. % \subsection{\protect\command{bdist\_rpm}} +.. % \subsection{\protect\command{bdist\_wininst}} + + diff --git a/cpython_2/environment/repo/Doc/distutils/configfile.rst b/cpython_2/environment/repo/Doc/distutils/configfile.rst new file mode 100644 index 0000000000000000000000000000000000000000..2a5c8329e318b7d244594ab626db24f2124c9ac2 --- /dev/null +++ b/cpython_2/environment/repo/Doc/distutils/configfile.rst @@ -0,0 +1,144 @@ +.. _setup-config: + +************************************ +Writing the Setup Configuration File +************************************ + +.. include:: ./_setuptools_disclaimer.rst + +Often, it's not possible to write down everything needed to build a distribution +*a priori*: you may need to get some information from the user, or from the +user's system, in order to proceed. As long as that information is fairly +simple---a list of directories to search for C header files or libraries, for +example---then providing a configuration file, :file:`setup.cfg`, for users to +edit is a cheap and easy way to solicit it. Configuration files also let you +provide default values for any command option, which the installer can then +override either on the command-line or by editing the config file. + +The setup configuration file is a useful middle-ground between the setup +script---which, ideally, would be opaque to installers [#]_---and the command-line to +the setup script, which is outside of your control and entirely up to the +installer. In fact, :file:`setup.cfg` (and any other Distutils configuration +files present on the target system) are processed after the contents of the +setup script, but before the command-line. This has several useful +consequences: + +.. % (If you have more advanced needs, such as determining which extensions +.. % to build based on what capabilities are present on the target system, +.. % then you need the Distutils ``auto-configuration'' facility. This +.. % started to appear in Distutils 0.9 but, as of this writing, isn't mature +.. % or stable enough yet for real-world use.) + +* installers can override some of what you put in :file:`setup.py` by editing + :file:`setup.cfg` + +* you can provide non-standard defaults for options that are not easily set in + :file:`setup.py` + +* installers can override anything in :file:`setup.cfg` using the command-line + options to :file:`setup.py` + +The basic syntax of the configuration file is simple: + +.. code-block:: ini + + [command] + option=value + ... + +where *command* is one of the Distutils commands (e.g. :command:`build_py`, +:command:`install`), and *option* is one of the options that command supports. +Any number of options can be supplied for each command, and any number of +command sections can be included in the file. Blank lines are ignored, as are +comments, which run from a ``'#'`` character until the end of the line. Long +option values can be split across multiple lines simply by indenting the +continuation lines. + +You can find out the list of options supported by a particular command with the +universal :option:`!--help` option, e.g. + +.. code-block:: shell-session + + $ python setup.py --help build_ext + [...] + Options for 'build_ext' command: + --build-lib (-b) directory for compiled extension modules + --build-temp (-t) directory for temporary files (build by-products) + --inplace (-i) ignore build-lib and put compiled extensions into the + source directory alongside your pure Python modules + --include-dirs (-I) list of directories to search for header files + --define (-D) C preprocessor macros to define + --undef (-U) C preprocessor macros to undefine + --swig-opts list of SWIG command line options + [...] + +Note that an option spelled :option:`!--foo-bar` on the command-line is spelled +``foo_bar`` in configuration files. + +.. _distutils-build-ext-inplace: + +For example, say you want your extensions to be built "in-place"---that is, you +have an extension :mod:`pkg.ext`, and you want the compiled extension file +(:file:`ext.so` on Unix, say) to be put in the same source directory as your +pure Python modules :mod:`pkg.mod1` and :mod:`pkg.mod2`. You can always use the +:option:`!--inplace` option on the command-line to ensure this: + +.. code-block:: sh + + python setup.py build_ext --inplace + +But this requires that you always specify the :command:`build_ext` command +explicitly, and remember to provide :option:`!--inplace`. An easier way is to +"set and forget" this option, by encoding it in :file:`setup.cfg`, the +configuration file for this distribution: + +.. code-block:: ini + + [build_ext] + inplace=1 + +This will affect all builds of this module distribution, whether or not you +explicitly specify :command:`build_ext`. If you include :file:`setup.cfg` in +your source distribution, it will also affect end-user builds---which is +probably a bad idea for this option, since always building extensions in-place +would break installation of the module distribution. In certain peculiar cases, +though, modules are built right in their installation directory, so this is +conceivably a useful ability. (Distributing extensions that expect to be built +in their installation directory is almost always a bad idea, though.) + +Another example: certain commands take a lot of options that don't change from +run to run; for example, :command:`bdist_rpm` needs to know everything required +to generate a "spec" file for creating an RPM distribution. Some of this +information comes from the setup script, and some is automatically generated by +the Distutils (such as the list of files installed). But some of it has to be +supplied as options to :command:`bdist_rpm`, which would be very tedious to do +on the command-line for every run. Hence, here is a snippet from the Distutils' +own :file:`setup.cfg`: + +.. code-block:: ini + + [bdist_rpm] + release = 1 + packager = Greg Ward <gward@python.net> + doc_files = CHANGES.txt + README.txt + USAGE.txt + doc/ + examples/ + +Note that the ``doc_files`` option is simply a whitespace-separated string +split across multiple lines for readability. + + +.. seealso:: + + :ref:`inst-config-syntax` in "Installing Python Modules" + More information on the configuration files is available in the manual for + system administrators. + + +.. rubric:: Footnotes + +.. [#] This ideal probably won't be achieved until auto-configuration is fully + supported by the Distutils. + diff --git a/cpython_2/environment/repo/Doc/distutils/examples.rst b/cpython_2/environment/repo/Doc/distutils/examples.rst new file mode 100644 index 0000000000000000000000000000000000000000..e492b7f6057596b3af5a11178e4ebb2a5382f4e7 --- /dev/null +++ b/cpython_2/environment/repo/Doc/distutils/examples.rst @@ -0,0 +1,340 @@ +.. _distutils_examples: + +****************** +Distutils Examples +****************** + +.. include:: ./_setuptools_disclaimer.rst + +This chapter provides a number of basic examples to help get started with +distutils. Additional information about using distutils can be found in the +Distutils Cookbook. + + +.. seealso:: + + `Distutils Cookbook <https://wiki.python.org/moin/Distutils/Cookbook>`_ + Collection of recipes showing how to achieve more control over distutils. + + +.. _pure-mod: + +Pure Python distribution (by module) +==================================== + +If you're just distributing a couple of modules, especially if they don't live +in a particular package, you can specify them individually using the +``py_modules`` option in the setup script. + +In the simplest case, you'll have two files to worry about: a setup script and +the single module you're distributing, :file:`foo.py` in this example:: + + <root>/ + setup.py + foo.py + +(In all diagrams in this section, *<root>* will refer to the distribution root +directory.) A minimal setup script to describe this situation would be:: + + from distutils.core import setup + setup(name='foo', + version='1.0', + py_modules=['foo'], + ) + +Note that the name of the distribution is specified independently with the +``name`` option, and there's no rule that says it has to be the same as +the name of the sole module in the distribution (although that's probably a good +convention to follow). However, the distribution name is used to generate +filenames, so you should stick to letters, digits, underscores, and hyphens. + +Since ``py_modules`` is a list, you can of course specify multiple +modules, eg. if you're distributing modules :mod:`foo` and :mod:`bar`, your +setup might look like this:: + + <root>/ + setup.py + foo.py + bar.py + +and the setup script might be :: + + from distutils.core import setup + setup(name='foobar', + version='1.0', + py_modules=['foo', 'bar'], + ) + +You can put module source files into another directory, but if you have enough +modules to do that, it's probably easier to specify modules by package rather +than listing them individually. + + +.. _pure-pkg: + +Pure Python distribution (by package) +===================================== + +If you have more than a couple of modules to distribute, especially if they are +in multiple packages, it's probably easier to specify whole packages rather than +individual modules. This works even if your modules are not in a package; you +can just tell the Distutils to process modules from the root package, and that +works the same as any other package (except that you don't have to have an +:file:`__init__.py` file). + +The setup script from the last example could also be written as :: + + from distutils.core import setup + setup(name='foobar', + version='1.0', + packages=[''], + ) + +(The empty string stands for the root package.) + +If those two files are moved into a subdirectory, but remain in the root +package, e.g.:: + + <root>/ + setup.py + src/ foo.py + bar.py + +then you would still specify the root package, but you have to tell the +Distutils where source files in the root package live:: + + from distutils.core import setup + setup(name='foobar', + version='1.0', + package_dir={'': 'src'}, + packages=[''], + ) + +More typically, though, you will want to distribute multiple modules in the same +package (or in sub-packages). For example, if the :mod:`foo` and :mod:`bar` +modules belong in package :mod:`foobar`, one way to layout your source tree is +:: + + <root>/ + setup.py + foobar/ + __init__.py + foo.py + bar.py + +This is in fact the default layout expected by the Distutils, and the one that +requires the least work to describe in your setup script:: + + from distutils.core import setup + setup(name='foobar', + version='1.0', + packages=['foobar'], + ) + +If you want to put modules in directories not named for their package, then you +need to use the ``package_dir`` option again. For example, if the +:file:`src` directory holds modules in the :mod:`foobar` package:: + + <root>/ + setup.py + src/ + __init__.py + foo.py + bar.py + +an appropriate setup script would be :: + + from distutils.core import setup + setup(name='foobar', + version='1.0', + package_dir={'foobar': 'src'}, + packages=['foobar'], + ) + +Or, you might put modules from your main package right in the distribution +root:: + + <root>/ + setup.py + __init__.py + foo.py + bar.py + +in which case your setup script would be :: + + from distutils.core import setup + setup(name='foobar', + version='1.0', + package_dir={'foobar': ''}, + packages=['foobar'], + ) + +(The empty string also stands for the current directory.) + +If you have sub-packages, they must be explicitly listed in ``packages``, +but any entries in ``package_dir`` automatically extend to sub-packages. +(In other words, the Distutils does *not* scan your source tree, trying to +figure out which directories correspond to Python packages by looking for +:file:`__init__.py` files.) Thus, if the default layout grows a sub-package:: + + <root>/ + setup.py + foobar/ + __init__.py + foo.py + bar.py + subfoo/ + __init__.py + blah.py + +then the corresponding setup script would be :: + + from distutils.core import setup + setup(name='foobar', + version='1.0', + packages=['foobar', 'foobar.subfoo'], + ) + + +.. _single-ext: + +Single extension module +======================= + +Extension modules are specified using the ``ext_modules`` option. +``package_dir`` has no effect on where extension source files are found; +it only affects the source for pure Python modules. The simplest case, a +single extension module in a single C source file, is:: + + <root>/ + setup.py + foo.c + +If the :mod:`foo` extension belongs in the root package, the setup script for +this could be :: + + from distutils.core import setup + from distutils.extension import Extension + setup(name='foobar', + version='1.0', + ext_modules=[Extension('foo', ['foo.c'])], + ) + +If the extension actually belongs in a package, say :mod:`foopkg`, then + +With exactly the same source tree layout, this extension can be put in the +:mod:`foopkg` package simply by changing the name of the extension:: + + from distutils.core import setup + from distutils.extension import Extension + setup(name='foobar', + version='1.0', + ext_modules=[Extension('foopkg.foo', ['foo.c'])], + ) + +Checking a package +================== + +The ``check`` command allows you to verify if your package meta-data +meet the minimum requirements to build a distribution. + +To run it, just call it using your :file:`setup.py` script. If something is +missing, ``check`` will display a warning. + +Let's take an example with a simple script:: + + from distutils.core import setup + + setup(name='foobar') + +Running the ``check`` command will display some warnings: + +.. code-block:: shell-session + + $ python setup.py check + running check + warning: check: missing required meta-data: version, url + warning: check: missing meta-data: either (author and author_email) or + (maintainer and maintainer_email) should be supplied + + +If you use the reStructuredText syntax in the ``long_description`` field and +`docutils`_ is installed you can check if the syntax is fine with the +``check`` command, using the ``restructuredtext`` option. + +For example, if the :file:`setup.py` script is changed like this:: + + from distutils.core import setup + + desc = """\ + My description + ============== + + This is the description of the ``foobar`` package. + """ + + setup(name='foobar', version='1', author='tarek', + author_email='tarek@ziade.org', + url='http://example.com', long_description=desc) + +Where the long description is broken, ``check`` will be able to detect it +by using the :mod:`docutils` parser: + +.. code-block:: shell-session + + $ python setup.py check --restructuredtext + running check + warning: check: Title underline too short. (line 2) + warning: check: Could not finish the parsing. + +Reading the metadata +===================== + +The :func:`distutils.core.setup` function provides a command-line interface +that allows you to query the metadata fields of a project through the +``setup.py`` script of a given project: + +.. code-block:: shell-session + + $ python setup.py --name + distribute + +This call reads the ``name`` metadata by running the +:func:`distutils.core.setup` function. Although, when a source or binary +distribution is created with Distutils, the metadata fields are written +in a static file called :file:`PKG-INFO`. When a Distutils-based project is +installed in Python, the :file:`PKG-INFO` file is copied alongside the modules +and packages of the distribution under :file:`NAME-VERSION-pyX.X.egg-info`, +where ``NAME`` is the name of the project, ``VERSION`` its version as defined +in the Metadata, and ``pyX.X`` the major and minor version of Python like +``2.7`` or ``3.2``. + +You can read back this static file, by using the +:class:`distutils.dist.DistributionMetadata` class and its +:func:`read_pkg_file` method:: + + >>> from distutils.dist import DistributionMetadata + >>> metadata = DistributionMetadata() + >>> metadata.read_pkg_file(open('distribute-0.6.8-py2.7.egg-info')) + >>> metadata.name + 'distribute' + >>> metadata.version + '0.6.8' + >>> metadata.description + 'Easily download, build, install, upgrade, and uninstall Python packages' + +Notice that the class can also be instantiated with a metadata file path to +loads its values:: + + >>> pkg_info_path = 'distribute-0.6.8-py2.7.egg-info' + >>> DistributionMetadata(pkg_info_path).name + 'distribute' + + +.. % \section{Multiple extension modules} +.. % \label{multiple-ext} + +.. % \section{Putting it all together} + + +.. _docutils: http://docutils.sourceforge.net diff --git a/cpython_2/environment/repo/Doc/distutils/extending.rst b/cpython_2/environment/repo/Doc/distutils/extending.rst new file mode 100644 index 0000000000000000000000000000000000000000..1075e81779a7bae6806949bcd5cc089df856d3d0 --- /dev/null +++ b/cpython_2/environment/repo/Doc/distutils/extending.rst @@ -0,0 +1,98 @@ +.. _extending-distutils: + +******************* +Extending Distutils +******************* + +.. include:: ./_setuptools_disclaimer.rst + +Distutils can be extended in various ways. Most extensions take the form of new +commands or replacements for existing commands. New commands may be written to +support new types of platform-specific packaging, for example, while +replacements for existing commands may be made to modify details of how the +command operates on a package. + +Most extensions of the distutils are made within :file:`setup.py` scripts that +want to modify existing commands; many simply add a few file extensions that +should be copied into packages in addition to :file:`.py` files as a +convenience. + +Most distutils command implementations are subclasses of the +:class:`distutils.cmd.Command` class. New commands may directly inherit from +:class:`Command`, while replacements often derive from :class:`Command` +indirectly, directly subclassing the command they are replacing. Commands are +required to derive from :class:`Command`. + +.. % \section{Extending existing commands} +.. % \label{extend-existing} + +.. % \section{Writing new commands} +.. % \label{new-commands} +.. % \XXX{Would an uninstall command be a good example here?} + + +Integrating new commands +======================== + +There are different ways to integrate new command implementations into +distutils. The most difficult is to lobby for the inclusion of the new features +in distutils itself, and wait for (and require) a version of Python that +provides that support. This is really hard for many reasons. + +The most common, and possibly the most reasonable for most needs, is to include +the new implementations with your :file:`setup.py` script, and cause the +:func:`distutils.core.setup` function use them:: + + from distutils.command.build_py import build_py as _build_py + from distutils.core import setup + + class build_py(_build_py): + """Specialized Python source builder.""" + + # implement whatever needs to be different... + + setup(cmdclass={'build_py': build_py}, + ...) + +This approach is most valuable if the new implementations must be used to use a +particular package, as everyone interested in the package will need to have the +new command implementation. + +Beginning with Python 2.4, a third option is available, intended to allow new +commands to be added which can support existing :file:`setup.py` scripts without +requiring modifications to the Python installation. This is expected to allow +third-party extensions to provide support for additional packaging systems, but +the commands can be used for anything distutils commands can be used for. A new +configuration option, ``command_packages`` (command-line option +:option:`!--command-packages`), can be used to specify additional packages to be +searched for modules implementing commands. Like all distutils options, this +can be specified on the command line or in a configuration file. This option +can only be set in the ``[global]`` section of a configuration file, or before +any commands on the command line. If set in a configuration file, it can be +overridden from the command line; setting it to an empty string on the command +line causes the default to be used. This should never be set in a configuration +file provided with a package. + +This new option can be used to add any number of packages to the list of +packages searched for command implementations; multiple package names should be +separated by commas. When not specified, the search is only performed in the +:mod:`distutils.command` package. When :file:`setup.py` is run with the option +``--command-packages distcmds,buildcmds``, however, the packages +:mod:`distutils.command`, :mod:`distcmds`, and :mod:`buildcmds` will be searched +in that order. New commands are expected to be implemented in modules of the +same name as the command by classes sharing the same name. Given the example +command line option above, the command :command:`bdist_openpkg` could be +implemented by the class :class:`distcmds.bdist_openpkg.bdist_openpkg` or +:class:`buildcmds.bdist_openpkg.bdist_openpkg`. + + +Adding new distribution types +============================= + +Commands that create distributions (files in the :file:`dist/` directory) need +to add ``(command, filename)`` pairs to ``self.distribution.dist_files`` so that +:command:`upload` can upload it to PyPI. The *filename* in the pair contains no +path information, only the name of the file itself. In dry-run mode, pairs +should still be added to represent what would have been created. + + diff --git a/cpython_2/environment/repo/Doc/distutils/index.rst b/cpython_2/environment/repo/Doc/distutils/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..1f72a25542494abd0861372e9f2aa9b098bda893 --- /dev/null +++ b/cpython_2/environment/repo/Doc/distutils/index.rst @@ -0,0 +1,42 @@ +.. _distutils-index: + +############################################## + Distributing Python Modules (Legacy version) +############################################## + +:Authors: Greg Ward, Anthony Baxter +:Email: distutils-sig@python.org + +.. seealso:: + + :ref:`distributing-index` + The up to date module distribution documentations + +.. include:: ./_setuptools_disclaimer.rst + +.. note:: + + This guide only covers the basic tools for building and distributing + extensions that are provided as part of this version of Python. Third party + tools offer easier to use and more secure alternatives. Refer to the `quick + recommendations section <https://packaging.python.org/guides/tool-recommendations/>`__ + in the Python Packaging User Guide for more information. + +This document describes the Python Distribution Utilities ("Distutils") from +the module developer's point of view, describing the underlying capabilities +that ``setuptools`` builds on to allow Python developers to make Python modules +and extensions readily available to a wider audience. + +.. toctree:: + :maxdepth: 2 + :numbered: + + introduction.rst + setupscript.rst + configfile.rst + sourcedist.rst + builtdist.rst + examples.rst + extending.rst + commandref.rst + apiref.rst diff --git a/cpython_2/environment/repo/Doc/distutils/introduction.rst b/cpython_2/environment/repo/Doc/distutils/introduction.rst new file mode 100644 index 0000000000000000000000000000000000000000..1f8a560e138616fed5289044b6c9864dc8c892e6 --- /dev/null +++ b/cpython_2/environment/repo/Doc/distutils/introduction.rst @@ -0,0 +1,214 @@ +.. _distutils-intro: + +**************************** +An Introduction to Distutils +**************************** + +.. include:: ./_setuptools_disclaimer.rst + +This document covers using the Distutils to distribute your Python modules, +concentrating on the role of developer/distributor: if you're looking for +information on installing Python modules, you should refer to the +:ref:`install-index` chapter. + + +.. _distutils-concepts: + +Concepts & Terminology +====================== + +Using the Distutils is quite simple, both for module developers and for +users/administrators installing third-party modules. As a developer, your +responsibilities (apart from writing solid, well-documented and well-tested +code, of course!) are: + +* write a setup script (:file:`setup.py` by convention) + +* (optional) write a setup configuration file + +* create a source distribution + +* (optional) create one or more built (binary) distributions + +Each of these tasks is covered in this document. + +Not all module developers have access to a multitude of platforms, so it's not +always feasible to expect them to create a multitude of built distributions. It +is hoped that a class of intermediaries, called *packagers*, will arise to +address this need. Packagers will take source distributions released by module +developers, build them on one or more platforms, and release the resulting built +distributions. Thus, users on the most popular platforms will be able to +install most popular Python module distributions in the most natural way for +their platform, without having to run a single setup script or compile a line of +code. + + +.. _distutils-simple-example: + +A Simple Example +================ + +The setup script is usually quite simple, although since it's written in Python, +there are no arbitrary limits to what you can do with it, though you should be +careful about putting arbitrarily expensive operations in your setup script. +Unlike, say, Autoconf-style configure scripts, the setup script may be run +multiple times in the course of building and installing your module +distribution. + +If all you want to do is distribute a module called :mod:`foo`, contained in a +file :file:`foo.py`, then your setup script can be as simple as this:: + + from distutils.core import setup + setup(name='foo', + version='1.0', + py_modules=['foo'], + ) + +Some observations: + +* most information that you supply to the Distutils is supplied as keyword + arguments to the :func:`setup` function + +* those keyword arguments fall into two categories: package metadata (name, + version number) and information about what's in the package (a list of pure + Python modules, in this case) + +* modules are specified by module name, not filename (the same will hold true + for packages and extensions) + +* it's recommended that you supply a little more metadata, in particular your + name, email address and a URL for the project (see section :ref:`setup-script` + for an example) + +To create a source distribution for this module, you would create a setup +script, :file:`setup.py`, containing the above code, and run this command from a +terminal:: + + python setup.py sdist + +For Windows, open a command prompt window (:menuselection:`Start --> +Accessories`) and change the command to:: + + setup.py sdist + +:command:`sdist` will create an archive file (e.g., tarball on Unix, ZIP file on Windows) +containing your setup script :file:`setup.py`, and your module :file:`foo.py`. +The archive file will be named :file:`foo-1.0.tar.gz` (or :file:`.zip`), and +will unpack into a directory :file:`foo-1.0`. + +If an end-user wishes to install your :mod:`foo` module, all they have to do is +download :file:`foo-1.0.tar.gz` (or :file:`.zip`), unpack it, and---from the +:file:`foo-1.0` directory---run :: + + python setup.py install + +which will ultimately copy :file:`foo.py` to the appropriate directory for +third-party modules in their Python installation. + +This simple example demonstrates some fundamental concepts of the Distutils. +First, both developers and installers have the same basic user interface, i.e. +the setup script. The difference is which Distutils *commands* they use: the +:command:`sdist` command is almost exclusively for module developers, while +:command:`install` is more often for installers (although most developers will +want to install their own code occasionally). + +If you want to make things really easy for your users, you can create one or +more built distributions for them. For instance, if you are running on a +Windows machine, and want to make things easy for other Windows users, you can +create an executable installer (the most appropriate type of built distribution +for this platform) with the :command:`bdist_wininst` command. For example:: + + python setup.py bdist_wininst + +will create an executable installer, :file:`foo-1.0.win32.exe`, in the current +directory. + +Other useful built distribution formats are RPM, implemented by the +:command:`bdist_rpm` command, Solaris :program:`pkgtool` +(:command:`bdist_pkgtool`), and HP-UX :program:`swinstall` +(:command:`bdist_sdux`). For example, the following command will create an RPM +file called :file:`foo-1.0.noarch.rpm`:: + + python setup.py bdist_rpm + +(The :command:`bdist_rpm` command uses the :command:`rpm` executable, therefore +this has to be run on an RPM-based system such as Red Hat Linux, SuSE Linux, or +Mandrake Linux.) + +You can find out what distribution formats are available at any time by running +:: + + python setup.py bdist --help-formats + + +.. _python-terms: + +General Python terminology +========================== + +If you're reading this document, you probably have a good idea of what modules, +extensions, and so forth are. Nevertheless, just to be sure that everyone is +operating from a common starting point, we offer the following glossary of +common Python terms: + +module + the basic unit of code reusability in Python: a block of code imported by some + other code. Three types of modules concern us here: pure Python modules, + extension modules, and packages. + +pure Python module + a module written in Python and contained in a single :file:`.py` file (and + possibly associated :file:`.pyc` files). Sometimes referred to as a + "pure module." + +extension module + a module written in the low-level language of the Python implementation: C/C++ + for Python, Java for Jython. Typically contained in a single dynamically + loadable pre-compiled file, e.g. a shared object (:file:`.so`) file for Python + extensions on Unix, a DLL (given the :file:`.pyd` extension) for Python + extensions on Windows, or a Java class file for Jython extensions. (Note that + currently, the Distutils only handles C/C++ extensions for Python.) + +package + a module that contains other modules; typically contained in a directory in the + filesystem and distinguished from other directories by the presence of a file + :file:`__init__.py`. + +root package + the root of the hierarchy of packages. (This isn't really a package, since it + doesn't have an :file:`__init__.py` file. But we have to call it something.) + The vast majority of the standard library is in the root package, as are many + small, standalone third-party modules that don't belong to a larger module + collection. Unlike regular packages, modules in the root package can be found in + many directories: in fact, every directory listed in ``sys.path`` contributes + modules to the root package. + + +.. _distutils-term: + +Distutils-specific terminology +============================== + +The following terms apply more specifically to the domain of distributing Python +modules using the Distutils: + +module distribution + a collection of Python modules distributed together as a single downloadable + resource and meant to be installed *en masse*. Examples of some well-known + module distributions are NumPy, SciPy, Pillow, + or mxBase. (This would be called a *package*, except that term is + already taken in the Python context: a single module distribution may contain + zero, one, or many Python packages.) + +pure module distribution + a module distribution that contains only pure Python modules and packages. + Sometimes referred to as a "pure distribution." + +non-pure module distribution + a module distribution that contains at least one extension module. Sometimes + referred to as a "non-pure distribution." + +distribution root + the top-level directory of your source tree (or source distribution); the + directory where :file:`setup.py` exists. Generally :file:`setup.py` will be + run from this directory. diff --git a/cpython_2/environment/repo/Doc/distutils/packageindex.rst b/cpython_2/environment/repo/Doc/distutils/packageindex.rst new file mode 100644 index 0000000000000000000000000000000000000000..ccb9a598b2b7a2955e5377a0e47d24abdced6dea --- /dev/null +++ b/cpython_2/environment/repo/Doc/distutils/packageindex.rst @@ -0,0 +1,16 @@ +:orphan: + +.. _package-index: + +******************************* +The Python Package Index (PyPI) +******************************* + +The `Python Package Index (PyPI)`_ stores metadata describing distributions +packaged with distutils and other publishing tools, as well the distribution +archives themselves. + +References to up to date PyPI documentation can be found at +:ref:`publishing-python-packages`. + +.. _Python Package Index (PyPI): https://pypi.org diff --git a/cpython_2/environment/repo/Doc/distutils/setupscript.rst b/cpython_2/environment/repo/Doc/distutils/setupscript.rst new file mode 100644 index 0000000000000000000000000000000000000000..4386a60b664bfb3581a8d554cdbf6278164a34dc --- /dev/null +++ b/cpython_2/environment/repo/Doc/distutils/setupscript.rst @@ -0,0 +1,713 @@ +.. _setup-script: + +************************ +Writing the Setup Script +************************ + +.. include:: ./_setuptools_disclaimer.rst + +The setup script is the centre of all activity in building, distributing, and +installing modules using the Distutils. The main purpose of the setup script is +to describe your module distribution to the Distutils, so that the various +commands that operate on your modules do the right thing. As we saw in section +:ref:`distutils-simple-example` above, the setup script consists mainly of a call to +:func:`setup`, and most information supplied to the Distutils by the module +developer is supplied as keyword arguments to :func:`setup`. + +Here's a slightly more involved example, which we'll follow for the next couple +of sections: the Distutils' own setup script. (Keep in mind that although the +Distutils are included with Python 1.6 and later, they also have an independent +existence so that Python 1.5.2 users can use them to install other module +distributions. The Distutils' own setup script, shown here, is used to install +the package into Python 1.5.2.) :: + + #!/usr/bin/env python + + from distutils.core import setup + + setup(name='Distutils', + version='1.0', + description='Python Distribution Utilities', + author='Greg Ward', + author_email='gward@python.net', + url='https://www.python.org/sigs/distutils-sig/', + packages=['distutils', 'distutils.command'], + ) + +There are only two differences between this and the trivial one-file +distribution presented in section :ref:`distutils-simple-example`: more metadata, and the +specification of pure Python modules by package, rather than by module. This is +important since the Distutils consist of a couple of dozen modules split into +(so far) two packages; an explicit list of every module would be tedious to +generate and difficult to maintain. For more information on the additional +meta-data, see section :ref:`meta-data`. + +Note that any pathnames (files or directories) supplied in the setup script +should be written using the Unix convention, i.e. slash-separated. The +Distutils will take care of converting this platform-neutral representation into +whatever is appropriate on your current platform before actually using the +pathname. This makes your setup script portable across operating systems, which +of course is one of the major goals of the Distutils. In this spirit, all +pathnames in this document are slash-separated. + +This, of course, only applies to pathnames given to Distutils functions. If +you, for example, use standard Python functions such as :func:`glob.glob` or +:func:`os.listdir` to specify files, you should be careful to write portable +code instead of hardcoding path separators:: + + glob.glob(os.path.join('mydir', 'subdir', '*.html')) + os.listdir(os.path.join('mydir', 'subdir')) + + +.. _listing-packages: + +Listing whole packages +====================== + +The ``packages`` option tells the Distutils to process (build, distribute, +install, etc.) all pure Python modules found in each package mentioned in the +``packages`` list. In order to do this, of course, there has to be a +correspondence between package names and directories in the filesystem. The +default correspondence is the most obvious one, i.e. package :mod:`distutils` is +found in the directory :file:`distutils` relative to the distribution root. +Thus, when you say ``packages = ['foo']`` in your setup script, you are +promising that the Distutils will find a file :file:`foo/__init__.py` (which +might be spelled differently on your system, but you get the idea) relative to +the directory where your setup script lives. If you break this promise, the +Distutils will issue a warning but still process the broken package anyway. + +If you use a different convention to lay out your source directory, that's no +problem: you just have to supply the ``package_dir`` option to tell the +Distutils about your convention. For example, say you keep all Python source +under :file:`lib`, so that modules in the "root package" (i.e., not in any +package at all) are in :file:`lib`, modules in the :mod:`foo` package are in +:file:`lib/foo`, and so forth. Then you would put :: + + package_dir = {'': 'lib'} + +in your setup script. The keys to this dictionary are package names, and an +empty package name stands for the root package. The values are directory names +relative to your distribution root. In this case, when you say ``packages = +['foo']``, you are promising that the file :file:`lib/foo/__init__.py` exists. + +Another possible convention is to put the :mod:`foo` package right in +:file:`lib`, the :mod:`foo.bar` package in :file:`lib/bar`, etc. This would be +written in the setup script as :: + + package_dir = {'foo': 'lib'} + +A ``package: dir`` entry in the ``package_dir`` dictionary implicitly +applies to all packages below *package*, so the :mod:`foo.bar` case is +automatically handled here. In this example, having ``packages = ['foo', +'foo.bar']`` tells the Distutils to look for :file:`lib/__init__.py` and +:file:`lib/bar/__init__.py`. (Keep in mind that although ``package_dir`` +applies recursively, you must explicitly list all packages in +``packages``: the Distutils will *not* recursively scan your source tree +looking for any directory with an :file:`__init__.py` file.) + + +.. _listing-modules: + +Listing individual modules +========================== + +For a small module distribution, you might prefer to list all modules rather +than listing packages---especially the case of a single module that goes in the +"root package" (i.e., no package at all). This simplest case was shown in +section :ref:`distutils-simple-example`; here is a slightly more involved example:: + + py_modules = ['mod1', 'pkg.mod2'] + +This describes two modules, one of them in the "root" package, the other in the +:mod:`pkg` package. Again, the default package/directory layout implies that +these two modules can be found in :file:`mod1.py` and :file:`pkg/mod2.py`, and +that :file:`pkg/__init__.py` exists as well. And again, you can override the +package/directory correspondence using the ``package_dir`` option. + + +.. _describing-extensions: + +Describing extension modules +============================ + +Just as writing Python extension modules is a bit more complicated than writing +pure Python modules, describing them to the Distutils is a bit more complicated. +Unlike pure modules, it's not enough just to list modules or packages and expect +the Distutils to go out and find the right files; you have to specify the +extension name, source file(s), and any compile/link requirements (include +directories, libraries to link with, etc.). + +.. XXX read over this section + +All of this is done through another keyword argument to :func:`setup`, the +``ext_modules`` option. ``ext_modules`` is just a list of +:class:`~distutils.core.Extension` instances, each of which describes a +single extension module. +Suppose your distribution includes a single extension, called :mod:`foo` and +implemented by :file:`foo.c`. If no additional instructions to the +compiler/linker are needed, describing this extension is quite simple:: + + Extension('foo', ['foo.c']) + +The :class:`Extension` class can be imported from :mod:`distutils.core` along +with :func:`setup`. Thus, the setup script for a module distribution that +contains only this one extension and nothing else might be:: + + from distutils.core import setup, Extension + setup(name='foo', + version='1.0', + ext_modules=[Extension('foo', ['foo.c'])], + ) + +The :class:`Extension` class (actually, the underlying extension-building +machinery implemented by the :command:`build_ext` command) supports a great deal +of flexibility in describing Python extensions, which is explained in the +following sections. + + +Extension names and packages +---------------------------- + +The first argument to the :class:`~distutils.core.Extension` constructor is +always the name of the extension, including any package names. For example, :: + + Extension('foo', ['src/foo1.c', 'src/foo2.c']) + +describes an extension that lives in the root package, while :: + + Extension('pkg.foo', ['src/foo1.c', 'src/foo2.c']) + +describes the same extension in the :mod:`pkg` package. The source files and +resulting object code are identical in both cases; the only difference is where +in the filesystem (and therefore where in Python's namespace hierarchy) the +resulting extension lives. + +If you have a number of extensions all in the same package (or all under the +same base package), use the ``ext_package`` keyword argument to +:func:`setup`. For example, :: + + setup(..., + ext_package='pkg', + ext_modules=[Extension('foo', ['foo.c']), + Extension('subpkg.bar', ['bar.c'])], + ) + +will compile :file:`foo.c` to the extension :mod:`pkg.foo`, and :file:`bar.c` to +:mod:`pkg.subpkg.bar`. + + +Extension source files +---------------------- + +The second argument to the :class:`~distutils.core.Extension` constructor is +a list of source +files. Since the Distutils currently only support C, C++, and Objective-C +extensions, these are normally C/C++/Objective-C source files. (Be sure to use +appropriate extensions to distinguish C++ source files: :file:`.cc` and +:file:`.cpp` seem to be recognized by both Unix and Windows compilers.) + +However, you can also include SWIG interface (:file:`.i`) files in the list; the +:command:`build_ext` command knows how to deal with SWIG extensions: it will run +SWIG on the interface file and compile the resulting C/C++ file into your +extension. + +.. XXX SWIG support is rough around the edges and largely untested! + +This warning notwithstanding, options to SWIG can be currently passed like +this:: + + setup(..., + ext_modules=[Extension('_foo', ['foo.i'], + swig_opts=['-modern', '-I../include'])], + py_modules=['foo'], + ) + +Or on the commandline like this:: + + > python setup.py build_ext --swig-opts="-modern -I../include" + +On some platforms, you can include non-source files that are processed by the +compiler and included in your extension. Currently, this just means Windows +message text (:file:`.mc`) files and resource definition (:file:`.rc`) files for +Visual C++. These will be compiled to binary resource (:file:`.res`) files and +linked into the executable. + + +Preprocessor options +-------------------- + +Three optional arguments to :class:`~distutils.core.Extension` will help if +you need to specify include directories to search or preprocessor macros to +define/undefine: ``include_dirs``, ``define_macros``, and ``undef_macros``. + +For example, if your extension requires header files in the :file:`include` +directory under your distribution root, use the ``include_dirs`` option:: + + Extension('foo', ['foo.c'], include_dirs=['include']) + +You can specify absolute directories there; if you know that your extension will +only be built on Unix systems with X11R6 installed to :file:`/usr`, you can get +away with :: + + Extension('foo', ['foo.c'], include_dirs=['/usr/include/X11']) + +You should avoid this sort of non-portable usage if you plan to distribute your +code: it's probably better to write C code like :: + + #include <X11/Xlib.h> + +If you need to include header files from some other Python extension, you can +take advantage of the fact that header files are installed in a consistent way +by the Distutils :command:`install_headers` command. For example, the Numerical +Python header files are installed (on a standard Unix installation) to +:file:`/usr/local/include/python1.5/Numerical`. (The exact location will differ +according to your platform and Python installation.) Since the Python include +directory---\ :file:`/usr/local/include/python1.5` in this case---is always +included in the search path when building Python extensions, the best approach +is to write C code like :: + + #include <Numerical/arrayobject.h> + +If you must put the :file:`Numerical` include directory right into your header +search path, though, you can find that directory using the Distutils +:mod:`distutils.sysconfig` module:: + + from distutils.sysconfig import get_python_inc + incdir = os.path.join(get_python_inc(plat_specific=1), 'Numerical') + setup(..., + Extension(..., include_dirs=[incdir]), + ) + +Even though this is quite portable---it will work on any Python installation, +regardless of platform---it's probably easier to just write your C code in the +sensible way. + +You can define and undefine pre-processor macros with the ``define_macros`` and +``undef_macros`` options. ``define_macros`` takes a list of ``(name, value)`` +tuples, where ``name`` is the name of the macro to define (a string) and +``value`` is its value: either a string or ``None``. (Defining a macro ``FOO`` +to ``None`` is the equivalent of a bare ``#define FOO`` in your C source: with +most compilers, this sets ``FOO`` to the string ``1``.) ``undef_macros`` is +just a list of macros to undefine. + +For example:: + + Extension(..., + define_macros=[('NDEBUG', '1'), + ('HAVE_STRFTIME', None)], + undef_macros=['HAVE_FOO', 'HAVE_BAR']) + +is the equivalent of having this at the top of every C source file:: + + #define NDEBUG 1 + #define HAVE_STRFTIME + #undef HAVE_FOO + #undef HAVE_BAR + + +Library options +--------------- + +You can also specify the libraries to link against when building your extension, +and the directories to search for those libraries. The ``libraries`` option is +a list of libraries to link against, ``library_dirs`` is a list of directories +to search for libraries at link-time, and ``runtime_library_dirs`` is a list of +directories to search for shared (dynamically loaded) libraries at run-time. + +For example, if you need to link against libraries known to be in the standard +library search path on target systems :: + + Extension(..., + libraries=['gdbm', 'readline']) + +If you need to link with libraries in a non-standard location, you'll have to +include the location in ``library_dirs``:: + + Extension(..., + library_dirs=['/usr/X11R6/lib'], + libraries=['X11', 'Xt']) + +(Again, this sort of non-portable construct should be avoided if you intend to +distribute your code.) + +.. XXX Should mention clib libraries here or somewhere else! + + +Other options +------------- + +There are still some other options which can be used to handle special cases. + +The ``optional`` option is a boolean; if it is true, +a build failure in the extension will not abort the build process, but +instead simply not install the failing extension. + +The ``extra_objects`` option is a list of object files to be passed to the +linker. These files must not have extensions, as the default extension for the +compiler is used. + +``extra_compile_args`` and ``extra_link_args`` can be used to +specify additional command line options for the respective compiler and linker +command lines. + +``export_symbols`` is only useful on Windows. It can contain a list of +symbols (functions or variables) to be exported. This option is not needed when +building compiled extensions: Distutils will automatically add ``initmodule`` +to the list of exported symbols. + +The ``depends`` option is a list of files that the extension depends on +(for example header files). The build command will call the compiler on the +sources to rebuild extension if any on this files has been modified since the +previous build. + +Relationships between Distributions and Packages +================================================ + +A distribution may relate to packages in three specific ways: + +#. It can require packages or modules. + +#. It can provide packages or modules. + +#. It can obsolete packages or modules. + +These relationships can be specified using keyword arguments to the +:func:`distutils.core.setup` function. + +Dependencies on other Python modules and packages can be specified by supplying +the *requires* keyword argument to :func:`setup`. The value must be a list of +strings. Each string specifies a package that is required, and optionally what +versions are sufficient. + +To specify that any version of a module or package is required, the string +should consist entirely of the module or package name. Examples include +``'mymodule'`` and ``'xml.parsers.expat'``. + +If specific versions are required, a sequence of qualifiers can be supplied in +parentheses. Each qualifier may consist of a comparison operator and a version +number. The accepted comparison operators are:: + + < > == + <= >= != + +These can be combined by using multiple qualifiers separated by commas (and +optional whitespace). In this case, all of the qualifiers must be matched; a +logical AND is used to combine the evaluations. + +Let's look at a bunch of examples: + ++-------------------------+----------------------------------------------+ +| Requires Expression | Explanation | ++=========================+==============================================+ +| ``==1.0`` | Only version ``1.0`` is compatible | ++-------------------------+----------------------------------------------+ +| ``>1.0, !=1.5.1, <2.0`` | Any version after ``1.0`` and before ``2.0`` | +| | is compatible, except ``1.5.1`` | ++-------------------------+----------------------------------------------+ + +Now that we can specify dependencies, we also need to be able to specify what we +provide that other distributions can require. This is done using the *provides* +keyword argument to :func:`setup`. The value for this keyword is a list of +strings, each of which names a Python module or package, and optionally +identifies the version. If the version is not specified, it is assumed to match +that of the distribution. + +Some examples: + ++---------------------+----------------------------------------------+ +| Provides Expression | Explanation | ++=====================+==============================================+ +| ``mypkg`` | Provide ``mypkg``, using the distribution | +| | version | ++---------------------+----------------------------------------------+ +| ``mypkg (1.1)`` | Provide ``mypkg`` version 1.1, regardless of | +| | the distribution version | ++---------------------+----------------------------------------------+ + +A package can declare that it obsoletes other packages using the *obsoletes* +keyword argument. The value for this is similar to that of the *requires* +keyword: a list of strings giving module or package specifiers. Each specifier +consists of a module or package name optionally followed by one or more version +qualifiers. Version qualifiers are given in parentheses after the module or +package name. + +The versions identified by the qualifiers are those that are obsoleted by the +distribution being described. If no qualifiers are given, all versions of the +named module or package are understood to be obsoleted. + +.. _distutils-installing-scripts: + +Installing Scripts +================== + +So far we have been dealing with pure and non-pure Python modules, which are +usually not run by themselves but imported by scripts. + +Scripts are files containing Python source code, intended to be started from the +command line. Scripts don't require Distutils to do anything very complicated. +The only clever feature is that if the first line of the script starts with +``#!`` and contains the word "python", the Distutils will adjust the first line +to refer to the current interpreter location. By default, it is replaced with +the current interpreter location. The :option:`!--executable` (or :option:`!-e`) +option will allow the interpreter path to be explicitly overridden. + +The ``scripts`` option simply is a list of files to be handled in this +way. From the PyXML setup script:: + + setup(..., + scripts=['scripts/xmlproc_parse', 'scripts/xmlproc_val'] + ) + +.. versionchanged:: 3.1 + All the scripts will also be added to the ``MANIFEST`` file if no template is + provided. See :ref:`manifest`. + + +.. _distutils-installing-package-data: + +Installing Package Data +======================= + +Often, additional files need to be installed into a package. These files are +often data that's closely related to the package's implementation, or text files +containing documentation that might be of interest to programmers using the +package. These files are called :dfn:`package data`. + +Package data can be added to packages using the ``package_data`` keyword +argument to the :func:`setup` function. The value must be a mapping from +package name to a list of relative path names that should be copied into the +package. The paths are interpreted as relative to the directory containing the +package (information from the ``package_dir`` mapping is used if appropriate); +that is, the files are expected to be part of the package in the source +directories. They may contain glob patterns as well. + +The path names may contain directory portions; any necessary directories will be +created in the installation. + +For example, if a package should contain a subdirectory with several data files, +the files can be arranged like this in the source tree:: + + setup.py + src/ + mypkg/ + __init__.py + module.py + data/ + tables.dat + spoons.dat + forks.dat + +The corresponding call to :func:`setup` might be:: + + setup(..., + packages=['mypkg'], + package_dir={'mypkg': 'src/mypkg'}, + package_data={'mypkg': ['data/*.dat']}, + ) + + +.. versionchanged:: 3.1 + All the files that match ``package_data`` will be added to the ``MANIFEST`` + file if no template is provided. See :ref:`manifest`. + + +.. _distutils-additional-files: + +Installing Additional Files +=========================== + +The ``data_files`` option can be used to specify additional files needed +by the module distribution: configuration files, message catalogs, data files, +anything which doesn't fit in the previous categories. + +``data_files`` specifies a sequence of (*directory*, *files*) pairs in the +following way:: + + setup(..., + data_files=[('bitmaps', ['bm/b1.gif', 'bm/b2.gif']), + ('config', ['cfg/data.cfg'])], + ) + +Each (*directory*, *files*) pair in the sequence specifies the installation +directory and the files to install there. + +Each file name in *files* is interpreted relative to the :file:`setup.py` +script at the top of the package source distribution. Note that you can +specify the directory where the data files will be installed, but you cannot +rename the data files themselves. + +The *directory* should be a relative path. It is interpreted relative to the +installation prefix (Python's ``sys.prefix`` for system installations; +``site.USER_BASE`` for user installations). Distutils allows *directory* to be +an absolute installation path, but this is discouraged since it is +incompatible with the wheel packaging format. No directory information from +*files* is used to determine the final location of the installed file; only +the name of the file is used. + +You can specify the ``data_files`` options as a simple sequence of files +without specifying a target directory, but this is not recommended, and the +:command:`install` command will print a warning in this case. To install data +files directly in the target directory, an empty string should be given as the +directory. + +.. versionchanged:: 3.1 + All the files that match ``data_files`` will be added to the ``MANIFEST`` + file if no template is provided. See :ref:`manifest`. + + +.. _meta-data: + +Additional meta-data +==================== + +The setup script may include additional meta-data beyond the name and version. +This information includes: + ++----------------------+---------------------------+-----------------+--------+ +| Meta-Data | Description | Value | Notes | ++======================+===========================+=================+========+ +| ``name`` | name of the package | short string | \(1) | ++----------------------+---------------------------+-----------------+--------+ +| ``version`` | version of this release | short string | (1)(2) | ++----------------------+---------------------------+-----------------+--------+ +| ``author`` | package author's name | short string | \(3) | ++----------------------+---------------------------+-----------------+--------+ +| ``author_email`` | email address of the | email address | \(3) | +| | package author | | | ++----------------------+---------------------------+-----------------+--------+ +| ``maintainer`` | package maintainer's name | short string | \(3) | ++----------------------+---------------------------+-----------------+--------+ +| ``maintainer_email`` | email address of the | email address | \(3) | +| | package maintainer | | | ++----------------------+---------------------------+-----------------+--------+ +| ``url`` | home page for the package | URL | \(1) | ++----------------------+---------------------------+-----------------+--------+ +| ``description`` | short, summary | short string | | +| | description of the | | | +| | package | | | ++----------------------+---------------------------+-----------------+--------+ +| ``long_description`` | longer description of the | long string | \(4) | +| | package | | | ++----------------------+---------------------------+-----------------+--------+ +| ``download_url`` | location where the | URL | | +| | package may be downloaded | | | ++----------------------+---------------------------+-----------------+--------+ +| ``classifiers`` | a list of classifiers | list of strings | (6)(7) | ++----------------------+---------------------------+-----------------+--------+ +| ``platforms`` | a list of platforms | list of strings | (6)(8) | ++----------------------+---------------------------+-----------------+--------+ +| ``keywords`` | a list of keywords | list of strings | (6)(8) | ++----------------------+---------------------------+-----------------+--------+ +| ``license`` | license for the package | short string | \(5) | ++----------------------+---------------------------+-----------------+--------+ + +Notes: + +(1) + These fields are required. + +(2) + It is recommended that versions take the form *major.minor[.patch[.sub]]*. + +(3) + Either the author or the maintainer must be identified. If maintainer is + provided, distutils lists it as the author in :file:`PKG-INFO`. + +(4) + The ``long_description`` field is used by PyPI when you publish a package, + to build its project page. + +(5) + The ``license`` field is a text indicating the license covering the + package where the license is not a selection from the "License" Trove + classifiers. See the ``Classifier`` field. Notice that + there's a ``licence`` distribution option which is deprecated but still + acts as an alias for ``license``. + +(6) + This field must be a list. + +(7) + The valid classifiers are listed on + `PyPI <https://pypi.org/classifiers>`_. + +(8) + To preserve backward compatibility, this field also accepts a string. If + you pass a comma-separated string ``'foo, bar'``, it will be converted to + ``['foo', 'bar']``, Otherwise, it will be converted to a list of one + string. + +'short string' + A single line of text, not more than 200 characters. + +'long string' + Multiple lines of plain text in reStructuredText format (see + http://docutils.sourceforge.net/). + +'list of strings' + See below. + +Encoding the version information is an art in itself. Python packages generally +adhere to the version format *major.minor[.patch][sub]*. The major number is 0 +for initial, experimental releases of software. It is incremented for releases +that represent major milestones in a package. The minor number is incremented +when important new features are added to the package. The patch number +increments when bug-fix releases are made. Additional trailing version +information is sometimes used to indicate sub-releases. These are +"a1,a2,...,aN" (for alpha releases, where functionality and API may change), +"b1,b2,...,bN" (for beta releases, which only fix bugs) and "pr1,pr2,...,prN" +(for final pre-release release testing). Some examples: + +0.1.0 + the first, experimental release of a package + +1.0.1a2 + the second alpha release of the first patch version of 1.0 + +``classifiers`` must be specified in a list:: + + setup(..., + classifiers=[ + 'Development Status :: 4 - Beta', + 'Environment :: Console', + 'Environment :: Web Environment', + 'Intended Audience :: End Users/Desktop', + 'Intended Audience :: Developers', + 'Intended Audience :: System Administrators', + 'License :: OSI Approved :: Python Software Foundation License', + 'Operating System :: MacOS :: MacOS X', + 'Operating System :: Microsoft :: Windows', + 'Operating System :: POSIX', + 'Programming Language :: Python', + 'Topic :: Communications :: Email', + 'Topic :: Office/Business', + 'Topic :: Software Development :: Bug Tracking', + ], + ) + +.. versionchanged:: 3.7 + :class:`~distutils.core.setup` now warns when ``classifiers``, ``keywords`` + or ``platforms`` fields are not specified as a list or a string. + +.. _debug-setup-script: + +Debugging the setup script +========================== + +Sometimes things go wrong, and the setup script doesn't do what the developer +wants. + +Distutils catches any exceptions when running the setup script, and print a +simple error message before the script is terminated. The motivation for this +behaviour is to not confuse administrators who don't know much about Python and +are trying to install a package. If they get a big long traceback from deep +inside the guts of Distutils, they may think the package or the Python +installation is broken because they don't read all the way down to the bottom +and see that it's a permission problem. + +On the other hand, this doesn't help the developer to find the cause of the +failure. For this purpose, the :envvar:`DISTUTILS_DEBUG` environment variable can be set +to anything except an empty string, and distutils will now print detailed +information about what it is doing, dump the full traceback when an exception +occurs, and print the whole command line when an external program (like a C +compiler) fails. diff --git a/cpython_2/environment/repo/Doc/distutils/sourcedist.rst b/cpython_2/environment/repo/Doc/distutils/sourcedist.rst new file mode 100644 index 0000000000000000000000000000000000000000..0600663d00e9dc28b523bd6c8e1855d0a9d61206 --- /dev/null +++ b/cpython_2/environment/repo/Doc/distutils/sourcedist.rst @@ -0,0 +1,242 @@ +.. _source-dist: + +****************************** +Creating a Source Distribution +****************************** + +.. include:: ./_setuptools_disclaimer.rst + +As shown in section :ref:`distutils-simple-example`, you use the :command:`sdist` command +to create a source distribution. In the simplest case, :: + + python setup.py sdist + +(assuming you haven't specified any :command:`sdist` options in the setup script +or config file), :command:`sdist` creates the archive of the default format for +the current platform. The default format is a gzip'ed tar file +(:file:`.tar.gz`) on Unix, and ZIP file on Windows. + +You can specify as many formats as you like using the :option:`!--formats` +option, for example:: + + python setup.py sdist --formats=gztar,zip + +to create a gzipped tarball and a zip file. The available formats are: + ++-----------+-------------------------+---------+ +| Format | Description | Notes | ++===========+=========================+=========+ +| ``zip`` | zip file (:file:`.zip`) | (1),(3) | ++-----------+-------------------------+---------+ +| ``gztar`` | gzip'ed tar file | \(2) | +| | (:file:`.tar.gz`) | | ++-----------+-------------------------+---------+ +| ``bztar`` | bzip2'ed tar file | | +| | (:file:`.tar.bz2`) | | ++-----------+-------------------------+---------+ +| ``xztar`` | xz'ed tar file | | +| | (:file:`.tar.xz`) | | ++-----------+-------------------------+---------+ +| ``ztar`` | compressed tar file | \(4) | +| | (:file:`.tar.Z`) | | ++-----------+-------------------------+---------+ +| ``tar`` | tar file (:file:`.tar`) | | ++-----------+-------------------------+---------+ + +.. versionchanged:: 3.5 + Added support for the ``xztar`` format. + +Notes: + +(1) + default on Windows + +(2) + default on Unix + +(3) + requires either external :program:`zip` utility or :mod:`zipfile` module (part + of the standard Python library since Python 1.6) + +(4) + requires the :program:`compress` program. Notice that this format is now + pending for deprecation and will be removed in the future versions of Python. + +When using any ``tar`` format (``gztar``, ``bztar``, ``xztar``, ``ztar`` or +``tar``), under Unix you can specify the ``owner`` and ``group`` names +that will be set for each member of the archive. + +For example, if you want all files of the archive to be owned by root:: + + python setup.py sdist --owner=root --group=root + + +.. _manifest: + +Specifying the files to distribute +================================== + +If you don't supply an explicit list of files (or instructions on how to +generate one), the :command:`sdist` command puts a minimal default set into the +source distribution: + +* all Python source files implied by the ``py_modules`` and + ``packages`` options + +* all C source files mentioned in the ``ext_modules`` or + ``libraries`` options + + .. XXX getting C library sources currently broken---no + :meth:`get_source_files` method in :file:`build_clib.py`! + +* scripts identified by the ``scripts`` option + See :ref:`distutils-installing-scripts`. + +* anything that looks like a test script: :file:`test/test\*.py` (currently, the + Distutils don't do anything with test scripts except include them in source + distributions, but in the future there will be a standard for testing Python + module distributions) + +* Any of the standard README files (:file:`README`, :file:`README.txt`, + or :file:`README.rst`), :file:`setup.py` (or whatever you called your setup + script), and :file:`setup.cfg`. + +* all files that matches the ``package_data`` metadata. + See :ref:`distutils-installing-package-data`. + +* all files that matches the ``data_files`` metadata. + See :ref:`distutils-additional-files`. + +Sometimes this is enough, but usually you will want to specify additional files +to distribute. The typical way to do this is to write a *manifest template*, +called :file:`MANIFEST.in` by default. The manifest template is just a list of +instructions for how to generate your manifest file, :file:`MANIFEST`, which is +the exact list of files to include in your source distribution. The +:command:`sdist` command processes this template and generates a manifest based +on its instructions and what it finds in the filesystem. + +If you prefer to roll your own manifest file, the format is simple: one filename +per line, regular files (or symlinks to them) only. If you do supply your own +:file:`MANIFEST`, you must specify everything: the default set of files +described above does not apply in this case. + +.. versionchanged:: 3.1 + An existing generated :file:`MANIFEST` will be regenerated without + :command:`sdist` comparing its modification time to the one of + :file:`MANIFEST.in` or :file:`setup.py`. + +.. versionchanged:: 3.1.3 + :file:`MANIFEST` files start with a comment indicating they are generated. + Files without this comment are not overwritten or removed. + +.. versionchanged:: 3.2.2 + :command:`sdist` will read a :file:`MANIFEST` file if no :file:`MANIFEST.in` + exists, like it used to do. + +.. versionchanged:: 3.7 + :file:`README.rst` is now included in the list of distutils standard READMEs. + + +The manifest template has one command per line, where each command specifies a +set of files to include or exclude from the source distribution. For an +example, again we turn to the Distutils' own manifest template: + +.. code-block:: none + + include *.txt + recursive-include examples *.txt *.py + prune examples/sample?/build + +The meanings should be fairly clear: include all files in the distribution root +matching :file:`\*.txt`, all files anywhere under the :file:`examples` directory +matching :file:`\*.txt` or :file:`\*.py`, and exclude all directories matching +:file:`examples/sample?/build`. All of this is done *after* the standard +include set, so you can exclude files from the standard set with explicit +instructions in the manifest template. (Or, you can use the +:option:`!--no-defaults` option to disable the standard set entirely.) There are +several other commands available in the manifest template mini-language; see +section :ref:`sdist-cmd`. + +The order of commands in the manifest template matters: initially, we have the +list of default files as described above, and each command in the template adds +to or removes from that list of files. Once we have fully processed the +manifest template, we remove files that should not be included in the source +distribution: + +* all files in the Distutils "build" tree (default :file:`build/`) + +* all files in directories named :file:`RCS`, :file:`CVS`, :file:`.svn`, + :file:`.hg`, :file:`.git`, :file:`.bzr` or :file:`_darcs` + +Now we have our complete list of files, which is written to the manifest for +future reference, and then used to build the source distribution archive(s). + +You can disable the default set of included files with the +:option:`!--no-defaults` option, and you can disable the standard exclude set +with :option:`!--no-prune`. + +Following the Distutils' own manifest template, let's trace how the +:command:`sdist` command builds the list of files to include in the Distutils +source distribution: + +#. include all Python source files in the :file:`distutils` and + :file:`distutils/command` subdirectories (because packages corresponding to + those two directories were mentioned in the ``packages`` option in the + setup script---see section :ref:`setup-script`) + +#. include :file:`README.txt`, :file:`setup.py`, and :file:`setup.cfg` (standard + files) + +#. include :file:`test/test\*.py` (standard files) + +#. include :file:`\*.txt` in the distribution root (this will find + :file:`README.txt` a second time, but such redundancies are weeded out later) + +#. include anything matching :file:`\*.txt` or :file:`\*.py` in the sub-tree + under :file:`examples`, + +#. exclude all files in the sub-trees starting at directories matching + :file:`examples/sample?/build`\ ---this may exclude files included by the + previous two steps, so it's important that the ``prune`` command in the manifest + template comes after the ``recursive-include`` command + +#. exclude the entire :file:`build` tree, and any :file:`RCS`, :file:`CVS`, + :file:`.svn`, :file:`.hg`, :file:`.git`, :file:`.bzr` and :file:`_darcs` + directories + +Just like in the setup script, file and directory names in the manifest template +should always be slash-separated; the Distutils will take care of converting +them to the standard representation on your platform. That way, the manifest +template is portable across operating systems. + + +.. _manifest-options: + +Manifest-related options +======================== + +The normal course of operations for the :command:`sdist` command is as follows: + +* if the manifest file (:file:`MANIFEST` by default) exists and the first line + does not have a comment indicating it is generated from :file:`MANIFEST.in`, + then it is used as is, unaltered + +* if the manifest file doesn't exist or has been previously automatically + generated, read :file:`MANIFEST.in` and create the manifest + +* if neither :file:`MANIFEST` nor :file:`MANIFEST.in` exist, create a manifest + with just the default file set + +* use the list of files now in :file:`MANIFEST` (either just generated or read + in) to create the source distribution archive(s) + +There are a couple of options that modify this behaviour. First, use the +:option:`!--no-defaults` and :option:`!--no-prune` to disable the standard +"include" and "exclude" sets. + +Second, you might just want to (re)generate the manifest, but not create a source +distribution:: + + python setup.py sdist --manifest-only + +:option:`!-o` is a shortcut for :option:`!--manifest-only`. diff --git a/cpython_2/environment/repo/Doc/distutils/uploading.rst b/cpython_2/environment/repo/Doc/distutils/uploading.rst new file mode 100644 index 0000000000000000000000000000000000000000..4c391cab072ea6a41d67b23c1f616123c4b9f1b3 --- /dev/null +++ b/cpython_2/environment/repo/Doc/distutils/uploading.rst @@ -0,0 +1,8 @@ +:orphan: + +*************************************** +Uploading Packages to the Package Index +*************************************** + +References to up to date PyPI documentation can be found at +:ref:`publishing-python-packages`. diff --git a/cpython_2/environment/repo/Doc/extending/building.rst b/cpython_2/environment/repo/Doc/extending/building.rst new file mode 100644 index 0000000000000000000000000000000000000000..753b5511ed9d6351ca9c6c27661fb961d42a92fc --- /dev/null +++ b/cpython_2/environment/repo/Doc/extending/building.rst @@ -0,0 +1,167 @@ +.. highlight:: c + +.. _building: + +***************************** +Building C and C++ Extensions +***************************** + +A C extension for CPython is a shared library (e.g. a ``.so`` file on Linux, +``.pyd`` on Windows), which exports an *initialization function*. + +To be importable, the shared library must be available on :envvar:`PYTHONPATH`, +and must be named after the module name, with an appropriate extension. +When using distutils, the correct filename is generated automatically. + +The initialization function has the signature: + +.. c:function:: PyObject* PyInit_modulename(void) + +It returns either a fully-initialized module, or a :c:type:`PyModuleDef` +instance. See :ref:`initializing-modules` for details. + +.. highlight:: python + +For modules with ASCII-only names, the function must be named +``PyInit_<modulename>``, with ``<modulename>`` replaced by the name of the +module. When using :ref:`multi-phase-initialization`, non-ASCII module names +are allowed. In this case, the initialization function name is +``PyInitU_<modulename>``, with ``<modulename>`` encoded using Python's +*punycode* encoding with hyphens replaced by underscores. In Python:: + + def initfunc_name(name): + try: + suffix = b'_' + name.encode('ascii') + except UnicodeEncodeError: + suffix = b'U_' + name.encode('punycode').replace(b'-', b'_') + return b'PyInit' + suffix + +It is possible to export multiple modules from a single shared library by +defining multiple initialization functions. However, importing them requires +using symbolic links or a custom importer, because by default only the +function corresponding to the filename is found. +See the *"Multiple modules in one library"* section in :pep:`489` for details. + + +.. highlight:: c + +Building C and C++ Extensions with distutils +============================================ + +.. sectionauthor:: Martin v. Löwis <martin@v.loewis.de> + +Extension modules can be built using distutils, which is included in Python. +Since distutils also supports creation of binary packages, users don't +necessarily need a compiler and distutils to install the extension. + +A distutils package contains a driver script, :file:`setup.py`. This is a plain +Python file, which, in the most simple case, could look like this: + +.. code-block:: python3 + + from distutils.core import setup, Extension + + module1 = Extension('demo', + sources = ['demo.c']) + + setup (name = 'PackageName', + version = '1.0', + description = 'This is a demo package', + ext_modules = [module1]) + + +With this :file:`setup.py`, and a file :file:`demo.c`, running :: + + python setup.py build + +will compile :file:`demo.c`, and produce an extension module named ``demo`` in +the :file:`build` directory. Depending on the system, the module file will end +up in a subdirectory :file:`build/lib.system`, and may have a name like +:file:`demo.so` or :file:`demo.pyd`. + +In the :file:`setup.py`, all execution is performed by calling the ``setup`` +function. This takes a variable number of keyword arguments, of which the +example above uses only a subset. Specifically, the example specifies +meta-information to build packages, and it specifies the contents of the +package. Normally, a package will contain additional modules, like Python +source modules, documentation, subpackages, etc. Please refer to the distutils +documentation in :ref:`distutils-index` to learn more about the features of +distutils; this section explains building extension modules only. + +It is common to pre-compute arguments to :func:`setup`, to better structure the +driver script. In the example above, the ``ext_modules`` argument to +:func:`~distutils.core.setup` is a list of extension modules, each of which is +an instance of +the :class:`~distutils.extension.Extension`. In the example, the instance +defines an extension named ``demo`` which is build by compiling a single source +file, :file:`demo.c`. + +In many cases, building an extension is more complex, since additional +preprocessor defines and libraries may be needed. This is demonstrated in the +example below. + +.. code-block:: python3 + + from distutils.core import setup, Extension + + module1 = Extension('demo', + define_macros = [('MAJOR_VERSION', '1'), + ('MINOR_VERSION', '0')], + include_dirs = ['/usr/local/include'], + libraries = ['tcl83'], + library_dirs = ['/usr/local/lib'], + sources = ['demo.c']) + + setup (name = 'PackageName', + version = '1.0', + description = 'This is a demo package', + author = 'Martin v. Loewis', + author_email = 'martin@v.loewis.de', + url = 'https://docs.python.org/extending/building', + long_description = ''' + This is really just a demo package. + ''', + ext_modules = [module1]) + + +In this example, :func:`~distutils.core.setup` is called with additional +meta-information, which +is recommended when distribution packages have to be built. For the extension +itself, it specifies preprocessor defines, include directories, library +directories, and libraries. Depending on the compiler, distutils passes this +information in different ways to the compiler. For example, on Unix, this may +result in the compilation commands :: + + gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -DMAJOR_VERSION=1 -DMINOR_VERSION=0 -I/usr/local/include -I/usr/local/include/python2.2 -c demo.c -o build/temp.linux-i686-2.2/demo.o + + gcc -shared build/temp.linux-i686-2.2/demo.o -L/usr/local/lib -ltcl83 -o build/lib.linux-i686-2.2/demo.so + +These lines are for demonstration purposes only; distutils users should trust +that distutils gets the invocations right. + + +.. _distributing: + +Distributing your extension modules +=================================== + +When an extension has been successfully built, there are three ways to use it. + +End-users will typically want to install the module, they do so by running :: + + python setup.py install + +Module maintainers should produce source packages; to do so, they run :: + + python setup.py sdist + +In some cases, additional files need to be included in a source distribution; +this is done through a :file:`MANIFEST.in` file; see :ref:`manifest` for details. + +If the source distribution has been built successfully, maintainers can also +create binary distributions. Depending on the platform, one of the following +commands can be used to do so. :: + + python setup.py bdist_wininst + python setup.py bdist_rpm + python setup.py bdist_dumb diff --git a/cpython_2/environment/repo/Doc/extending/embedding.rst b/cpython_2/environment/repo/Doc/extending/embedding.rst new file mode 100644 index 0000000000000000000000000000000000000000..5f5abdf9c15067b42e0cb2a064a5c5984d8a7b30 --- /dev/null +++ b/cpython_2/environment/repo/Doc/extending/embedding.rst @@ -0,0 +1,336 @@ +.. highlight:: c + + +.. _embedding: + +*************************************** +Embedding Python in Another Application +*************************************** + +The previous chapters discussed how to extend Python, that is, how to extend the +functionality of Python by attaching a library of C functions to it. It is also +possible to do it the other way around: enrich your C/C++ application by +embedding Python in it. Embedding provides your application with the ability to +implement some of the functionality of your application in Python rather than C +or C++. This can be used for many purposes; one example would be to allow users +to tailor the application to their needs by writing some scripts in Python. You +can also use it yourself if some of the functionality can be written in Python +more easily. + +Embedding Python is similar to extending it, but not quite. The difference is +that when you extend Python, the main program of the application is still the +Python interpreter, while if you embed Python, the main program may have nothing +to do with Python --- instead, some parts of the application occasionally call +the Python interpreter to run some Python code. + +So if you are embedding Python, you are providing your own main program. One of +the things this main program has to do is initialize the Python interpreter. At +the very least, you have to call the function :c:func:`Py_Initialize`. There are +optional calls to pass command line arguments to Python. Then later you can +call the interpreter from any part of the application. + +There are several different ways to call the interpreter: you can pass a string +containing Python statements to :c:func:`PyRun_SimpleString`, or you can pass a +stdio file pointer and a file name (for identification in error messages only) +to :c:func:`PyRun_SimpleFile`. You can also call the lower-level operations +described in the previous chapters to construct and use Python objects. + + +.. seealso:: + + :ref:`c-api-index` + The details of Python's C interface are given in this manual. A great deal of + necessary information can be found here. + + +.. _high-level-embedding: + +Very High Level Embedding +========================= + +The simplest form of embedding Python is the use of the very high level +interface. This interface is intended to execute a Python script without needing +to interact with the application directly. This can for example be used to +perform some operation on a file. :: + + #define PY_SSIZE_T_CLEAN + #include <Python.h> + + int + main(int argc, char *argv[]) + { + wchar_t *program = Py_DecodeLocale(argv[0], NULL); + if (program == NULL) { + fprintf(stderr, "Fatal error: cannot decode argv[0]\n"); + exit(1); + } + Py_SetProgramName(program); /* optional but recommended */ + Py_Initialize(); + PyRun_SimpleString("from time import time,ctime\n" + "print('Today is', ctime(time()))\n"); + if (Py_FinalizeEx() < 0) { + exit(120); + } + PyMem_RawFree(program); + return 0; + } + +The :c:func:`Py_SetProgramName` function should be called before +:c:func:`Py_Initialize` to inform the interpreter about paths to Python run-time +libraries. Next, the Python interpreter is initialized with +:c:func:`Py_Initialize`, followed by the execution of a hard-coded Python script +that prints the date and time. Afterwards, the :c:func:`Py_FinalizeEx` call shuts +the interpreter down, followed by the end of the program. In a real program, +you may want to get the Python script from another source, perhaps a text-editor +routine, a file, or a database. Getting the Python code from a file can better +be done by using the :c:func:`PyRun_SimpleFile` function, which saves you the +trouble of allocating memory space and loading the file contents. + + +.. _lower-level-embedding: + +Beyond Very High Level Embedding: An overview +============================================= + +The high level interface gives you the ability to execute arbitrary pieces of +Python code from your application, but exchanging data values is quite +cumbersome to say the least. If you want that, you should use lower level calls. +At the cost of having to write more C code, you can achieve almost anything. + +It should be noted that extending Python and embedding Python is quite the same +activity, despite the different intent. Most topics discussed in the previous +chapters are still valid. To show this, consider what the extension code from +Python to C really does: + +#. Convert data values from Python to C, + +#. Perform a function call to a C routine using the converted values, and + +#. Convert the data values from the call from C to Python. + +When embedding Python, the interface code does: + +#. Convert data values from C to Python, + +#. Perform a function call to a Python interface routine using the converted + values, and + +#. Convert the data values from the call from Python to C. + +As you can see, the data conversion steps are simply swapped to accommodate the +different direction of the cross-language transfer. The only difference is the +routine that you call between both data conversions. When extending, you call a +C routine, when embedding, you call a Python routine. + +This chapter will not discuss how to convert data from Python to C and vice +versa. Also, proper use of references and dealing with errors is assumed to be +understood. Since these aspects do not differ from extending the interpreter, +you can refer to earlier chapters for the required information. + + +.. _pure-embedding: + +Pure Embedding +============== + +The first program aims to execute a function in a Python script. Like in the +section about the very high level interface, the Python interpreter does not +directly interact with the application (but that will change in the next +section). + +The code to run a function defined in a Python script is: + +.. literalinclude:: ../includes/run-func.c + + +This code loads a Python script using ``argv[1]``, and calls the function named +in ``argv[2]``. Its integer arguments are the other values of the ``argv`` +array. If you :ref:`compile and link <compiling>` this program (let's call +the finished executable :program:`call`), and use it to execute a Python +script, such as: + +.. code-block:: python + + def multiply(a,b): + print("Will compute", a, "times", b) + c = 0 + for i in range(0, a): + c = c + b + return c + +then the result should be: + +.. code-block:: shell-session + + $ call multiply multiply 3 2 + Will compute 3 times 2 + Result of call: 6 + +Although the program is quite large for its functionality, most of the code is +for data conversion between Python and C, and for error reporting. The +interesting part with respect to embedding Python starts with :: + + Py_Initialize(); + pName = PyUnicode_DecodeFSDefault(argv[1]); + /* Error checking of pName left out */ + pModule = PyImport_Import(pName); + +After initializing the interpreter, the script is loaded using +:c:func:`PyImport_Import`. This routine needs a Python string as its argument, +which is constructed using the :c:func:`PyUnicode_FromString` data conversion +routine. :: + + pFunc = PyObject_GetAttrString(pModule, argv[2]); + /* pFunc is a new reference */ + + if (pFunc && PyCallable_Check(pFunc)) { + ... + } + Py_XDECREF(pFunc); + +Once the script is loaded, the name we're looking for is retrieved using +:c:func:`PyObject_GetAttrString`. If the name exists, and the object returned is +callable, you can safely assume that it is a function. The program then +proceeds by constructing a tuple of arguments as normal. The call to the Python +function is then made with:: + + pValue = PyObject_CallObject(pFunc, pArgs); + +Upon return of the function, ``pValue`` is either ``NULL`` or it contains a +reference to the return value of the function. Be sure to release the reference +after examining the value. + + +.. _extending-with-embedding: + +Extending Embedded Python +========================= + +Until now, the embedded Python interpreter had no access to functionality from +the application itself. The Python API allows this by extending the embedded +interpreter. That is, the embedded interpreter gets extended with routines +provided by the application. While it sounds complex, it is not so bad. Simply +forget for a while that the application starts the Python interpreter. Instead, +consider the application to be a set of subroutines, and write some glue code +that gives Python access to those routines, just like you would write a normal +Python extension. For example:: + + static int numargs=0; + + /* Return the number of arguments of the application command line */ + static PyObject* + emb_numargs(PyObject *self, PyObject *args) + { + if(!PyArg_ParseTuple(args, ":numargs")) + return NULL; + return PyLong_FromLong(numargs); + } + + static PyMethodDef EmbMethods[] = { + {"numargs", emb_numargs, METH_VARARGS, + "Return the number of arguments received by the process."}, + {NULL, NULL, 0, NULL} + }; + + static PyModuleDef EmbModule = { + PyModuleDef_HEAD_INIT, "emb", NULL, -1, EmbMethods, + NULL, NULL, NULL, NULL + }; + + static PyObject* + PyInit_emb(void) + { + return PyModule_Create(&EmbModule); + } + +Insert the above code just above the :c:func:`main` function. Also, insert the +following two statements before the call to :c:func:`Py_Initialize`:: + + numargs = argc; + PyImport_AppendInittab("emb", &PyInit_emb); + +These two lines initialize the ``numargs`` variable, and make the +:func:`emb.numargs` function accessible to the embedded Python interpreter. +With these extensions, the Python script can do things like + +.. code-block:: python + + import emb + print("Number of arguments", emb.numargs()) + +In a real application, the methods will expose an API of the application to +Python. + +.. TODO: threads, code examples do not really behave well if errors happen + (what to watch out for) + + +.. _embeddingincplusplus: + +Embedding Python in C++ +======================= + +It is also possible to embed Python in a C++ program; precisely how this is done +will depend on the details of the C++ system used; in general you will need to +write the main program in C++, and use the C++ compiler to compile and link your +program. There is no need to recompile Python itself using C++. + + +.. _compiling: + +Compiling and Linking under Unix-like systems +============================================= + +It is not necessarily trivial to find the right flags to pass to your +compiler (and linker) in order to embed the Python interpreter into your +application, particularly because Python needs to load library modules +implemented as C dynamic extensions (:file:`.so` files) linked against +it. + +To find out the required compiler and linker flags, you can execute the +:file:`python{X.Y}-config` script which is generated as part of the +installation process (a :file:`python3-config` script may also be +available). This script has several options, of which the following will +be directly useful to you: + +* ``pythonX.Y-config --cflags`` will give you the recommended flags when + compiling: + + .. code-block:: shell-session + + $ /opt/bin/python3.4-config --cflags + -I/opt/include/python3.4m -I/opt/include/python3.4m -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes + +* ``pythonX.Y-config --ldflags`` will give you the recommended flags when + linking: + + .. code-block:: shell-session + + $ /opt/bin/python3.4-config --ldflags + -L/opt/lib/python3.4/config-3.4m -lpthread -ldl -lutil -lm -lpython3.4m -Xlinker -export-dynamic + +.. note:: + To avoid confusion between several Python installations (and especially + between the system Python and your own compiled Python), it is recommended + that you use the absolute path to :file:`python{X.Y}-config`, as in the above + example. + +If this procedure doesn't work for you (it is not guaranteed to work for +all Unix-like platforms; however, we welcome :ref:`bug reports <reporting-bugs>`) +you will have to read your system's documentation about dynamic linking and/or +examine Python's :file:`Makefile` (use :func:`sysconfig.get_makefile_filename` +to find its location) and compilation +options. In this case, the :mod:`sysconfig` module is a useful tool to +programmatically extract the configuration values that you will want to +combine together. For example: + +.. code-block:: pycon + + >>> import sysconfig + >>> sysconfig.get_config_var('LIBS') + '-lpthread -ldl -lutil' + >>> sysconfig.get_config_var('LINKFORSHARED') + '-Xlinker -export-dynamic' + + +.. XXX similar documentation for Windows missing diff --git a/cpython_2/environment/repo/Doc/extending/extending.rst b/cpython_2/environment/repo/Doc/extending/extending.rst new file mode 100644 index 0000000000000000000000000000000000000000..25dc2934d29ef6fcaba24faa96e21d934dc0b308 --- /dev/null +++ b/cpython_2/environment/repo/Doc/extending/extending.rst @@ -0,0 +1,1383 @@ +.. highlight:: c + + +.. _extending-intro: + +****************************** +Extending Python with C or C++ +****************************** + +It is quite easy to add new built-in modules to Python, if you know how to +program in C. Such :dfn:`extension modules` can do two things that can't be +done directly in Python: they can implement new built-in object types, and they +can call C library functions and system calls. + +To support extensions, the Python API (Application Programmers Interface) +defines a set of functions, macros and variables that provide access to most +aspects of the Python run-time system. The Python API is incorporated in a C +source file by including the header ``"Python.h"``. + +The compilation of an extension module depends on its intended use as well as on +your system setup; details are given in later chapters. + +.. note:: + + The C extension interface is specific to CPython, and extension modules do + not work on other Python implementations. In many cases, it is possible to + avoid writing C extensions and preserve portability to other implementations. + For example, if your use case is calling C library functions or system calls, + you should consider using the :mod:`ctypes` module or the `cffi + <https://cffi.readthedocs.io/>`_ library rather than writing + custom C code. + These modules let you write Python code to interface with C code and are more + portable between implementations of Python than writing and compiling a C + extension module. + + +.. _extending-simpleexample: + +A Simple Example +================ + +Let's create an extension module called ``spam`` (the favorite food of Monty +Python fans...) and let's say we want to create a Python interface to the C +library function :c:func:`system` [#]_. This function takes a null-terminated +character string as argument and returns an integer. We want this function to +be callable from Python as follows: + +.. code-block:: pycon + + >>> import spam + >>> status = spam.system("ls -l") + +Begin by creating a file :file:`spammodule.c`. (Historically, if a module is +called ``spam``, the C file containing its implementation is called +:file:`spammodule.c`; if the module name is very long, like ``spammify``, the +module name can be just :file:`spammify.c`.) + +The first two lines of our file can be:: + + #define PY_SSIZE_T_CLEAN + #include <Python.h> + +which pulls in the Python API (you can add a comment describing the purpose of +the module and a copyright notice if you like). + +.. note:: + + Since Python may define some pre-processor definitions which affect the standard + headers on some systems, you *must* include :file:`Python.h` before any standard + headers are included. + + It is recommended to always define ``PY_SSIZE_T_CLEAN`` before including + ``Python.h``. See :ref:`parsetuple` for a description of this macro. + +All user-visible symbols defined by :file:`Python.h` have a prefix of ``Py`` or +``PY``, except those defined in standard header files. For convenience, and +since they are used extensively by the Python interpreter, ``"Python.h"`` +includes a few standard header files: ``<stdio.h>``, ``<string.h>``, +``<errno.h>``, and ``<stdlib.h>``. If the latter header file does not exist on +your system, it declares the functions :c:func:`malloc`, :c:func:`free` and +:c:func:`realloc` directly. + +The next thing we add to our module file is the C function that will be called +when the Python expression ``spam.system(string)`` is evaluated (we'll see +shortly how it ends up being called):: + + static PyObject * + spam_system(PyObject *self, PyObject *args) + { + const char *command; + int sts; + + if (!PyArg_ParseTuple(args, "s", &command)) + return NULL; + sts = system(command); + return PyLong_FromLong(sts); + } + +There is a straightforward translation from the argument list in Python (for +example, the single expression ``"ls -l"``) to the arguments passed to the C +function. The C function always has two arguments, conventionally named *self* +and *args*. + +The *self* argument points to the module object for module-level functions; +for a method it would point to the object instance. + +The *args* argument will be a pointer to a Python tuple object containing the +arguments. Each item of the tuple corresponds to an argument in the call's +argument list. The arguments are Python objects --- in order to do anything +with them in our C function we have to convert them to C values. The function +:c:func:`PyArg_ParseTuple` in the Python API checks the argument types and +converts them to C values. It uses a template string to determine the required +types of the arguments as well as the types of the C variables into which to +store the converted values. More about this later. + +:c:func:`PyArg_ParseTuple` returns true (nonzero) if all arguments have the right +type and its components have been stored in the variables whose addresses are +passed. It returns false (zero) if an invalid argument list was passed. In the +latter case it also raises an appropriate exception so the calling function can +return ``NULL`` immediately (as we saw in the example). + + +.. _extending-errors: + +Intermezzo: Errors and Exceptions +================================= + +An important convention throughout the Python interpreter is the following: when +a function fails, it should set an exception condition and return an error value +(usually a ``NULL`` pointer). Exceptions are stored in a static global variable +inside the interpreter; if this variable is ``NULL`` no exception has occurred. A +second global variable stores the "associated value" of the exception (the +second argument to :keyword:`raise`). A third variable contains the stack +traceback in case the error originated in Python code. These three variables +are the C equivalents of the result in Python of :meth:`sys.exc_info` (see the +section on module :mod:`sys` in the Python Library Reference). It is important +to know about them to understand how errors are passed around. + +The Python API defines a number of functions to set various types of exceptions. + +The most common one is :c:func:`PyErr_SetString`. Its arguments are an exception +object and a C string. The exception object is usually a predefined object like +:c:data:`PyExc_ZeroDivisionError`. The C string indicates the cause of the error +and is converted to a Python string object and stored as the "associated value" +of the exception. + +Another useful function is :c:func:`PyErr_SetFromErrno`, which only takes an +exception argument and constructs the associated value by inspection of the +global variable :c:data:`errno`. The most general function is +:c:func:`PyErr_SetObject`, which takes two object arguments, the exception and +its associated value. You don't need to :c:func:`Py_INCREF` the objects passed +to any of these functions. + +You can test non-destructively whether an exception has been set with +:c:func:`PyErr_Occurred`. This returns the current exception object, or ``NULL`` +if no exception has occurred. You normally don't need to call +:c:func:`PyErr_Occurred` to see whether an error occurred in a function call, +since you should be able to tell from the return value. + +When a function *f* that calls another function *g* detects that the latter +fails, *f* should itself return an error value (usually ``NULL`` or ``-1``). It +should *not* call one of the :c:func:`PyErr_\*` functions --- one has already +been called by *g*. *f*'s caller is then supposed to also return an error +indication to *its* caller, again *without* calling :c:func:`PyErr_\*`, and so on +--- the most detailed cause of the error was already reported by the function +that first detected it. Once the error reaches the Python interpreter's main +loop, this aborts the currently executing Python code and tries to find an +exception handler specified by the Python programmer. + +(There are situations where a module can actually give a more detailed error +message by calling another :c:func:`PyErr_\*` function, and in such cases it is +fine to do so. As a general rule, however, this is not necessary, and can cause +information about the cause of the error to be lost: most operations can fail +for a variety of reasons.) + +To ignore an exception set by a function call that failed, the exception +condition must be cleared explicitly by calling :c:func:`PyErr_Clear`. The only +time C code should call :c:func:`PyErr_Clear` is if it doesn't want to pass the +error on to the interpreter but wants to handle it completely by itself +(possibly by trying something else, or pretending nothing went wrong). + +Every failing :c:func:`malloc` call must be turned into an exception --- the +direct caller of :c:func:`malloc` (or :c:func:`realloc`) must call +:c:func:`PyErr_NoMemory` and return a failure indicator itself. All the +object-creating functions (for example, :c:func:`PyLong_FromLong`) already do +this, so this note is only relevant to those who call :c:func:`malloc` directly. + +Also note that, with the important exception of :c:func:`PyArg_ParseTuple` and +friends, functions that return an integer status usually return a positive value +or zero for success and ``-1`` for failure, like Unix system calls. + +Finally, be careful to clean up garbage (by making :c:func:`Py_XDECREF` or +:c:func:`Py_DECREF` calls for objects you have already created) when you return +an error indicator! + +The choice of which exception to raise is entirely yours. There are predeclared +C objects corresponding to all built-in Python exceptions, such as +:c:data:`PyExc_ZeroDivisionError`, which you can use directly. Of course, you +should choose exceptions wisely --- don't use :c:data:`PyExc_TypeError` to mean +that a file couldn't be opened (that should probably be :c:data:`PyExc_IOError`). +If something's wrong with the argument list, the :c:func:`PyArg_ParseTuple` +function usually raises :c:data:`PyExc_TypeError`. If you have an argument whose +value must be in a particular range or must satisfy other conditions, +:c:data:`PyExc_ValueError` is appropriate. + +You can also define a new exception that is unique to your module. For this, you +usually declare a static object variable at the beginning of your file:: + + static PyObject *SpamError; + +and initialize it in your module's initialization function (:c:func:`PyInit_spam`) +with an exception object:: + + PyMODINIT_FUNC + PyInit_spam(void) + { + PyObject *m; + + m = PyModule_Create(&spammodule); + if (m == NULL) + return NULL; + + SpamError = PyErr_NewException("spam.error", NULL, NULL); + Py_XINCREF(SpamError); + if (PyModule_AddObject(m, "error", SpamError) < 0) { + Py_XDECREF(SpamError); + Py_CLEAR(SpamError); + Py_DECREF(m); + return NULL; + } + + return m; + } + +Note that the Python name for the exception object is :exc:`spam.error`. The +:c:func:`PyErr_NewException` function may create a class with the base class +being :exc:`Exception` (unless another class is passed in instead of ``NULL``), +described in :ref:`bltin-exceptions`. + +Note also that the :c:data:`SpamError` variable retains a reference to the newly +created exception class; this is intentional! Since the exception could be +removed from the module by external code, an owned reference to the class is +needed to ensure that it will not be discarded, causing :c:data:`SpamError` to +become a dangling pointer. Should it become a dangling pointer, C code which +raises the exception could cause a core dump or other unintended side effects. + +We discuss the use of ``PyMODINIT_FUNC`` as a function return type later in this +sample. + +The :exc:`spam.error` exception can be raised in your extension module using a +call to :c:func:`PyErr_SetString` as shown below:: + + static PyObject * + spam_system(PyObject *self, PyObject *args) + { + const char *command; + int sts; + + if (!PyArg_ParseTuple(args, "s", &command)) + return NULL; + sts = system(command); + if (sts < 0) { + PyErr_SetString(SpamError, "System command failed"); + return NULL; + } + return PyLong_FromLong(sts); + } + + +.. _backtoexample: + +Back to the Example +=================== + +Going back to our example function, you should now be able to understand this +statement:: + + if (!PyArg_ParseTuple(args, "s", &command)) + return NULL; + +It returns ``NULL`` (the error indicator for functions returning object pointers) +if an error is detected in the argument list, relying on the exception set by +:c:func:`PyArg_ParseTuple`. Otherwise the string value of the argument has been +copied to the local variable :c:data:`command`. This is a pointer assignment and +you are not supposed to modify the string to which it points (so in Standard C, +the variable :c:data:`command` should properly be declared as ``const char +*command``). + +The next statement is a call to the Unix function :c:func:`system`, passing it +the string we just got from :c:func:`PyArg_ParseTuple`:: + + sts = system(command); + +Our :func:`spam.system` function must return the value of :c:data:`sts` as a +Python object. This is done using the function :c:func:`PyLong_FromLong`. :: + + return PyLong_FromLong(sts); + +In this case, it will return an integer object. (Yes, even integers are objects +on the heap in Python!) + +If you have a C function that returns no useful argument (a function returning +:c:type:`void`), the corresponding Python function must return ``None``. You +need this idiom to do so (which is implemented by the :c:macro:`Py_RETURN_NONE` +macro):: + + Py_INCREF(Py_None); + return Py_None; + +:c:data:`Py_None` is the C name for the special Python object ``None``. It is a +genuine Python object rather than a ``NULL`` pointer, which means "error" in most +contexts, as we have seen. + + +.. _methodtable: + +The Module's Method Table and Initialization Function +===================================================== + +I promised to show how :c:func:`spam_system` is called from Python programs. +First, we need to list its name and address in a "method table":: + + static PyMethodDef SpamMethods[] = { + ... + {"system", spam_system, METH_VARARGS, + "Execute a shell command."}, + ... + {NULL, NULL, 0, NULL} /* Sentinel */ + }; + +Note the third entry (``METH_VARARGS``). This is a flag telling the interpreter +the calling convention to be used for the C function. It should normally always +be ``METH_VARARGS`` or ``METH_VARARGS | METH_KEYWORDS``; a value of ``0`` means +that an obsolete variant of :c:func:`PyArg_ParseTuple` is used. + +When using only ``METH_VARARGS``, the function should expect the Python-level +parameters to be passed in as a tuple acceptable for parsing via +:c:func:`PyArg_ParseTuple`; more information on this function is provided below. + +The :const:`METH_KEYWORDS` bit may be set in the third field if keyword +arguments should be passed to the function. In this case, the C function should +accept a third ``PyObject *`` parameter which will be a dictionary of keywords. +Use :c:func:`PyArg_ParseTupleAndKeywords` to parse the arguments to such a +function. + +The method table must be referenced in the module definition structure:: + + static struct PyModuleDef spammodule = { + PyModuleDef_HEAD_INIT, + "spam", /* name of module */ + spam_doc, /* module documentation, may be NULL */ + -1, /* size of per-interpreter state of the module, + or -1 if the module keeps state in global variables. */ + SpamMethods + }; + +This structure, in turn, must be passed to the interpreter in the module's +initialization function. The initialization function must be named +:c:func:`PyInit_name`, where *name* is the name of the module, and should be the +only non-\ ``static`` item defined in the module file:: + + PyMODINIT_FUNC + PyInit_spam(void) + { + return PyModule_Create(&spammodule); + } + +Note that PyMODINIT_FUNC declares the function as ``PyObject *`` return type, +declares any special linkage declarations required by the platform, and for C++ +declares the function as ``extern "C"``. + +When the Python program imports module :mod:`spam` for the first time, +:c:func:`PyInit_spam` is called. (See below for comments about embedding Python.) +It calls :c:func:`PyModule_Create`, which returns a module object, and +inserts built-in function objects into the newly created module based upon the +table (an array of :c:type:`PyMethodDef` structures) found in the module definition. +:c:func:`PyModule_Create` returns a pointer to the module object +that it creates. It may abort with a fatal error for +certain errors, or return ``NULL`` if the module could not be initialized +satisfactorily. The init function must return the module object to its caller, +so that it then gets inserted into ``sys.modules``. + +When embedding Python, the :c:func:`PyInit_spam` function is not called +automatically unless there's an entry in the :c:data:`PyImport_Inittab` table. +To add the module to the initialization table, use :c:func:`PyImport_AppendInittab`, +optionally followed by an import of the module:: + + int + main(int argc, char *argv[]) + { + wchar_t *program = Py_DecodeLocale(argv[0], NULL); + if (program == NULL) { + fprintf(stderr, "Fatal error: cannot decode argv[0]\n"); + exit(1); + } + + /* Add a built-in module, before Py_Initialize */ + if (PyImport_AppendInittab("spam", PyInit_spam) == -1) { + fprintf(stderr, "Error: could not extend in-built modules table\n"); + exit(1); + } + + /* Pass argv[0] to the Python interpreter */ + Py_SetProgramName(program); + + /* Initialize the Python interpreter. Required. + If this step fails, it will be a fatal error. */ + Py_Initialize(); + + /* Optionally import the module; alternatively, + import can be deferred until the embedded script + imports it. */ + pmodule = PyImport_ImportModule("spam"); + if (!pmodule) { + PyErr_Print(); + fprintf(stderr, "Error: could not import module 'spam'\n"); + } + + ... + + PyMem_RawFree(program); + return 0; + } + +.. note:: + + Removing entries from ``sys.modules`` or importing compiled modules into + multiple interpreters within a process (or following a :c:func:`fork` without an + intervening :c:func:`exec`) can create problems for some extension modules. + Extension module authors should exercise caution when initializing internal data + structures. + +A more substantial example module is included in the Python source distribution +as :file:`Modules/xxmodule.c`. This file may be used as a template or simply +read as an example. + +.. note:: + + Unlike our ``spam`` example, ``xxmodule`` uses *multi-phase initialization* + (new in Python 3.5), where a PyModuleDef structure is returned from + ``PyInit_spam``, and creation of the module is left to the import machinery. + For details on multi-phase initialization, see :PEP:`489`. + + +.. _compilation: + +Compilation and Linkage +======================= + +There are two more things to do before you can use your new extension: compiling +and linking it with the Python system. If you use dynamic loading, the details +may depend on the style of dynamic loading your system uses; see the chapters +about building extension modules (chapter :ref:`building`) and additional +information that pertains only to building on Windows (chapter +:ref:`building-on-windows`) for more information about this. + +If you can't use dynamic loading, or if you want to make your module a permanent +part of the Python interpreter, you will have to change the configuration setup +and rebuild the interpreter. Luckily, this is very simple on Unix: just place +your file (:file:`spammodule.c` for example) in the :file:`Modules/` directory +of an unpacked source distribution, add a line to the file +:file:`Modules/Setup.local` describing your file: + +.. code-block:: sh + + spam spammodule.o + +and rebuild the interpreter by running :program:`make` in the toplevel +directory. You can also run :program:`make` in the :file:`Modules/` +subdirectory, but then you must first rebuild :file:`Makefile` there by running +':program:`make` Makefile'. (This is necessary each time you change the +:file:`Setup` file.) + +If your module requires additional libraries to link with, these can be listed +on the line in the configuration file as well, for instance: + +.. code-block:: sh + + spam spammodule.o -lX11 + + +.. _callingpython: + +Calling Python Functions from C +=============================== + +So far we have concentrated on making C functions callable from Python. The +reverse is also useful: calling Python functions from C. This is especially the +case for libraries that support so-called "callback" functions. If a C +interface makes use of callbacks, the equivalent Python often needs to provide a +callback mechanism to the Python programmer; the implementation will require +calling the Python callback functions from a C callback. Other uses are also +imaginable. + +Fortunately, the Python interpreter is easily called recursively, and there is a +standard interface to call a Python function. (I won't dwell on how to call the +Python parser with a particular string as input --- if you're interested, have a +look at the implementation of the :option:`-c` command line option in +:file:`Modules/main.c` from the Python source code.) + +Calling a Python function is easy. First, the Python program must somehow pass +you the Python function object. You should provide a function (or some other +interface) to do this. When this function is called, save a pointer to the +Python function object (be careful to :c:func:`Py_INCREF` it!) in a global +variable --- or wherever you see fit. For example, the following function might +be part of a module definition:: + + static PyObject *my_callback = NULL; + + static PyObject * + my_set_callback(PyObject *dummy, PyObject *args) + { + PyObject *result = NULL; + PyObject *temp; + + if (PyArg_ParseTuple(args, "O:set_callback", &temp)) { + if (!PyCallable_Check(temp)) { + PyErr_SetString(PyExc_TypeError, "parameter must be callable"); + return NULL; + } + Py_XINCREF(temp); /* Add a reference to new callback */ + Py_XDECREF(my_callback); /* Dispose of previous callback */ + my_callback = temp; /* Remember new callback */ + /* Boilerplate to return "None" */ + Py_INCREF(Py_None); + result = Py_None; + } + return result; + } + +This function must be registered with the interpreter using the +:const:`METH_VARARGS` flag; this is described in section :ref:`methodtable`. The +:c:func:`PyArg_ParseTuple` function and its arguments are documented in section +:ref:`parsetuple`. + +The macros :c:func:`Py_XINCREF` and :c:func:`Py_XDECREF` increment/decrement the +reference count of an object and are safe in the presence of ``NULL`` pointers +(but note that *temp* will not be ``NULL`` in this context). More info on them +in section :ref:`refcounts`. + +.. index:: single: PyObject_CallObject() + +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 +arbitrary Python objects: the Python function, and the argument list. The +argument list must always be a tuple object, whose length is the number of +arguments. To call the Python function with no arguments, pass in ``NULL``, or +an empty tuple; to call it with one argument, pass a singleton tuple. +:c:func:`Py_BuildValue` returns a tuple when its format string consists of zero +or more format codes between parentheses. For example:: + + int arg; + PyObject *arglist; + PyObject *result; + ... + arg = 123; + ... + /* Time to call the callback */ + arglist = Py_BuildValue("(i)", arg); + result = PyObject_CallObject(my_callback, arglist); + Py_DECREF(arglist); + +:c:func:`PyObject_CallObject` returns a Python object pointer: this is the return +value of the Python function. :c:func:`PyObject_CallObject` is +"reference-count-neutral" with respect to its arguments. In the example a new +tuple was created to serve as the argument list, which is +:c:func:`Py_DECREF`\ -ed immediately after the :c:func:`PyObject_CallObject` +call. + +The return value of :c:func:`PyObject_CallObject` is "new": either it is a brand +new object, or it is an existing object whose reference count has been +incremented. So, unless you want to save it in a global variable, you should +somehow :c:func:`Py_DECREF` the result, even (especially!) if you are not +interested in its value. + +Before you do this, however, it is important to check that the return value +isn't ``NULL``. If it is, the Python function terminated by raising an exception. +If the C code that called :c:func:`PyObject_CallObject` is called from Python, it +should now return an error indication to its Python caller, so the interpreter +can print a stack trace, or the calling Python code can handle the exception. +If this is not possible or desirable, the exception should be cleared by calling +:c:func:`PyErr_Clear`. For example:: + + if (result == NULL) + return NULL; /* Pass error back */ + ...use result... + Py_DECREF(result); + +Depending on the desired interface to the Python callback function, you may also +have to provide an argument list to :c:func:`PyObject_CallObject`. In some cases +the argument list is also provided by the Python program, through the same +interface that specified the callback function. It can then be saved and used +in the same manner as the function object. In other cases, you may have to +construct a new tuple to pass as the argument list. The simplest way to do this +is to call :c:func:`Py_BuildValue`. For example, if you want to pass an integral +event code, you might use the following code:: + + PyObject *arglist; + ... + arglist = Py_BuildValue("(l)", eventcode); + result = PyObject_CallObject(my_callback, arglist); + Py_DECREF(arglist); + if (result == NULL) + return NULL; /* Pass error back */ + /* Here maybe use the result */ + Py_DECREF(result); + +Note the placement of ``Py_DECREF(arglist)`` immediately after the call, before +the error check! Also note that strictly speaking this code is not complete: +:c:func:`Py_BuildValue` may run out of memory, and this should be checked. + +You may also call a function with keyword arguments by using +:c:func:`PyObject_Call`, which supports arguments and keyword arguments. As in +the above example, we use :c:func:`Py_BuildValue` to construct the dictionary. :: + + PyObject *dict; + ... + dict = Py_BuildValue("{s:i}", "name", val); + result = PyObject_Call(my_callback, NULL, dict); + Py_DECREF(dict); + if (result == NULL) + return NULL; /* Pass error back */ + /* Here maybe use the result */ + Py_DECREF(result); + + +.. _parsetuple: + +Extracting Parameters in Extension Functions +============================================ + +.. index:: single: PyArg_ParseTuple() + +The :c:func:`PyArg_ParseTuple` function is declared as follows:: + + int PyArg_ParseTuple(PyObject *arg, const char *format, ...); + +The *arg* argument must be a tuple object containing an argument list passed +from Python to a C function. The *format* argument must be a format string, +whose syntax is explained in :ref:`arg-parsing` in the Python/C API Reference +Manual. The remaining arguments must be addresses of variables whose type is +determined by the format string. + +Note that while :c:func:`PyArg_ParseTuple` checks that the Python arguments have +the required types, it cannot check the validity of the addresses of C variables +passed to the call: if you make mistakes there, your code will probably crash or +at least overwrite random bits in memory. So be careful! + +Note that any Python object references which are provided to the caller are +*borrowed* references; do not decrement their reference count! + +Some example calls:: + + #define PY_SSIZE_T_CLEAN /* Make "s#" use Py_ssize_t rather than int. */ + #include <Python.h> + +:: + + int ok; + int i, j; + long k, l; + const char *s; + Py_ssize_t size; + + ok = PyArg_ParseTuple(args, ""); /* No arguments */ + /* Python call: f() */ + +:: + + ok = PyArg_ParseTuple(args, "s", &s); /* A string */ + /* Possible Python call: f('whoops!') */ + +:: + + ok = PyArg_ParseTuple(args, "lls", &k, &l, &s); /* Two longs and a string */ + /* Possible Python call: f(1, 2, 'three') */ + +:: + + ok = PyArg_ParseTuple(args, "(ii)s#", &i, &j, &s, &size); + /* A pair of ints and a string, whose size is also returned */ + /* Possible Python call: f((1, 2), 'three') */ + +:: + + { + const char *file; + const char *mode = "r"; + int bufsize = 0; + ok = PyArg_ParseTuple(args, "s|si", &file, &mode, &bufsize); + /* A string, and optionally another string and an integer */ + /* Possible Python calls: + f('spam') + f('spam', 'w') + f('spam', 'wb', 100000) */ + } + +:: + + { + int left, top, right, bottom, h, v; + ok = PyArg_ParseTuple(args, "((ii)(ii))(ii)", + &left, &top, &right, &bottom, &h, &v); + /* A rectangle and a point */ + /* Possible Python call: + f(((0, 0), (400, 300)), (10, 10)) */ + } + +:: + + { + Py_complex c; + ok = PyArg_ParseTuple(args, "D:myfunction", &c); + /* a complex, also providing a function name for errors */ + /* Possible Python call: myfunction(1+2j) */ + } + + +.. _parsetupleandkeywords: + +Keyword Parameters for Extension Functions +========================================== + +.. index:: single: PyArg_ParseTupleAndKeywords() + +The :c:func:`PyArg_ParseTupleAndKeywords` function is declared as follows:: + + int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict, + const char *format, char *kwlist[], ...); + +The *arg* and *format* parameters are identical to those of the +:c:func:`PyArg_ParseTuple` function. The *kwdict* parameter is the dictionary of +keywords received as the third parameter from the Python runtime. The *kwlist* +parameter is a ``NULL``-terminated list of strings which identify the parameters; +the names are matched with the type information from *format* from left to +right. On success, :c:func:`PyArg_ParseTupleAndKeywords` returns true, otherwise +it returns false and raises an appropriate exception. + +.. note:: + + Nested tuples cannot be parsed when using keyword arguments! Keyword parameters + passed in which are not present in the *kwlist* will cause :exc:`TypeError` to + be raised. + +.. index:: single: Philbrick, Geoff + +Here is an example module which uses keywords, based on an example by Geoff +Philbrick (philbrick@hks.com):: + + #define PY_SSIZE_T_CLEAN /* Make "s#" use Py_ssize_t rather than int. */ + #include <Python.h> + + static PyObject * + keywdarg_parrot(PyObject *self, PyObject *args, PyObject *keywds) + { + int voltage; + const char *state = "a stiff"; + const char *action = "voom"; + const char *type = "Norwegian Blue"; + + static char *kwlist[] = {"voltage", "state", "action", "type", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist, + &voltage, &state, &action, &type)) + return NULL; + + printf("-- This parrot wouldn't %s if you put %i Volts through it.\n", + action, voltage); + printf("-- Lovely plumage, the %s -- It's %s!\n", type, state); + + Py_RETURN_NONE; + } + + static PyMethodDef keywdarg_methods[] = { + /* The cast of the function is necessary since PyCFunction values + * only take two PyObject* parameters, and keywdarg_parrot() takes + * three. + */ + {"parrot", (PyCFunction)(void(*)(void))keywdarg_parrot, METH_VARARGS | METH_KEYWORDS, + "Print a lovely skit to standard output."}, + {NULL, NULL, 0, NULL} /* sentinel */ + }; + + static struct PyModuleDef keywdargmodule = { + PyModuleDef_HEAD_INIT, + "keywdarg", + NULL, + -1, + keywdarg_methods + }; + + PyMODINIT_FUNC + PyInit_keywdarg(void) + { + return PyModule_Create(&keywdargmodule); + } + + +.. _buildvalue: + +Building Arbitrary Values +========================= + +This function is the counterpart to :c:func:`PyArg_ParseTuple`. It is declared +as follows:: + + PyObject *Py_BuildValue(const char *format, ...); + +It recognizes a set of format units similar to the ones recognized by +:c:func:`PyArg_ParseTuple`, but the arguments (which are input to the function, +not output) must not be pointers, just values. It returns a new Python object, +suitable for returning from a C function called from Python. + +One difference with :c:func:`PyArg_ParseTuple`: while the latter requires its +first argument to be a tuple (since Python argument lists are always represented +as tuples internally), :c:func:`Py_BuildValue` does not always build a tuple. It +builds a tuple only if its format string contains two or more format units. If +the format string is empty, it returns ``None``; if it contains exactly one +format unit, it returns whatever object is described by that format unit. To +force it to return a tuple of size 0 or one, parenthesize the format string. + +Examples (to the left the call, to the right the resulting Python value): + +.. code-block:: none + + Py_BuildValue("") None + Py_BuildValue("i", 123) 123 + Py_BuildValue("iii", 123, 456, 789) (123, 456, 789) + Py_BuildValue("s", "hello") 'hello' + Py_BuildValue("y", "hello") b'hello' + Py_BuildValue("ss", "hello", "world") ('hello', 'world') + Py_BuildValue("s#", "hello", 4) 'hell' + Py_BuildValue("y#", "hello", 4) b'hell' + Py_BuildValue("()") () + Py_BuildValue("(i)", 123) (123,) + Py_BuildValue("(ii)", 123, 456) (123, 456) + Py_BuildValue("(i,i)", 123, 456) (123, 456) + Py_BuildValue("[i,i]", 123, 456) [123, 456] + Py_BuildValue("{s:i,s:i}", + "abc", 123, "def", 456) {'abc': 123, 'def': 456} + Py_BuildValue("((ii)(ii)) (ii)", + 1, 2, 3, 4, 5, 6) (((1, 2), (3, 4)), (5, 6)) + + +.. _refcounts: + +Reference Counts +================ + +In languages like C or C++, the programmer is responsible for dynamic allocation +and deallocation of memory on the heap. In C, this is done using the functions +:c:func:`malloc` and :c:func:`free`. In C++, the operators ``new`` and +``delete`` are used with essentially the same meaning and we'll restrict +the following discussion to the C case. + +Every block of memory allocated with :c:func:`malloc` should eventually be +returned to the pool of available memory by exactly one call to :c:func:`free`. +It is important to call :c:func:`free` at the right time. If a block's address +is forgotten but :c:func:`free` is not called for it, the memory it occupies +cannot be reused until the program terminates. This is called a :dfn:`memory +leak`. On the other hand, if a program calls :c:func:`free` for a block and then +continues to use the block, it creates a conflict with re-use of the block +through another :c:func:`malloc` call. This is called :dfn:`using freed memory`. +It has the same bad consequences as referencing uninitialized data --- core +dumps, wrong results, mysterious crashes. + +Common causes of memory leaks are unusual paths through the code. For instance, +a function may allocate a block of memory, do some calculation, and then free +the block again. Now a change in the requirements for the function may add a +test to the calculation that detects an error condition and can return +prematurely from the function. It's easy to forget to free the allocated memory +block when taking this premature exit, especially when it is added later to the +code. Such leaks, once introduced, often go undetected for a long time: the +error exit is taken only in a small fraction of all calls, and most modern +machines have plenty of virtual memory, so the leak only becomes apparent in a +long-running process that uses the leaking function frequently. Therefore, it's +important to prevent leaks from happening by having a coding convention or +strategy that minimizes this kind of errors. + +Since Python makes heavy use of :c:func:`malloc` and :c:func:`free`, it needs a +strategy to avoid memory leaks as well as the use of freed memory. The chosen +method is called :dfn:`reference counting`. The principle is simple: every +object contains a counter, which is incremented when a reference to the object +is stored somewhere, and which is decremented when a reference to it is deleted. +When the counter reaches zero, the last reference to the object has been deleted +and the object is freed. + +An alternative strategy is called :dfn:`automatic garbage collection`. +(Sometimes, reference counting is also referred to as a garbage collection +strategy, hence my use of "automatic" to distinguish the two.) The big +advantage of automatic garbage collection is that the user doesn't need to call +:c:func:`free` explicitly. (Another claimed advantage is an improvement in speed +or memory usage --- this is no hard fact however.) The disadvantage is that for +C, there is no truly portable automatic garbage collector, while reference +counting can be implemented portably (as long as the functions :c:func:`malloc` +and :c:func:`free` are available --- which the C Standard guarantees). Maybe some +day a sufficiently portable automatic garbage collector will be available for C. +Until then, we'll have to live with reference counts. + +While Python uses the traditional reference counting implementation, it also +offers a cycle detector that works to detect reference cycles. This allows +applications to not worry about creating direct or indirect circular references; +these are the weakness of garbage collection implemented using only reference +counting. Reference cycles consist of objects which contain (possibly indirect) +references to themselves, so that each object in the cycle has a reference count +which is non-zero. Typical reference counting implementations are not able to +reclaim the memory belonging to any objects in a reference cycle, or referenced +from the objects in the cycle, even though there are no further references to +the cycle itself. + +The cycle detector is able to detect garbage cycles and can reclaim them. +The :mod:`gc` module exposes a way to run the detector (the +:func:`~gc.collect` function), as well as configuration +interfaces and the ability to disable the detector at runtime. The cycle +detector is considered an optional component; though it is included by default, +it can be disabled at build time using the :option:`!--without-cycle-gc` option +to the :program:`configure` script on Unix platforms (including Mac OS X). If +the cycle detector is disabled in this way, the :mod:`gc` module will not be +available. + + +.. _refcountsinpython: + +Reference Counting in Python +---------------------------- + +There are two macros, ``Py_INCREF(x)`` and ``Py_DECREF(x)``, which handle the +incrementing and decrementing of the reference count. :c:func:`Py_DECREF` also +frees the object when the count reaches zero. For flexibility, it doesn't call +:c:func:`free` directly --- rather, it makes a call through a function pointer in +the object's :dfn:`type object`. For this purpose (and others), every object +also contains a pointer to its type object. + +The big question now remains: when to use ``Py_INCREF(x)`` and ``Py_DECREF(x)``? +Let's first introduce some terms. Nobody "owns" an object; however, you can +:dfn:`own a reference` to an object. An object's reference count is now defined +as the number of owned references to it. The owner of a reference is +responsible for calling :c:func:`Py_DECREF` when the reference is no longer +needed. Ownership of a reference can be transferred. There are three ways to +dispose of an owned reference: pass it on, store it, or call :c:func:`Py_DECREF`. +Forgetting to dispose of an owned reference creates a memory leak. + +It is also possible to :dfn:`borrow` [#]_ a reference to an object. The +borrower of a reference should not call :c:func:`Py_DECREF`. The borrower must +not hold on to the object longer than the owner from which it was borrowed. +Using a borrowed reference after the owner has disposed of it risks using freed +memory and should be avoided completely [#]_. + +The advantage of borrowing over owning a reference is that you don't need to +take care of disposing of the reference on all possible paths through the code +--- in other words, with a borrowed reference you don't run the risk of leaking +when a premature exit is taken. The disadvantage of borrowing over owning is +that there are some subtle situations where in seemingly correct code a borrowed +reference can be used after the owner from which it was borrowed has in fact +disposed of it. + +A borrowed reference can be changed into an owned reference by calling +:c:func:`Py_INCREF`. This does not affect the status of the owner from which the +reference was borrowed --- it creates a new owned reference, and gives full +owner responsibilities (the new owner must dispose of the reference properly, as +well as the previous owner). + + +.. _ownershiprules: + +Ownership Rules +--------------- + +Whenever an object reference is passed into or out of a function, it is part of +the function's interface specification whether ownership is transferred with the +reference or not. + +Most functions that return a reference to an object pass on ownership with the +reference. In particular, all functions whose function it is to create a new +object, such as :c:func:`PyLong_FromLong` and :c:func:`Py_BuildValue`, pass +ownership to the receiver. Even if the object is not actually new, you still +receive ownership of a new reference to that object. For instance, +:c:func:`PyLong_FromLong` maintains a cache of popular values and can return a +reference to a cached item. + +Many functions that extract objects from other objects also transfer ownership +with the reference, for instance :c:func:`PyObject_GetAttrString`. The picture +is less clear, here, however, since a few common routines are exceptions: +:c:func:`PyTuple_GetItem`, :c:func:`PyList_GetItem`, :c:func:`PyDict_GetItem`, and +:c:func:`PyDict_GetItemString` all return references that you borrow from the +tuple, list or dictionary. + +The function :c:func:`PyImport_AddModule` also returns a borrowed reference, even +though it may actually create the object it returns: this is possible because an +owned reference to the object is stored in ``sys.modules``. + +When you pass an object reference into another function, in general, the +function borrows the reference from you --- if it needs to store it, it will use +:c:func:`Py_INCREF` to become an independent owner. There are exactly two +important exceptions to this rule: :c:func:`PyTuple_SetItem` and +:c:func:`PyList_SetItem`. These functions take over ownership of the item passed +to them --- even if they fail! (Note that :c:func:`PyDict_SetItem` and friends +don't take over ownership --- they are "normal.") + +When a C function is called from Python, it borrows references to its arguments +from the caller. The caller owns a reference to the object, so the borrowed +reference's lifetime is guaranteed until the function returns. Only when such a +borrowed reference must be stored or passed on, it must be turned into an owned +reference by calling :c:func:`Py_INCREF`. + +The object reference returned from a C function that is called from Python must +be an owned reference --- ownership is transferred from the function to its +caller. + + +.. _thinice: + +Thin Ice +-------- + +There are a few situations where seemingly harmless use of a borrowed reference +can lead to problems. These all have to do with implicit invocations of the +interpreter, which can cause the owner of a reference to dispose of it. + +The first and most important case to know about is using :c:func:`Py_DECREF` on +an unrelated object while borrowing a reference to a list item. For instance:: + + void + bug(PyObject *list) + { + PyObject *item = PyList_GetItem(list, 0); + + PyList_SetItem(list, 1, PyLong_FromLong(0L)); + PyObject_Print(item, stdout, 0); /* BUG! */ + } + +This function first borrows a reference to ``list[0]``, then replaces +``list[1]`` with the value ``0``, and finally prints the borrowed reference. +Looks harmless, right? But it's not! + +Let's follow the control flow into :c:func:`PyList_SetItem`. The list owns +references to all its items, so when item 1 is replaced, it has to dispose of +the original item 1. Now let's suppose the original item 1 was an instance of a +user-defined class, and let's further suppose that the class defined a +:meth:`__del__` method. If this class instance has a reference count of 1, +disposing of it will call its :meth:`__del__` method. + +Since it is written in Python, the :meth:`__del__` method can execute arbitrary +Python code. Could it perhaps do something to invalidate the reference to +``item`` in :c:func:`bug`? You bet! Assuming that the list passed into +:c:func:`bug` is accessible to the :meth:`__del__` method, it could execute a +statement to the effect of ``del list[0]``, and assuming this was the last +reference to that object, it would free the memory associated with it, thereby +invalidating ``item``. + +The solution, once you know the source of the problem, is easy: temporarily +increment the reference count. The correct version of the function reads:: + + void + no_bug(PyObject *list) + { + PyObject *item = PyList_GetItem(list, 0); + + Py_INCREF(item); + PyList_SetItem(list, 1, PyLong_FromLong(0L)); + PyObject_Print(item, stdout, 0); + Py_DECREF(item); + } + +This is a true story. An older version of Python contained variants of this bug +and someone spent a considerable amount of time in a C debugger to figure out +why his :meth:`__del__` methods would fail... + +The second case of problems with a borrowed reference is a variant involving +threads. Normally, multiple threads in the Python interpreter can't get in each +other's way, because there is a global lock protecting Python's entire object +space. However, it is possible to temporarily release this lock using the macro +:c:macro:`Py_BEGIN_ALLOW_THREADS`, and to re-acquire it using +:c:macro:`Py_END_ALLOW_THREADS`. This is common around blocking I/O calls, to +let other threads use the processor while waiting for the I/O to complete. +Obviously, the following function has the same problem as the previous one:: + + void + bug(PyObject *list) + { + PyObject *item = PyList_GetItem(list, 0); + Py_BEGIN_ALLOW_THREADS + ...some blocking I/O call... + Py_END_ALLOW_THREADS + PyObject_Print(item, stdout, 0); /* BUG! */ + } + + +.. _nullpointers: + +NULL Pointers +------------- + +In general, functions that take object references as arguments do not expect you +to pass them ``NULL`` pointers, and will dump core (or cause later core dumps) if +you do so. Functions that return object references generally return ``NULL`` only +to indicate that an exception occurred. The reason for not testing for ``NULL`` +arguments is that functions often pass the objects they receive on to other +function --- if each function were to test for ``NULL``, there would be a lot of +redundant tests and the code would run more slowly. + +It is better to test for ``NULL`` only at the "source:" when a pointer that may be +``NULL`` is received, for example, from :c:func:`malloc` or from a function that +may raise an exception. + +The macros :c:func:`Py_INCREF` and :c:func:`Py_DECREF` do not check for ``NULL`` +pointers --- however, their variants :c:func:`Py_XINCREF` and :c:func:`Py_XDECREF` +do. + +The macros for checking for a particular object type (``Pytype_Check()``) don't +check for ``NULL`` pointers --- again, there is much code that calls several of +these in a row to test an object against various different expected types, and +this would generate redundant tests. There are no variants with ``NULL`` +checking. + +The C function calling mechanism guarantees that the argument list passed to C +functions (``args`` in the examples) is never ``NULL`` --- in fact it guarantees +that it is always a tuple [#]_. + +It is a severe error to ever let a ``NULL`` pointer "escape" to the Python user. + +.. Frank Stajano: + A pedagogically buggy example, along the lines of the previous listing, would + be helpful here -- showing in more concrete terms what sort of actions could + cause the problem. I can't very well imagine it from the description. + + +.. _cplusplus: + +Writing Extensions in C++ +========================= + +It is possible to write extension modules in C++. Some restrictions apply. If +the main program (the Python interpreter) is compiled and linked by the C +compiler, global or static objects with constructors cannot be used. This is +not a problem if the main program is linked by the C++ compiler. Functions that +will be called by the Python interpreter (in particular, module initialization +functions) have to be declared using ``extern "C"``. It is unnecessary to +enclose the Python header files in ``extern "C" {...}`` --- they use this form +already if the symbol ``__cplusplus`` is defined (all recent C++ compilers +define this symbol). + + +.. _using-capsules: + +Providing a C API for an Extension Module +========================================= + +.. sectionauthor:: Konrad Hinsen <hinsen@cnrs-orleans.fr> + + +Many extension modules just provide new functions and types to be used from +Python, but sometimes the code in an extension module can be useful for other +extension modules. For example, an extension module could implement a type +"collection" which works like lists without order. Just like the standard Python +list type has a C API which permits extension modules to create and manipulate +lists, this new collection type should have a set of C functions for direct +manipulation from other extension modules. + +At first sight this seems easy: just write the functions (without declaring them +``static``, of course), provide an appropriate header file, and document +the C API. And in fact this would work if all extension modules were always +linked statically with the Python interpreter. When modules are used as shared +libraries, however, the symbols defined in one module may not be visible to +another module. The details of visibility depend on the operating system; some +systems use one global namespace for the Python interpreter and all extension +modules (Windows, for example), whereas others require an explicit list of +imported symbols at module link time (AIX is one example), or offer a choice of +different strategies (most Unices). And even if symbols are globally visible, +the module whose functions one wishes to call might not have been loaded yet! + +Portability therefore requires not to make any assumptions about symbol +visibility. This means that all symbols in extension modules should be declared +``static``, except for the module's initialization function, in order to +avoid name clashes with other extension modules (as discussed in section +:ref:`methodtable`). And it means that symbols that *should* be accessible from +other extension modules must be exported in a different way. + +Python provides a special mechanism to pass C-level information (pointers) from +one extension module to another one: Capsules. A Capsule is a Python data type +which stores a pointer (:c:type:`void \*`). Capsules can only be created and +accessed via their C API, but they can be passed around like any other Python +object. In particular, they can be assigned to a name in an extension module's +namespace. Other extension modules can then import this module, retrieve the +value of this name, and then retrieve the pointer from the Capsule. + +There are many ways in which Capsules can be used to export the C API of an +extension module. Each function could get its own Capsule, or all C API pointers +could be stored in an array whose address is published in a Capsule. And the +various tasks of storing and retrieving the pointers can be distributed in +different ways between the module providing the code and the client modules. + +Whichever method you choose, it's important to name your Capsules properly. +The function :c:func:`PyCapsule_New` takes a name parameter +(:c:type:`const char \*`); you're permitted to pass in a ``NULL`` name, but +we strongly encourage you to specify a name. Properly named Capsules provide +a degree of runtime type-safety; there is no feasible way to tell one unnamed +Capsule from another. + +In particular, Capsules used to expose C APIs should be given a name following +this convention:: + + modulename.attributename + +The convenience function :c:func:`PyCapsule_Import` makes it easy to +load a C API provided via a Capsule, but only if the Capsule's name +matches this convention. This behavior gives C API users a high degree +of certainty that the Capsule they load contains the correct C API. + +The following example demonstrates an approach that puts most of the burden on +the writer of the exporting module, which is appropriate for commonly used +library modules. It stores all C API pointers (just one in the example!) in an +array of :c:type:`void` pointers which becomes the value of a Capsule. The header +file corresponding to the module provides a macro that takes care of importing +the module and retrieving its C API pointers; client modules only have to call +this macro before accessing the C API. + +The exporting module is a modification of the :mod:`spam` module from section +:ref:`extending-simpleexample`. The function :func:`spam.system` does not call +the C library function :c:func:`system` directly, but a function +:c:func:`PySpam_System`, which would of course do something more complicated in +reality (such as adding "spam" to every command). This function +:c:func:`PySpam_System` is also exported to other extension modules. + +The function :c:func:`PySpam_System` is a plain C function, declared +``static`` like everything else:: + + static int + PySpam_System(const char *command) + { + return system(command); + } + +The function :c:func:`spam_system` is modified in a trivial way:: + + static PyObject * + spam_system(PyObject *self, PyObject *args) + { + const char *command; + int sts; + + if (!PyArg_ParseTuple(args, "s", &command)) + return NULL; + sts = PySpam_System(command); + return PyLong_FromLong(sts); + } + +In the beginning of the module, right after the line :: + + #include <Python.h> + +two more lines must be added:: + + #define SPAM_MODULE + #include "spammodule.h" + +The ``#define`` is used to tell the header file that it is being included in the +exporting module, not a client module. Finally, the module's initialization +function must take care of initializing the C API pointer array:: + + PyMODINIT_FUNC + PyInit_spam(void) + { + PyObject *m; + static void *PySpam_API[PySpam_API_pointers]; + PyObject *c_api_object; + + m = PyModule_Create(&spammodule); + if (m == NULL) + return NULL; + + /* Initialize the C API pointer array */ + PySpam_API[PySpam_System_NUM] = (void *)PySpam_System; + + /* Create a Capsule containing the API pointer array's address */ + c_api_object = PyCapsule_New((void *)PySpam_API, "spam._C_API", NULL); + + if (PyModule_AddObject(m, "_C_API", c_api_object) < 0) { + Py_XDECREF(c_api_object); + Py_DECREF(m); + return NULL; + } + + return m; + } + +Note that ``PySpam_API`` is declared ``static``; otherwise the pointer +array would disappear when :func:`PyInit_spam` terminates! + +The bulk of the work is in the header file :file:`spammodule.h`, which looks +like this:: + + #ifndef Py_SPAMMODULE_H + #define Py_SPAMMODULE_H + #ifdef __cplusplus + extern "C" { + #endif + + /* Header file for spammodule */ + + /* C API functions */ + #define PySpam_System_NUM 0 + #define PySpam_System_RETURN int + #define PySpam_System_PROTO (const char *command) + + /* Total number of C API pointers */ + #define PySpam_API_pointers 1 + + + #ifdef SPAM_MODULE + /* This section is used when compiling spammodule.c */ + + static PySpam_System_RETURN PySpam_System PySpam_System_PROTO; + + #else + /* This section is used in modules that use spammodule's API */ + + static void **PySpam_API; + + #define PySpam_System \ + (*(PySpam_System_RETURN (*)PySpam_System_PROTO) PySpam_API[PySpam_System_NUM]) + + /* Return -1 on error, 0 on success. + * PyCapsule_Import will set an exception if there's an error. + */ + static int + import_spam(void) + { + PySpam_API = (void **)PyCapsule_Import("spam._C_API", 0); + return (PySpam_API != NULL) ? 0 : -1; + } + + #endif + + #ifdef __cplusplus + } + #endif + + #endif /* !defined(Py_SPAMMODULE_H) */ + +All that a client module must do in order to have access to the function +:c:func:`PySpam_System` is to call the function (or rather macro) +:c:func:`import_spam` in its initialization function:: + + PyMODINIT_FUNC + PyInit_client(void) + { + PyObject *m; + + m = PyModule_Create(&clientmodule); + if (m == NULL) + return NULL; + if (import_spam() < 0) + return NULL; + /* additional initialization can happen here */ + return m; + } + +The main disadvantage of this approach is that the file :file:`spammodule.h` is +rather complicated. However, the basic structure is the same for each function +that is exported, so it has to be learned only once. + +Finally it should be mentioned that Capsules offer additional functionality, +which is especially useful for memory allocation and deallocation of the pointer +stored in a Capsule. The details are described in the Python/C API Reference +Manual in the section :ref:`capsules` and in the implementation of Capsules (files +:file:`Include/pycapsule.h` and :file:`Objects/pycapsule.c` in the Python source +code distribution). + +.. rubric:: Footnotes + +.. [#] An interface for this function already exists in the standard module :mod:`os` + --- it was chosen as a simple and straightforward example. + +.. [#] The metaphor of "borrowing" a reference is not completely correct: the owner + still has a copy of the reference. + +.. [#] Checking that the reference count is at least 1 **does not work** --- the + reference count itself could be in freed memory and may thus be reused for + another object! + +.. [#] These guarantees don't hold when you use the "old" style calling convention --- + this is still found in much existing code. diff --git a/cpython_2/environment/repo/Doc/extending/index.rst b/cpython_2/environment/repo/Doc/extending/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..0994e3e8627dfaed440585038bb7f29a93067e11 --- /dev/null +++ b/cpython_2/environment/repo/Doc/extending/index.rst @@ -0,0 +1,74 @@ +.. _extending-index: + +################################################## + Extending and Embedding the Python Interpreter +################################################## + +This document describes how to write modules in C or C++ to extend the Python +interpreter with new modules. Those modules can not only define new functions +but also new object types and their methods. The document also describes how +to embed the Python interpreter in another application, for use as an extension +language. Finally, it shows how to compile and link extension modules so that +they can be loaded dynamically (at run time) into the interpreter, if the +underlying operating system supports this feature. + +This document assumes basic knowledge about Python. For an informal +introduction to the language, see :ref:`tutorial-index`. :ref:`reference-index` +gives a more formal definition of the language. :ref:`library-index` documents +the existing object types, functions and modules (both built-in and written in +Python) that give the language its wide application range. + +For a detailed description of the whole Python/C API, see the separate +:ref:`c-api-index`. + + +Recommended third party tools +============================= + +This guide only covers the basic tools for creating extensions provided +as part of this version of CPython. Third party tools like +`Cython <http://cython.org/>`_, `cffi <https://cffi.readthedocs.io>`_, +`SWIG <http://www.swig.org>`_ and `Numba <https://numba.pydata.org/>`_ +offer both simpler and more sophisticated approaches to creating C and C++ +extensions for Python. + +.. seealso:: + + `Python Packaging User Guide: Binary Extensions <https://packaging.python.org/guides/packaging-binary-extensions/>`_ + The Python Packaging User Guide not only covers several available + tools that simplify the creation of binary extensions, but also + discusses the various reasons why creating an extension module may be + desirable in the first place. + + +Creating extensions without third party tools +============================================= + +This section of the guide covers creating C and C++ extensions without +assistance from third party tools. It is intended primarily for creators +of those tools, rather than being a recommended way to create your own +C extensions. + +.. toctree:: + :maxdepth: 2 + :numbered: + + extending.rst + newtypes_tutorial.rst + newtypes.rst + building.rst + windows.rst + +Embedding the CPython runtime in a larger application +===================================================== + +Sometimes, rather than creating an extension that runs inside the Python +interpreter as the main application, it is desirable to instead embed +the CPython runtime inside a larger application. This section covers +some of the details involved in doing that successfully. + +.. toctree:: + :maxdepth: 2 + :numbered: + + embedding.rst diff --git a/cpython_2/environment/repo/Doc/extending/newtypes.rst b/cpython_2/environment/repo/Doc/extending/newtypes.rst new file mode 100644 index 0000000000000000000000000000000000000000..d9023709fddc86ff42c387c2d912e047ac6c77ab --- /dev/null +++ b/cpython_2/environment/repo/Doc/extending/newtypes.rst @@ -0,0 +1,621 @@ +.. highlight:: c + +.. _new-types-topics: + +***************************************** +Defining Extension Types: Assorted Topics +***************************************** + +.. _dnt-type-methods: + +This section aims to give a quick fly-by on the various type methods you can +implement and what they do. + +Here is the definition of :c:type:`PyTypeObject`, with some fields only used in +debug builds omitted: + +.. literalinclude:: ../includes/typestruct.h + + +Now that's a *lot* of methods. Don't worry too much though -- if you have +a type you want to define, the chances are very good that you will only +implement a handful of these. + +As you probably expect by now, we're going to go over this and give more +information about the various handlers. We won't go in the order they are +defined in the structure, because there is a lot of historical baggage that +impacts the ordering of the fields. It's often easiest to find an example +that includes the fields you need and then change the values to suit your new +type. :: + + const char *tp_name; /* For printing */ + +The name of the type -- as mentioned in the previous chapter, this will appear in +various places, almost entirely for diagnostic purposes. Try to choose something +that will be helpful in such a situation! :: + + Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */ + +These fields tell the runtime how much memory to allocate when new objects of +this type are created. Python has some built-in support for variable length +structures (think: strings, tuples) which is where the :c:member:`~PyTypeObject.tp_itemsize` field +comes in. This will be dealt with later. :: + + const char *tp_doc; + +Here you can put a string (or its address) that you want returned when the +Python script references ``obj.__doc__`` to retrieve the doc string. + +Now we come to the basic type methods -- the ones most extension types will +implement. + + +Finalization and De-allocation +------------------------------ + +.. index:: + single: object; deallocation + single: deallocation, object + single: object; finalization + single: finalization, of objects + +:: + + destructor tp_dealloc; + +This function is called when the reference count of the instance of your type is +reduced to zero and the Python interpreter wants to reclaim it. If your type +has memory to free or other clean-up to perform, you can put it here. The +object itself needs to be freed here as well. Here is an example of this +function:: + + static void + newdatatype_dealloc(newdatatypeobject *obj) + { + free(obj->obj_UnderlyingDatatypePtr); + Py_TYPE(obj)->tp_free(obj); + } + +.. index:: + single: PyErr_Fetch() + single: PyErr_Restore() + +One important requirement of the deallocator function is that it leaves any +pending exceptions alone. This is important since deallocators are frequently +called as the interpreter unwinds the Python stack; when the stack is unwound +due to an exception (rather than normal returns), nothing is done to protect the +deallocators from seeing that an exception has already been set. Any actions +which a deallocator performs which may cause additional Python code to be +executed may detect that an exception has been set. This can lead to misleading +errors from the interpreter. The proper way to protect against this is to save +a pending exception before performing the unsafe action, and restoring it when +done. This can be done using the :c:func:`PyErr_Fetch` and +:c:func:`PyErr_Restore` functions:: + + static void + my_dealloc(PyObject *obj) + { + MyObject *self = (MyObject *) obj; + PyObject *cbresult; + + if (self->my_callback != NULL) { + PyObject *err_type, *err_value, *err_traceback; + + /* This saves the current exception state */ + PyErr_Fetch(&err_type, &err_value, &err_traceback); + + cbresult = PyObject_CallNoArgs(self->my_callback); + if (cbresult == NULL) + PyErr_WriteUnraisable(self->my_callback); + else + Py_DECREF(cbresult); + + /* This restores the saved exception state */ + PyErr_Restore(err_type, err_value, err_traceback); + + Py_DECREF(self->my_callback); + } + Py_TYPE(obj)->tp_free((PyObject*)self); + } + +.. note:: + There are limitations to what you can safely do in a deallocator function. + First, if your type supports garbage collection (using :c:member:`~PyTypeObject.tp_traverse` + and/or :c:member:`~PyTypeObject.tp_clear`), some of the object's members can have been + cleared or finalized by the time :c:member:`~PyTypeObject.tp_dealloc` is called. Second, in + :c:member:`~PyTypeObject.tp_dealloc`, your object is in an unstable state: its reference + count is equal to zero. Any call to a non-trivial object or API (as in the + example above) might end up calling :c:member:`~PyTypeObject.tp_dealloc` again, causing a + double free and a crash. + + Starting with Python 3.4, it is recommended not to put any complex + finalization code in :c:member:`~PyTypeObject.tp_dealloc`, and instead use the new + :c:member:`~PyTypeObject.tp_finalize` type method. + + .. seealso:: + :pep:`442` explains the new finalization scheme. + +.. index:: + single: string; object representation + builtin: repr + +Object Presentation +------------------- + +In Python, there are two ways to generate a textual representation of an object: +the :func:`repr` function, and the :func:`str` function. (The :func:`print` +function just calls :func:`str`.) These handlers are both optional. + +:: + + reprfunc tp_repr; + reprfunc tp_str; + +The :c:member:`~PyTypeObject.tp_repr` handler should return a string object containing a +representation of the instance for which it is called. Here is a simple +example:: + + static PyObject * + newdatatype_repr(newdatatypeobject * obj) + { + return PyUnicode_FromFormat("Repr-ified_newdatatype{{size:%d}}", + obj->obj_UnderlyingDatatypePtr->size); + } + +If no :c:member:`~PyTypeObject.tp_repr` handler is specified, the interpreter will supply a +representation that uses the type's :c:member:`~PyTypeObject.tp_name` and a uniquely-identifying +value for the object. + +The :c:member:`~PyTypeObject.tp_str` handler is to :func:`str` what the :c:member:`~PyTypeObject.tp_repr` handler +described above is to :func:`repr`; that is, it is called when Python code calls +:func:`str` on an instance of your object. Its implementation is very similar +to the :c:member:`~PyTypeObject.tp_repr` function, but the resulting string is intended for human +consumption. If :c:member:`~PyTypeObject.tp_str` is not specified, the :c:member:`~PyTypeObject.tp_repr` handler is +used instead. + +Here is a simple example:: + + static PyObject * + newdatatype_str(newdatatypeobject * obj) + { + return PyUnicode_FromFormat("Stringified_newdatatype{{size:%d}}", + obj->obj_UnderlyingDatatypePtr->size); + } + + + +Attribute Management +-------------------- + +For every object which can support attributes, the corresponding type must +provide the functions that control how the attributes are resolved. There needs +to be a function which can retrieve attributes (if any are defined), and another +to set attributes (if setting attributes is allowed). Removing an attribute is +a special case, for which the new value passed to the handler is ``NULL``. + +Python supports two pairs of attribute handlers; a type that supports attributes +only needs to implement the functions for one pair. The difference is that one +pair takes the name of the attribute as a :c:type:`char\*`, while the other +accepts a :c:type:`PyObject\*`. Each type can use whichever pair makes more +sense for the implementation's convenience. :: + + getattrfunc tp_getattr; /* char * version */ + setattrfunc tp_setattr; + /* ... */ + getattrofunc tp_getattro; /* PyObject * version */ + setattrofunc tp_setattro; + +If accessing attributes of an object is always a simple operation (this will be +explained shortly), there are generic implementations which can be used to +provide the :c:type:`PyObject\*` version of the attribute management functions. +The actual need for type-specific attribute handlers almost completely +disappeared starting with Python 2.2, though there are many examples which have +not been updated to use some of the new generic mechanism that is available. + + +.. _generic-attribute-management: + +Generic Attribute Management +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Most extension types only use *simple* attributes. So, what makes the +attributes simple? There are only a couple of conditions that must be met: + +#. The name of the attributes must be known when :c:func:`PyType_Ready` is + called. + +#. No special processing is needed to record that an attribute was looked up or + set, nor do actions need to be taken based on the value. + +Note that this list does not place any restrictions on the values of the +attributes, when the values are computed, or how relevant data is stored. + +When :c:func:`PyType_Ready` is called, it uses three tables referenced by the +type object to create :term:`descriptor`\s which are placed in the dictionary of the +type object. Each descriptor controls access to one attribute of the instance +object. Each of the tables is optional; if all three are ``NULL``, instances of +the type will only have attributes that are inherited from their base type, and +should leave the :c:member:`~PyTypeObject.tp_getattro` and :c:member:`~PyTypeObject.tp_setattro` fields ``NULL`` as +well, allowing the base type to handle attributes. + +The tables are declared as three fields of the type object:: + + struct PyMethodDef *tp_methods; + struct PyMemberDef *tp_members; + struct PyGetSetDef *tp_getset; + +If :c:member:`~PyTypeObject.tp_methods` is not ``NULL``, it must refer to an array of +:c:type:`PyMethodDef` structures. Each entry in the table is an instance of this +structure:: + + typedef struct PyMethodDef { + const char *ml_name; /* method name */ + PyCFunction ml_meth; /* implementation function */ + int ml_flags; /* flags */ + const char *ml_doc; /* docstring */ + } PyMethodDef; + +One entry should be defined for each method provided by the type; no entries are +needed for methods inherited from a base type. One additional entry is needed +at the end; it is a sentinel that marks the end of the array. The +:attr:`ml_name` field of the sentinel must be ``NULL``. + +The second table is used to define attributes which map directly to data stored +in the instance. A variety of primitive C types are supported, and access may +be read-only or read-write. The structures in the table are defined as:: + + typedef struct PyMemberDef { + const char *name; + int type; + int offset; + int flags; + const char *doc; + } PyMemberDef; + +For each entry in the table, a :term:`descriptor` will be constructed and added to the +type which will be able to extract a value from the instance structure. The +:attr:`type` field should contain one of the type codes defined in the +:file:`structmember.h` header; the value will be used to determine how to +convert Python values to and from C values. The :attr:`flags` field is used to +store flags which control how the attribute can be accessed. + +The following flag constants are defined in :file:`structmember.h`; they may be +combined using bitwise-OR. + ++---------------------------+----------------------------------------------+ +| Constant | Meaning | ++===========================+==============================================+ +| :const:`READONLY` | Never writable. | ++---------------------------+----------------------------------------------+ +| :const:`READ_RESTRICTED` | Not readable in restricted mode. | ++---------------------------+----------------------------------------------+ +| :const:`WRITE_RESTRICTED` | Not writable in restricted mode. | ++---------------------------+----------------------------------------------+ +| :const:`RESTRICTED` | Not readable or writable in restricted mode. | ++---------------------------+----------------------------------------------+ + +.. index:: + single: READONLY + single: READ_RESTRICTED + single: WRITE_RESTRICTED + single: RESTRICTED + +An interesting advantage of using the :c:member:`~PyTypeObject.tp_members` table to build +descriptors that are used at runtime is that any attribute defined this way can +have an associated doc string simply by providing the text in the table. An +application can use the introspection API to retrieve the descriptor from the +class object, and get the doc string using its :attr:`__doc__` attribute. + +As with the :c:member:`~PyTypeObject.tp_methods` table, a sentinel entry with a :attr:`name` value +of ``NULL`` is required. + +.. XXX Descriptors need to be explained in more detail somewhere, but not here. + + Descriptor objects have two handler functions which correspond to the + \member{tp_getattro} and \member{tp_setattro} handlers. The + \method{__get__()} handler is a function which is passed the descriptor, + instance, and type objects, and returns the value of the attribute, or it + returns \NULL{} and sets an exception. The \method{__set__()} handler is + passed the descriptor, instance, type, and new value; + + +Type-specific Attribute Management +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +For simplicity, only the :c:type:`char\*` version will be demonstrated here; the +type of the name parameter is the only difference between the :c:type:`char\*` +and :c:type:`PyObject\*` flavors of the interface. This example effectively does +the same thing as the generic example above, but does not use the generic +support added in Python 2.2. It explains how the handler functions are +called, so that if you do need to extend their functionality, you'll understand +what needs to be done. + +The :c:member:`~PyTypeObject.tp_getattr` handler is called when the object requires an attribute +look-up. It is called in the same situations where the :meth:`__getattr__` +method of a class would be called. + +Here is an example:: + + static PyObject * + newdatatype_getattr(newdatatypeobject *obj, char *name) + { + if (strcmp(name, "data") == 0) + { + return PyLong_FromLong(obj->data); + } + + PyErr_Format(PyExc_AttributeError, + "'%.50s' object has no attribute '%.400s'", + tp->tp_name, name); + return NULL; + } + +The :c:member:`~PyTypeObject.tp_setattr` handler is called when the :meth:`__setattr__` or +:meth:`__delattr__` method of a class instance would be called. When an +attribute should be deleted, the third parameter will be ``NULL``. Here is an +example that simply raises an exception; if this were really all you wanted, the +:c:member:`~PyTypeObject.tp_setattr` handler should be set to ``NULL``. :: + + static int + newdatatype_setattr(newdatatypeobject *obj, char *name, PyObject *v) + { + PyErr_Format(PyExc_RuntimeError, "Read-only attribute: %s", name); + return -1; + } + +Object Comparison +----------------- + +:: + + richcmpfunc tp_richcompare; + +The :c:member:`~PyTypeObject.tp_richcompare` handler is called when comparisons are needed. It is +analogous to the :ref:`rich comparison methods <richcmpfuncs>`, like +:meth:`__lt__`, and also called by :c:func:`PyObject_RichCompare` and +:c:func:`PyObject_RichCompareBool`. + +This function is called with two Python objects and the operator as arguments, +where the operator is one of ``Py_EQ``, ``Py_NE``, ``Py_LE``, ``Py_GT``, +``Py_LT`` or ``Py_GT``. It should compare the two objects with respect to the +specified operator and return ``Py_True`` or ``Py_False`` if the comparison is +successful, ``Py_NotImplemented`` to indicate that comparison is not +implemented and the other object's comparison method should be tried, or ``NULL`` +if an exception was set. + +Here is a sample implementation, for a datatype that is considered equal if the +size of an internal pointer is equal:: + + static PyObject * + newdatatype_richcmp(PyObject *obj1, PyObject *obj2, int op) + { + PyObject *result; + int c, size1, size2; + + /* code to make sure that both arguments are of type + newdatatype omitted */ + + size1 = obj1->obj_UnderlyingDatatypePtr->size; + size2 = obj2->obj_UnderlyingDatatypePtr->size; + + switch (op) { + case Py_LT: c = size1 < size2; break; + case Py_LE: c = size1 <= size2; break; + case Py_EQ: c = size1 == size2; break; + case Py_NE: c = size1 != size2; break; + case Py_GT: c = size1 > size2; break; + case Py_GE: c = size1 >= size2; break; + } + result = c ? Py_True : Py_False; + Py_INCREF(result); + return result; + } + + +Abstract Protocol Support +------------------------- + +Python supports a variety of *abstract* 'protocols;' the specific interfaces +provided to use these interfaces are documented in :ref:`abstract`. + + +A number of these abstract interfaces were defined early in the development of +the Python implementation. In particular, the number, mapping, and sequence +protocols have been part of Python since the beginning. Other protocols have +been added over time. For protocols which depend on several handler routines +from the type implementation, the older protocols have been defined as optional +blocks of handlers referenced by the type object. For newer protocols there are +additional slots in the main type object, with a flag bit being set to indicate +that the slots are present and should be checked by the interpreter. (The flag +bit does not indicate that the slot values are non-``NULL``. The flag may be set +to indicate the presence of a slot, but a slot may still be unfilled.) :: + + PyNumberMethods *tp_as_number; + PySequenceMethods *tp_as_sequence; + PyMappingMethods *tp_as_mapping; + +If you wish your object to be able to act like a number, a sequence, or a +mapping object, then you place the address of a structure that implements the C +type :c:type:`PyNumberMethods`, :c:type:`PySequenceMethods`, or +:c:type:`PyMappingMethods`, respectively. It is up to you to fill in this +structure with appropriate values. You can find examples of the use of each of +these in the :file:`Objects` directory of the Python source distribution. :: + + hashfunc tp_hash; + +This function, if you choose to provide it, should return a hash number for an +instance of your data type. Here is a simple example:: + + static Py_hash_t + newdatatype_hash(newdatatypeobject *obj) + { + Py_hash_t result; + result = obj->some_size + 32767 * obj->some_number; + if (result == -1) + result = -2; + return result; + } + +:c:type:`Py_hash_t` is a signed integer type with a platform-varying width. +Returning ``-1`` from :c:member:`~PyTypeObject.tp_hash` indicates an error, +which is why you should be careful to avoid returning it when hash computation +is successful, as seen above. + +:: + + ternaryfunc tp_call; + +This function is called when an instance of your data type is "called", for +example, if ``obj1`` is an instance of your data type and the Python script +contains ``obj1('hello')``, the :c:member:`~PyTypeObject.tp_call` handler is invoked. + +This function takes three arguments: + +#. *self* is the instance of the data type which is the subject of the call. + If the call is ``obj1('hello')``, then *self* is ``obj1``. + +#. *args* is a tuple containing the arguments to the call. You can use + :c:func:`PyArg_ParseTuple` to extract the arguments. + +#. *kwds* is a dictionary of keyword arguments that were passed. If this is + non-``NULL`` and you support keyword arguments, use + :c:func:`PyArg_ParseTupleAndKeywords` to extract the arguments. If you + do not want to support keyword arguments and this is non-``NULL``, raise a + :exc:`TypeError` with a message saying that keyword arguments are not supported. + +Here is a toy ``tp_call`` implementation:: + + static PyObject * + newdatatype_call(newdatatypeobject *self, PyObject *args, PyObject *kwds) + { + PyObject *result; + const char *arg1; + const char *arg2; + const char *arg3; + + if (!PyArg_ParseTuple(args, "sss:call", &arg1, &arg2, &arg3)) { + return NULL; + } + result = PyUnicode_FromFormat( + "Returning -- value: [%d] arg1: [%s] arg2: [%s] arg3: [%s]\n", + obj->obj_UnderlyingDatatypePtr->size, + arg1, arg2, arg3); + return result; + } + +:: + + /* Iterators */ + getiterfunc tp_iter; + iternextfunc tp_iternext; + +These functions provide support for the iterator protocol. Both handlers +take exactly one parameter, the instance for which they are being called, +and return a new reference. In the case of an error, they should set an +exception and return ``NULL``. :c:member:`~PyTypeObject.tp_iter` corresponds +to the Python :meth:`__iter__` method, while :c:member:`~PyTypeObject.tp_iternext` +corresponds to the Python :meth:`~iterator.__next__` method. + +Any :term:`iterable` object must implement the :c:member:`~PyTypeObject.tp_iter` +handler, which must return an :term:`iterator` object. Here the same guidelines +apply as for Python classes: + +* For collections (such as lists and tuples) which can support multiple + independent iterators, a new iterator should be created and returned by + each call to :c:member:`~PyTypeObject.tp_iter`. +* Objects which can only be iterated over once (usually due to side effects of + iteration, such as file objects) can implement :c:member:`~PyTypeObject.tp_iter` + by returning a new reference to themselves -- and should also therefore + implement the :c:member:`~PyTypeObject.tp_iternext` handler. + +Any :term:`iterator` object should implement both :c:member:`~PyTypeObject.tp_iter` +and :c:member:`~PyTypeObject.tp_iternext`. An iterator's +:c:member:`~PyTypeObject.tp_iter` handler should return a new reference +to the iterator. Its :c:member:`~PyTypeObject.tp_iternext` handler should +return a new reference to the next object in the iteration, if there is one. +If the iteration has reached the end, :c:member:`~PyTypeObject.tp_iternext` +may return ``NULL`` without setting an exception, or it may set +:exc:`StopIteration` *in addition* to returning ``NULL``; avoiding +the exception can yield slightly better performance. If an actual error +occurs, :c:member:`~PyTypeObject.tp_iternext` should always set an exception +and return ``NULL``. + + +.. _weakref-support: + +Weak Reference Support +---------------------- + +One of the goals of Python's weak reference implementation is to allow any type +to participate in the weak reference mechanism without incurring the overhead on +performance-critical objects (such as numbers). + +.. seealso:: + Documentation for the :mod:`weakref` module. + +For an object to be weakly referencable, the extension type must do two things: + +#. Include a :c:type:`PyObject\*` field in the C object structure dedicated to + the weak reference mechanism. The object's constructor should leave it + ``NULL`` (which is automatic when using the default + :c:member:`~PyTypeObject.tp_alloc`). + +#. Set the :c:member:`~PyTypeObject.tp_weaklistoffset` type member + to the offset of the aforementioned field in the C object structure, + so that the interpreter knows how to access and modify that field. + +Concretely, here is how a trivial object structure would be augmented +with the required field:: + + typedef struct { + PyObject_HEAD + PyObject *weakreflist; /* List of weak references */ + } TrivialObject; + +And the corresponding member in the statically-declared type object:: + + static PyTypeObject TrivialType = { + PyVarObject_HEAD_INIT(NULL, 0) + /* ... other members omitted for brevity ... */ + .tp_weaklistoffset = offsetof(TrivialObject, weakreflist), + }; + +The only further addition is that ``tp_dealloc`` needs to clear any weak +references (by calling :c:func:`PyObject_ClearWeakRefs`) if the field is +non-``NULL``:: + + static void + Trivial_dealloc(TrivialObject *self) + { + /* Clear weakrefs first before calling any destructors */ + if (self->weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *) self); + /* ... remainder of destruction code omitted for brevity ... */ + Py_TYPE(self)->tp_free((PyObject *) self); + } + + +More Suggestions +---------------- + +In order to learn how to implement any specific method for your new data type, +get the :term:`CPython` source code. Go to the :file:`Objects` directory, +then search the C source files for ``tp_`` plus the function you want +(for example, ``tp_richcompare``). You will find examples of the function +you want to implement. + +When you need to verify that an object is a concrete instance of the type you +are implementing, use the :c:func:`PyObject_TypeCheck` function. A sample of +its use might be something like the following:: + + if (!PyObject_TypeCheck(some_object, &MyType)) { + PyErr_SetString(PyExc_TypeError, "arg #1 not a mything"); + return NULL; + } + +.. seealso:: + Download CPython source releases. + https://www.python.org/downloads/source/ + + The CPython project on GitHub, where the CPython source code is developed. + https://github.com/python/cpython diff --git a/cpython_2/environment/repo/Doc/extending/newtypes_tutorial.rst b/cpython_2/environment/repo/Doc/extending/newtypes_tutorial.rst new file mode 100644 index 0000000000000000000000000000000000000000..0eb6ffd026f495913e9651085f5c2361361d0f00 --- /dev/null +++ b/cpython_2/environment/repo/Doc/extending/newtypes_tutorial.rst @@ -0,0 +1,907 @@ +.. highlight:: c + +.. _defining-new-types: + +********************************** +Defining Extension Types: Tutorial +********************************** + +.. sectionauthor:: Michael Hudson <mwh@python.net> +.. sectionauthor:: Dave Kuhlman <dkuhlman@rexx.com> +.. sectionauthor:: Jim Fulton <jim@zope.com> + + +Python allows the writer of a C extension module to define new types that +can be manipulated from Python code, much like the built-in :class:`str` +and :class:`list` types. The code for all extension types follows a +pattern, but there are some details that you need to understand before you +can get started. This document is a gentle introduction to the topic. + + +.. _dnt-basics: + +The Basics +========== + +The :term:`CPython` runtime sees all Python objects as variables of type +:c:type:`PyObject\*`, which serves as a "base type" for all Python objects. +The :c:type:`PyObject` structure itself only contains the object's +:term:`reference count` and a pointer to the object's "type object". +This is where the action is; the type object determines which (C) functions +get called by the interpreter when, for instance, an attribute gets looked up +on an object, a method called, or it is multiplied by another object. These +C functions are called "type methods". + +So, if you want to define a new extension type, you need to create a new type +object. + +This sort of thing can only be explained by example, so here's a minimal, but +complete, module that defines a new type named :class:`Custom` inside a C +extension module :mod:`custom`: + +.. note:: + What we're showing here is the traditional way of defining *static* + extension types. It should be adequate for most uses. The C API also + allows defining heap-allocated extension types using the + :c:func:`PyType_FromSpec` function, which isn't covered in this tutorial. + +.. literalinclude:: ../includes/custom.c + +Now that's quite a bit to take in at once, but hopefully bits will seem familiar +from the previous chapter. This file defines three things: + +#. What a :class:`Custom` **object** contains: this is the ``CustomObject`` + struct, which is allocated once for each :class:`Custom` instance. +#. How the :class:`Custom` **type** behaves: this is the ``CustomType`` struct, + which defines a set of flags and function pointers that the interpreter + inspects when specific operations are requested. +#. How to initialize the :mod:`custom` module: this is the ``PyInit_custom`` + function and the associated ``custommodule`` struct. + +The first bit is:: + + typedef struct { + PyObject_HEAD + } CustomObject; + +This is what a Custom object will contain. ``PyObject_HEAD`` is mandatory +at the start of each object struct and defines a field called ``ob_base`` +of type :c:type:`PyObject`, containing a pointer to a type object and a +reference count (these can be accessed using the macros :c:macro:`Py_REFCNT` +and :c:macro:`Py_TYPE` respectively). The reason for the macro is to +abstract away the layout and to enable additional fields in debug builds. + +.. note:: + There is no semicolon above after the :c:macro:`PyObject_HEAD` macro. + Be wary of adding one by accident: some compilers will complain. + +Of course, objects generally store additional data besides the standard +``PyObject_HEAD`` boilerplate; for example, here is the definition for +standard Python floats:: + + typedef struct { + PyObject_HEAD + double ob_fval; + } PyFloatObject; + +The second bit is the definition of the type object. :: + + static PyTypeObject CustomType = { + PyVarObject_HEAD_INIT(NULL, 0) + .tp_name = "custom.Custom", + .tp_doc = "Custom objects", + .tp_basicsize = sizeof(CustomObject), + .tp_itemsize = 0, + .tp_flags = Py_TPFLAGS_DEFAULT, + .tp_new = PyType_GenericNew, + }; + +.. note:: + We recommend using C99-style designated initializers as above, to + avoid listing all the :c:type:`PyTypeObject` fields that you don't care + about and also to avoid caring about the fields' declaration order. + +The actual definition of :c:type:`PyTypeObject` in :file:`object.h` has +many more :ref:`fields <type-structs>` than the definition above. The +remaining fields will be filled with zeros by the C compiler, and it's +common practice to not specify them explicitly unless you need them. + +We're going to pick it apart, one field at a time:: + + PyVarObject_HEAD_INIT(NULL, 0) + +This line is mandatory boilerplate to initialize the ``ob_base`` +field mentioned above. :: + + .tp_name = "custom.Custom", + +The name of our type. This will appear in the default textual representation of +our objects and in some error messages, for example: + +.. code-block:: pycon + + >>> "" + custom.Custom() + Traceback (most recent call last): + File "<stdin>", line 1, in <module> + TypeError: can only concatenate str (not "custom.Custom") to str + +Note that the name is a dotted name that includes both the module name and the +name of the type within the module. The module in this case is :mod:`custom` and +the type is :class:`Custom`, so we set the type name to :class:`custom.Custom`. +Using the real dotted import path is important to make your type compatible +with the :mod:`pydoc` and :mod:`pickle` modules. :: + + .tp_basicsize = sizeof(CustomObject), + .tp_itemsize = 0, + +This is so that Python knows how much memory to allocate when creating +new :class:`Custom` instances. :c:member:`~PyTypeObject.tp_itemsize` is +only used for variable-sized objects and should otherwise be zero. + +.. note:: + + If you want your type to be subclassable from Python, and your type has the same + :c:member:`~PyTypeObject.tp_basicsize` as its base type, you may have problems with multiple + inheritance. A Python subclass of your type will have to list your type first + in its :attr:`~class.__bases__`, or else it will not be able to call your type's + :meth:`__new__` method without getting an error. You can avoid this problem by + ensuring that your type has a larger value for :c:member:`~PyTypeObject.tp_basicsize` than its + base type does. Most of the time, this will be true anyway, because either your + base type will be :class:`object`, or else you will be adding data members to + your base type, and therefore increasing its size. + +We set the class flags to :const:`Py_TPFLAGS_DEFAULT`. :: + + .tp_flags = Py_TPFLAGS_DEFAULT, + +All types should include this constant in their flags. It enables all of the +members defined until at least Python 3.3. If you need further members, +you will need to OR the corresponding flags. + +We provide a doc string for the type in :c:member:`~PyTypeObject.tp_doc`. :: + + .tp_doc = "Custom objects", + +To enable object creation, we have to provide a :c:member:`~PyTypeObject.tp_new` +handler. This is the equivalent of the Python method :meth:`__new__`, but +has to be specified explicitly. In this case, we can just use the default +implementation provided by the API function :c:func:`PyType_GenericNew`. :: + + .tp_new = PyType_GenericNew, + +Everything else in the file should be familiar, except for some code in +:c:func:`PyInit_custom`:: + + if (PyType_Ready(&CustomType) < 0) + return; + +This initializes the :class:`Custom` type, filling in a number of members +to the appropriate default values, including :attr:`ob_type` that we initially +set to ``NULL``. :: + + Py_INCREF(&CustomType); + if (PyModule_AddObject(m, "Custom", (PyObject *) &CustomType) < 0) { + Py_DECREF(&CustomType); + Py_DECREF(m); + return NULL; + } + +This adds the type to the module dictionary. This allows us to create +:class:`Custom` instances by calling the :class:`Custom` class: + +.. code-block:: pycon + + >>> import custom + >>> mycustom = custom.Custom() + +That's it! All that remains is to build it; put the above code in a file called +:file:`custom.c` and: + +.. code-block:: python + + from distutils.core import setup, Extension + setup(name="custom", version="1.0", + ext_modules=[Extension("custom", ["custom.c"])]) + +in a file called :file:`setup.py`; then typing + +.. code-block:: shell-session + + $ python setup.py build + +at a shell should produce a file :file:`custom.so` in a subdirectory; move to +that directory and fire up Python --- you should be able to ``import custom`` and +play around with Custom objects. + +That wasn't so hard, was it? + +Of course, the current Custom type is pretty uninteresting. It has no data and +doesn't do anything. It can't even be subclassed. + +.. note:: + While this documentation showcases the standard :mod:`distutils` module + for building C extensions, it is recommended in real-world use cases to + use the newer and better-maintained ``setuptools`` library. Documentation + on how to do this is out of scope for this document and can be found in + the `Python Packaging User's Guide <https://packaging.python.org/tutorials/distributing-packages/>`_. + + +Adding data and methods to the Basic example +============================================ + +Let's extend the basic example to add some data and methods. Let's also make +the type usable as a base class. We'll create a new module, :mod:`custom2` that +adds these capabilities: + +.. literalinclude:: ../includes/custom2.c + + +This version of the module has a number of changes. + +We've added an extra include:: + + #include <structmember.h> + +This include provides declarations that we use to handle attributes, as +described a bit later. + +The :class:`Custom` type now has three data attributes in its C struct, +*first*, *last*, and *number*. The *first* and *last* variables are Python +strings containing first and last names. The *number* attribute is a C integer. + +The object structure is updated accordingly:: + + typedef struct { + PyObject_HEAD + PyObject *first; /* first name */ + PyObject *last; /* last name */ + int number; + } CustomObject; + +Because we now have data to manage, we have to be more careful about object +allocation and deallocation. At a minimum, we need a deallocation method:: + + static void + Custom_dealloc(CustomObject *self) + { + Py_XDECREF(self->first); + Py_XDECREF(self->last); + Py_TYPE(self)->tp_free((PyObject *) self); + } + +which is assigned to the :c:member:`~PyTypeObject.tp_dealloc` member:: + + .tp_dealloc = (destructor) Custom_dealloc, + +This method first clears the reference counts of the two Python attributes. +:c:func:`Py_XDECREF` correctly handles the case where its argument is +``NULL`` (which might happen here if ``tp_new`` failed midway). It then +calls the :c:member:`~PyTypeObject.tp_free` member of the object's type +(computed by ``Py_TYPE(self)``) to free the object's memory. Note that +the object's type might not be :class:`CustomType`, because the object may +be an instance of a subclass. + +.. note:: + The explicit cast to ``destructor`` above is needed because we defined + ``Custom_dealloc`` to take a ``CustomObject *`` argument, but the ``tp_dealloc`` + function pointer expects to receive a ``PyObject *`` argument. Otherwise, + the compiler will emit a warning. This is object-oriented polymorphism, + in C! + +We want to make sure that the first and last names are initialized to empty +strings, so we provide a ``tp_new`` implementation:: + + static PyObject * + Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + CustomObject *self; + self = (CustomObject *) type->tp_alloc(type, 0); + if (self != NULL) { + self->first = PyUnicode_FromString(""); + if (self->first == NULL) { + Py_DECREF(self); + return NULL; + } + self->last = PyUnicode_FromString(""); + if (self->last == NULL) { + Py_DECREF(self); + return NULL; + } + self->number = 0; + } + return (PyObject *) self; + } + +and install it in the :c:member:`~PyTypeObject.tp_new` member:: + + .tp_new = Custom_new, + +The ``tp_new`` handler is responsible for creating (as opposed to initializing) +objects of the type. It is exposed in Python as the :meth:`__new__` method. +It is not required to define a ``tp_new`` member, and indeed many extension +types will simply reuse :c:func:`PyType_GenericNew` as done in the first +version of the ``Custom`` type above. In this case, we use the ``tp_new`` +handler to initialize the ``first`` and ``last`` attributes to non-``NULL`` +default values. + +``tp_new`` is passed the type being instantiated (not necessarily ``CustomType``, +if a subclass is instantiated) and any arguments passed when the type was +called, and is expected to return the instance created. ``tp_new`` handlers +always accept positional and keyword arguments, but they often ignore the +arguments, leaving the argument handling to initializer (a.k.a. ``tp_init`` +in C or ``__init__`` in Python) methods. + +.. note:: + ``tp_new`` shouldn't call ``tp_init`` explicitly, as the interpreter + will do it itself. + +The ``tp_new`` implementation calls the :c:member:`~PyTypeObject.tp_alloc` +slot to allocate memory:: + + self = (CustomObject *) type->tp_alloc(type, 0); + +Since memory allocation may fail, we must check the :c:member:`~PyTypeObject.tp_alloc` +result against ``NULL`` before proceeding. + +.. note:: + We didn't fill the :c:member:`~PyTypeObject.tp_alloc` slot ourselves. Rather + :c:func:`PyType_Ready` fills it for us by inheriting it from our base class, + which is :class:`object` by default. Most types use the default allocation + strategy. + +.. note:: + If you are creating a co-operative :c:member:`~PyTypeObject.tp_new` (one + that calls a base type's :c:member:`~PyTypeObject.tp_new` or :meth:`__new__`), + you must *not* try to determine what method to call using method resolution + order at runtime. Always statically determine what type you are going to + call, and call its :c:member:`~PyTypeObject.tp_new` directly, or via + ``type->tp_base->tp_new``. If you do not do this, Python subclasses of your + type that also inherit from other Python-defined classes may not work correctly. + (Specifically, you may not be able to create instances of such subclasses + without getting a :exc:`TypeError`.) + +We also define an initialization function which accepts arguments to provide +initial values for our instance:: + + static int + Custom_init(CustomObject *self, PyObject *args, PyObject *kwds) + { + static char *kwlist[] = {"first", "last", "number", NULL}; + PyObject *first = NULL, *last = NULL, *tmp; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi", kwlist, + &first, &last, + &self->number)) + return -1; + + if (first) { + tmp = self->first; + Py_INCREF(first); + self->first = first; + Py_XDECREF(tmp); + } + if (last) { + tmp = self->last; + Py_INCREF(last); + self->last = last; + Py_XDECREF(tmp); + } + return 0; + } + +by filling the :c:member:`~PyTypeObject.tp_init` slot. :: + + .tp_init = (initproc) Custom_init, + +The :c:member:`~PyTypeObject.tp_init` slot is exposed in Python as the +:meth:`__init__` method. It is used to initialize an object after it's +created. Initializers always accept positional and keyword arguments, +and they should return either ``0`` on success or ``-1`` on error. + +Unlike the ``tp_new`` handler, there is no guarantee that ``tp_init`` +is called at all (for example, the :mod:`pickle` module by default +doesn't call :meth:`__init__` on unpickled instances). It can also be +called multiple times. Anyone can call the :meth:`__init__` method on +our objects. For this reason, we have to be extra careful when assigning +the new attribute values. We might be tempted, for example to assign the +``first`` member like this:: + + if (first) { + Py_XDECREF(self->first); + Py_INCREF(first); + self->first = first; + } + +But this would be risky. Our type doesn't restrict the type of the +``first`` member, so it could be any kind of object. It could have a +destructor that causes code to be executed that tries to access the +``first`` member; or that destructor could release the +:term:`Global interpreter Lock` and let arbitrary code run in other +threads that accesses and modifies our object. + +To be paranoid and protect ourselves against this possibility, we almost +always reassign members before decrementing their reference counts. When +don't we have to do this? + +* when we absolutely know that the reference count is greater than 1; + +* when we know that deallocation of the object [#]_ will neither release + the :term:`GIL` nor cause any calls back into our type's code; + +* when decrementing a reference count in a :c:member:`~PyTypeObject.tp_dealloc` + handler on a type which doesn't support cyclic garbage collection [#]_. + +We want to expose our instance variables as attributes. There are a +number of ways to do that. The simplest way is to define member definitions:: + + static PyMemberDef Custom_members[] = { + {"first", T_OBJECT_EX, offsetof(CustomObject, first), 0, + "first name"}, + {"last", T_OBJECT_EX, offsetof(CustomObject, last), 0, + "last name"}, + {"number", T_INT, offsetof(CustomObject, number), 0, + "custom number"}, + {NULL} /* Sentinel */ + }; + +and put the definitions in the :c:member:`~PyTypeObject.tp_members` slot:: + + .tp_members = Custom_members, + +Each member definition has a member name, type, offset, access flags and +documentation string. See the :ref:`Generic-Attribute-Management` section +below for details. + +A disadvantage of this approach is that it doesn't provide a way to restrict the +types of objects that can be assigned to the Python attributes. We expect the +first and last names to be strings, but any Python objects can be assigned. +Further, the attributes can be deleted, setting the C pointers to ``NULL``. Even +though we can make sure the members are initialized to non-``NULL`` values, the +members can be set to ``NULL`` if the attributes are deleted. + +We define a single method, :meth:`Custom.name()`, that outputs the objects name as the +concatenation of the first and last names. :: + + static PyObject * + Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored)) + { + if (self->first == NULL) { + PyErr_SetString(PyExc_AttributeError, "first"); + return NULL; + } + if (self->last == NULL) { + PyErr_SetString(PyExc_AttributeError, "last"); + return NULL; + } + return PyUnicode_FromFormat("%S %S", self->first, self->last); + } + +The method is implemented as a C function that takes a :class:`Custom` (or +:class:`Custom` subclass) instance as the first argument. Methods always take an +instance as the first argument. Methods often take positional and keyword +arguments as well, but in this case we don't take any and don't need to accept +a positional argument tuple or keyword argument dictionary. This method is +equivalent to the Python method: + +.. code-block:: python + + def name(self): + return "%s %s" % (self.first, self.last) + +Note that we have to check for the possibility that our :attr:`first` and +:attr:`last` members are ``NULL``. This is because they can be deleted, in which +case they are set to ``NULL``. It would be better to prevent deletion of these +attributes and to restrict the attribute values to be strings. We'll see how to +do that in the next section. + +Now that we've defined the method, we need to create an array of method +definitions:: + + static PyMethodDef Custom_methods[] = { + {"name", (PyCFunction) Custom_name, METH_NOARGS, + "Return the name, combining the first and last name" + }, + {NULL} /* Sentinel */ + }; + +(note that we used the :const:`METH_NOARGS` flag to indicate that the method +is expecting no arguments other than *self*) + +and assign it to the :c:member:`~PyTypeObject.tp_methods` slot:: + + .tp_methods = Custom_methods, + +Finally, we'll make our type usable as a base class for subclassing. We've +written our methods carefully so far so that they don't make any assumptions +about the type of the object being created or used, so all we need to do is +to add the :const:`Py_TPFLAGS_BASETYPE` to our class flag definition:: + + .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, + +We rename :c:func:`PyInit_custom` to :c:func:`PyInit_custom2`, update the +module name in the :c:type:`PyModuleDef` struct, and update the full class +name in the :c:type:`PyTypeObject` struct. + +Finally, we update our :file:`setup.py` file to build the new module: + +.. code-block:: python + + from distutils.core import setup, Extension + setup(name="custom", version="1.0", + ext_modules=[ + Extension("custom", ["custom.c"]), + Extension("custom2", ["custom2.c"]), + ]) + + +Providing finer control over data attributes +============================================ + +In this section, we'll provide finer control over how the :attr:`first` and +:attr:`last` attributes are set in the :class:`Custom` example. In the previous +version of our module, the instance variables :attr:`first` and :attr:`last` +could be set to non-string values or even deleted. We want to make sure that +these attributes always contain strings. + +.. literalinclude:: ../includes/custom3.c + + +To provide greater control, over the :attr:`first` and :attr:`last` attributes, +we'll use custom getter and setter functions. Here are the functions for +getting and setting the :attr:`first` attribute:: + + static PyObject * + Custom_getfirst(CustomObject *self, void *closure) + { + Py_INCREF(self->first); + return self->first; + } + + static int + Custom_setfirst(CustomObject *self, PyObject *value, void *closure) + { + PyObject *tmp; + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, "Cannot delete the first attribute"); + return -1; + } + if (!PyUnicode_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "The first attribute value must be a string"); + return -1; + } + tmp = self->first; + Py_INCREF(value); + self->first = value; + Py_DECREF(tmp); + return 0; + } + +The getter function is passed a :class:`Custom` object and a "closure", which is +a void pointer. In this case, the closure is ignored. (The closure supports an +advanced usage in which definition data is passed to the getter and setter. This +could, for example, be used to allow a single set of getter and setter functions +that decide the attribute to get or set based on data in the closure.) + +The setter function is passed the :class:`Custom` object, the new value, and the +closure. The new value may be ``NULL``, in which case the attribute is being +deleted. In our setter, we raise an error if the attribute is deleted or if its +new value is not a string. + +We create an array of :c:type:`PyGetSetDef` structures:: + + static PyGetSetDef Custom_getsetters[] = { + {"first", (getter) Custom_getfirst, (setter) Custom_setfirst, + "first name", NULL}, + {"last", (getter) Custom_getlast, (setter) Custom_setlast, + "last name", NULL}, + {NULL} /* Sentinel */ + }; + +and register it in the :c:member:`~PyTypeObject.tp_getset` slot:: + + .tp_getset = Custom_getsetters, + +The last item in a :c:type:`PyGetSetDef` structure is the "closure" mentioned +above. In this case, we aren't using a closure, so we just pass ``NULL``. + +We also remove the member definitions for these attributes:: + + static PyMemberDef Custom_members[] = { + {"number", T_INT, offsetof(CustomObject, number), 0, + "custom number"}, + {NULL} /* Sentinel */ + }; + +We also need to update the :c:member:`~PyTypeObject.tp_init` handler to only +allow strings [#]_ to be passed:: + + static int + Custom_init(CustomObject *self, PyObject *args, PyObject *kwds) + { + static char *kwlist[] = {"first", "last", "number", NULL}; + PyObject *first = NULL, *last = NULL, *tmp; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|UUi", kwlist, + &first, &last, + &self->number)) + return -1; + + if (first) { + tmp = self->first; + Py_INCREF(first); + self->first = first; + Py_DECREF(tmp); + } + if (last) { + tmp = self->last; + Py_INCREF(last); + self->last = last; + Py_DECREF(tmp); + } + return 0; + } + +With these changes, we can assure that the ``first`` and ``last`` members are +never ``NULL`` so we can remove checks for ``NULL`` values in almost all cases. +This means that most of the :c:func:`Py_XDECREF` calls can be converted to +:c:func:`Py_DECREF` calls. The only place we can't change these calls is in +the ``tp_dealloc`` implementation, where there is the possibility that the +initialization of these members failed in ``tp_new``. + +We also rename the module initialization function and module name in the +initialization function, as we did before, and we add an extra definition to the +:file:`setup.py` file. + + +Supporting cyclic garbage collection +==================================== + +Python has a :term:`cyclic garbage collector (GC) <garbage collection>` that +can identify unneeded objects even when their reference counts are not zero. +This can happen when objects are involved in cycles. For example, consider: + +.. code-block:: pycon + + >>> l = [] + >>> l.append(l) + >>> del l + +In this example, we create a list that contains itself. When we delete it, it +still has a reference from itself. Its reference count doesn't drop to zero. +Fortunately, Python's cyclic garbage collector will eventually figure out that +the list is garbage and free it. + +In the second version of the :class:`Custom` example, we allowed any kind of +object to be stored in the :attr:`first` or :attr:`last` attributes [#]_. +Besides, in the second and third versions, we allowed subclassing +:class:`Custom`, and subclasses may add arbitrary attributes. For any of +those two reasons, :class:`Custom` objects can participate in cycles: + +.. code-block:: pycon + + >>> import custom3 + >>> class Derived(custom3.Custom): pass + ... + >>> n = Derived() + >>> n.some_attribute = n + +To allow a :class:`Custom` instance participating in a reference cycle to +be properly detected and collected by the cyclic GC, our :class:`Custom` type +needs to fill two additional slots and to enable a flag that enables these slots: + +.. literalinclude:: ../includes/custom4.c + + +First, the traversal method lets the cyclic GC know about subobjects that could +participate in cycles:: + + static int + Custom_traverse(CustomObject *self, visitproc visit, void *arg) + { + int vret; + if (self->first) { + vret = visit(self->first, arg); + if (vret != 0) + return vret; + } + if (self->last) { + vret = visit(self->last, arg); + if (vret != 0) + return vret; + } + return 0; + } + +For each subobject that can participate in cycles, we need to call the +:c:func:`visit` function, which is passed to the traversal method. The +:c:func:`visit` function takes as arguments the subobject and the extra argument +*arg* passed to the traversal method. It returns an integer value that must be +returned if it is non-zero. + +Python provides a :c:func:`Py_VISIT` macro that automates calling visit +functions. With :c:func:`Py_VISIT`, we can minimize the amount of boilerplate +in ``Custom_traverse``:: + + static int + Custom_traverse(CustomObject *self, visitproc visit, void *arg) + { + Py_VISIT(self->first); + Py_VISIT(self->last); + return 0; + } + +.. note:: + The :c:member:`~PyTypeObject.tp_traverse` implementation must name its + arguments exactly *visit* and *arg* in order to use :c:func:`Py_VISIT`. + +Second, we need to provide a method for clearing any subobjects that can +participate in cycles:: + + static int + Custom_clear(CustomObject *self) + { + Py_CLEAR(self->first); + Py_CLEAR(self->last); + return 0; + } + +Notice the use of the :c:func:`Py_CLEAR` macro. It is the recommended and safe +way to clear data attributes of arbitrary types while decrementing +their reference counts. If you were to call :c:func:`Py_XDECREF` instead +on the attribute before setting it to ``NULL``, there is a possibility +that the attribute's destructor would call back into code that reads the +attribute again (*especially* if there is a reference cycle). + +.. note:: + You could emulate :c:func:`Py_CLEAR` by writing:: + + PyObject *tmp; + tmp = self->first; + self->first = NULL; + Py_XDECREF(tmp); + + Nevertheless, it is much easier and less error-prone to always + use :c:func:`Py_CLEAR` when deleting an attribute. Don't + try to micro-optimize at the expense of robustness! + +The deallocator ``Custom_dealloc`` may call arbitrary code when clearing +attributes. It means the circular GC can be triggered inside the function. +Since the GC assumes reference count is not zero, we need to untrack the object +from the GC by calling :c:func:`PyObject_GC_UnTrack` before clearing members. +Here is our reimplemented deallocator using :c:func:`PyObject_GC_UnTrack` +and ``Custom_clear``:: + + static void + Custom_dealloc(CustomObject *self) + { + PyObject_GC_UnTrack(self); + Custom_clear(self); + Py_TYPE(self)->tp_free((PyObject *) self); + } + +Finally, we add the :const:`Py_TPFLAGS_HAVE_GC` flag to the class flags:: + + .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, + +That's pretty much it. If we had written custom :c:member:`~PyTypeObject.tp_alloc` or +:c:member:`~PyTypeObject.tp_free` handlers, we'd need to modify them for cyclic +garbage collection. Most extensions will use the versions automatically provided. + + +Subclassing other types +======================= + +It is possible to create new extension types that are derived from existing +types. It is easiest to inherit from the built in types, since an extension can +easily use the :c:type:`PyTypeObject` it needs. It can be difficult to share +these :c:type:`PyTypeObject` structures between extension modules. + +In this example we will create a :class:`SubList` type that inherits from the +built-in :class:`list` type. The new type will be completely compatible with +regular lists, but will have an additional :meth:`increment` method that +increases an internal counter: + +.. code-block:: pycon + + >>> import sublist + >>> s = sublist.SubList(range(3)) + >>> s.extend(s) + >>> print(len(s)) + 6 + >>> print(s.increment()) + 1 + >>> print(s.increment()) + 2 + +.. literalinclude:: ../includes/sublist.c + + +As you can see, the source code closely resembles the :class:`Custom` examples in +previous sections. We will break down the main differences between them. :: + + typedef struct { + PyListObject list; + int state; + } SubListObject; + +The primary difference for derived type objects is that the base type's +object structure must be the first value. The base type will already include +the :c:func:`PyObject_HEAD` at the beginning of its structure. + +When a Python object is a :class:`SubList` instance, its ``PyObject *`` pointer +can be safely cast to both ``PyListObject *`` and ``SubListObject *``:: + + static int + SubList_init(SubListObject *self, PyObject *args, PyObject *kwds) + { + if (PyList_Type.tp_init((PyObject *) self, args, kwds) < 0) + return -1; + self->state = 0; + return 0; + } + +We see above how to call through to the :attr:`__init__` method of the base +type. + +This pattern is important when writing a type with custom +:c:member:`~PyTypeObject.tp_new` and :c:member:`~PyTypeObject.tp_dealloc` +members. The :c:member:`~PyTypeObject.tp_new` handler should not actually +create the memory for the object with its :c:member:`~PyTypeObject.tp_alloc`, +but let the base class handle it by calling its own :c:member:`~PyTypeObject.tp_new`. + +The :c:type:`PyTypeObject` struct supports a :c:member:`~PyTypeObject.tp_base` +specifying the type's concrete base class. Due to cross-platform compiler +issues, you can't fill that field directly with a reference to +:c:type:`PyList_Type`; it should be done later in the module initialization +function:: + + PyMODINIT_FUNC + PyInit_sublist(void) + { + PyObject* m; + SubListType.tp_base = &PyList_Type; + if (PyType_Ready(&SubListType) < 0) + return NULL; + + m = PyModule_Create(&sublistmodule); + if (m == NULL) + return NULL; + + Py_INCREF(&SubListType); + if (PyModule_AddObject(m, "SubList", (PyObject *) &SubListType) < 0) { + Py_DECREF(&SubListType); + Py_DECREF(m); + return NULL; + } + + return m; + } + +Before calling :c:func:`PyType_Ready`, the type structure must have the +:c:member:`~PyTypeObject.tp_base` slot filled in. When we are deriving an +existing type, it is not necessary to fill out the :c:member:`~PyTypeObject.tp_alloc` +slot with :c:func:`PyType_GenericNew` -- the allocation function from the base +type will be inherited. + +After that, calling :c:func:`PyType_Ready` and adding the type object to the +module is the same as with the basic :class:`Custom` examples. + + +.. rubric:: Footnotes + +.. [#] This is true when we know that the object is a basic type, like a string or a + float. + +.. [#] We relied on this in the :c:member:`~PyTypeObject.tp_dealloc` handler + in this example, because our type doesn't support garbage collection. + +.. [#] We now know that the first and last members are strings, so perhaps we + could be less careful about decrementing their reference counts, however, + we accept instances of string subclasses. Even though deallocating normal + strings won't call back into our objects, we can't guarantee that deallocating + an instance of a string subclass won't call back into our objects. + +.. [#] Also, even with our attributes restricted to strings instances, the user + could pass arbitrary :class:`str` subclasses and therefore still create + reference cycles. diff --git a/cpython_2/environment/repo/Doc/extending/windows.rst b/cpython_2/environment/repo/Doc/extending/windows.rst new file mode 100644 index 0000000000000000000000000000000000000000..c7b92c6ea24ca868df1317d0b113d65651b7a86c --- /dev/null +++ b/cpython_2/environment/repo/Doc/extending/windows.rst @@ -0,0 +1,137 @@ +.. highlight:: c + + +.. _building-on-windows: + +**************************************** +Building C and C++ Extensions on Windows +**************************************** + +This chapter briefly explains how to create a Windows extension module for +Python using Microsoft Visual C++, and follows with more detailed background +information on how it works. The explanatory material is useful for both the +Windows programmer learning to build Python extensions and the Unix programmer +interested in producing software which can be successfully built on both Unix +and Windows. + +Module authors are encouraged to use the distutils approach for building +extension modules, instead of the one described in this section. You will still +need the C compiler that was used to build Python; typically Microsoft Visual +C++. + +.. note:: + + This chapter mentions a number of filenames that include an encoded Python + version number. These filenames are represented with the version number shown + as ``XY``; in practice, ``'X'`` will be the major version number and ``'Y'`` + will be the minor version number of the Python release you're working with. For + example, if you are using Python 2.2.1, ``XY`` will actually be ``22``. + + +.. _win-cookbook: + +A Cookbook Approach +=================== + +There are two approaches to building extension modules on Windows, just as there +are on Unix: use the :mod:`distutils` package to control the build process, or +do things manually. The distutils approach works well for most extensions; +documentation on using :mod:`distutils` to build and package extension modules +is available in :ref:`distutils-index`. If you find you really need to do +things manually, it may be instructive to study the project file for the +:source:`winsound <PCbuild/winsound.vcxproj>` standard library module. + + +.. _dynamic-linking: + +Differences Between Unix and Windows +==================================== + +.. sectionauthor:: Chris Phoenix <cphoenix@best.com> + + +Unix and Windows use completely different paradigms for run-time loading of +code. Before you try to build a module that can be dynamically loaded, be aware +of how your system works. + +In Unix, a shared object (:file:`.so`) file contains code to be used by the +program, and also the names of functions and data that it expects to find in the +program. When the file is joined to the program, all references to those +functions and data in the file's code are changed to point to the actual +locations in the program where the functions and data are placed in memory. +This is basically a link operation. + +In Windows, a dynamic-link library (:file:`.dll`) file has no dangling +references. Instead, an access to functions or data goes through a lookup +table. So the DLL code does not have to be fixed up at runtime to refer to the +program's memory; instead, the code already uses the DLL's lookup table, and the +lookup table is modified at runtime to point to the functions and data. + +In Unix, there is only one type of library file (:file:`.a`) which contains code +from several object files (:file:`.o`). During the link step to create a shared +object file (:file:`.so`), the linker may find that it doesn't know where an +identifier is defined. The linker will look for it in the object files in the +libraries; if it finds it, it will include all the code from that object file. + +In Windows, there are two types of library, a static library and an import +library (both called :file:`.lib`). A static library is like a Unix :file:`.a` +file; it contains code to be included as necessary. An import library is +basically used only to reassure the linker that a certain identifier is legal, +and will be present in the program when the DLL is loaded. So the linker uses +the information from the import library to build the lookup table for using +identifiers that are not included in the DLL. When an application or a DLL is +linked, an import library may be generated, which will need to be used for all +future DLLs that depend on the symbols in the application or DLL. + +Suppose you are building two dynamic-load modules, B and C, which should share +another block of code A. On Unix, you would *not* pass :file:`A.a` to the +linker for :file:`B.so` and :file:`C.so`; that would cause it to be included +twice, so that B and C would each have their own copy. In Windows, building +:file:`A.dll` will also build :file:`A.lib`. You *do* pass :file:`A.lib` to the +linker for B and C. :file:`A.lib` does not contain code; it just contains +information which will be used at runtime to access A's code. + +In Windows, using an import library is sort of like using ``import spam``; it +gives you access to spam's names, but does not create a separate copy. On Unix, +linking with a library is more like ``from spam import *``; it does create a +separate copy. + + +.. _win-dlls: + +Using DLLs in Practice +====================== + +.. sectionauthor:: Chris Phoenix <cphoenix@best.com> + + +Windows Python is built in Microsoft Visual C++; using other compilers may or +may not work (though Borland seems to). The rest of this section is MSVC++ +specific. + +When creating DLLs in Windows, you must pass :file:`pythonXY.lib` to the linker. +To build two DLLs, spam and ni (which uses C functions found in spam), you could +use these commands:: + + cl /LD /I/python/include spam.c ../libs/pythonXY.lib + cl /LD /I/python/include ni.c spam.lib ../libs/pythonXY.lib + +The first command created three files: :file:`spam.obj`, :file:`spam.dll` and +:file:`spam.lib`. :file:`Spam.dll` does not contain any Python functions (such +as :c:func:`PyArg_ParseTuple`), but it does know how to find the Python code +thanks to :file:`pythonXY.lib`. + +The second command created :file:`ni.dll` (and :file:`.obj` and :file:`.lib`), +which knows how to find the necessary functions from spam, and also from the +Python executable. + +Not every identifier is exported to the lookup table. If you want any other +modules (including Python) to be able to see your identifiers, you have to say +``_declspec(dllexport)``, as in ``void _declspec(dllexport) initspam(void)`` or +``PyObject _declspec(dllexport) *NiGetSpamData(void)``. + +Developer Studio will throw in a lot of import libraries that you do not really +need, adding about 100K to your executable. To get rid of them, use the Project +Settings dialog, Link tab, to specify *ignore default libraries*. Add the +correct :file:`msvcrtxx.lib` to the list of libraries. + diff --git a/cpython_2/environment/repo/Doc/faq/design.rst b/cpython_2/environment/repo/Doc/faq/design.rst new file mode 100644 index 0000000000000000000000000000000000000000..4e3cc575ee196499c9b49889a6c79c4a553a658f --- /dev/null +++ b/cpython_2/environment/repo/Doc/faq/design.rst @@ -0,0 +1,761 @@ +====================== +Design and History FAQ +====================== + +.. only:: html + + .. contents:: + + +Why does Python use indentation for grouping of statements? +----------------------------------------------------------- + +Guido van Rossum believes that using indentation for grouping is extremely +elegant and contributes a lot to the clarity of the average Python program. +Most people learn to love this feature after a while. + +Since there are no begin/end brackets there cannot be a disagreement between +grouping perceived by the parser and the human reader. Occasionally C +programmers will encounter a fragment of code like this:: + + if (x <= y) + x++; + y--; + z++; + +Only the ``x++`` statement is executed if the condition is true, but the +indentation leads many to believe otherwise. Even experienced C programmers will +sometimes stare at it a long time wondering as to why ``y`` is being decremented even +for ``x > y``. + +Because there are no begin/end brackets, Python is much less prone to +coding-style conflicts. In C there are many different ways to place the braces. +After becoming used to reading and writing code using a particular style, +it is normal to feel somewhat uneasy when reading (or being required to write) +in a different one. + + +Many coding styles place begin/end brackets on a line by themselves. This makes +programs considerably longer and wastes valuable screen space, making it harder +to get a good overview of a program. Ideally, a function should fit on one +screen (say, 20--30 lines). 20 lines of Python can do a lot more work than 20 +lines of C. This is not solely due to the lack of begin/end brackets -- the +lack of declarations and the high-level data types are also responsible -- but +the indentation-based syntax certainly helps. + + +Why am I getting strange results with simple arithmetic operations? +------------------------------------------------------------------- + +See the next question. + + +Why are floating-point calculations so inaccurate? +-------------------------------------------------- + +Users are often surprised by results like this:: + + >>> 1.2 - 1.0 + 0.19999999999999996 + +and think it is a bug in Python. It's not. This has little to do with Python, +and much more to do with how the underlying platform handles floating-point +numbers. + +The :class:`float` type in CPython uses a C ``double`` for storage. A +:class:`float` object's value is stored in binary floating-point with a fixed +precision (typically 53 bits) and Python uses C operations, which in turn rely +on the hardware implementation in the processor, to perform floating-point +operations. This means that as far as floating-point operations are concerned, +Python behaves like many popular languages including C and Java. + +Many numbers that can be written easily in decimal notation cannot be expressed +exactly in binary floating-point. For example, after:: + + >>> x = 1.2 + +the value stored for ``x`` is a (very good) approximation to the decimal value +``1.2``, but is not exactly equal to it. On a typical machine, the actual +stored value is:: + + 1.0011001100110011001100110011001100110011001100110011 (binary) + +which is exactly:: + + 1.1999999999999999555910790149937383830547332763671875 (decimal) + +The typical precision of 53 bits provides Python floats with 15--16 +decimal digits of accuracy. + +For a fuller explanation, please see the :ref:`floating point arithmetic +<tut-fp-issues>` chapter in the Python tutorial. + + +Why are Python strings immutable? +--------------------------------- + +There are several advantages. + +One is performance: knowing that a string is immutable means we can allocate +space for it at creation time, and the storage requirements are fixed and +unchanging. This is also one of the reasons for the distinction between tuples +and lists. + +Another advantage is that strings in Python are considered as "elemental" as +numbers. No amount of activity will change the value 8 to anything else, and in +Python, no amount of activity will change the string "eight" to anything else. + + +.. _why-self: + +Why must 'self' be used explicitly in method definitions and calls? +------------------------------------------------------------------- + +The idea was borrowed from Modula-3. It turns out to be very useful, for a +variety of reasons. + +First, it's more obvious that you are using a method or instance attribute +instead of a local variable. Reading ``self.x`` or ``self.meth()`` makes it +absolutely clear that an instance variable or method is used even if you don't +know the class definition by heart. In C++, you can sort of tell by the lack of +a local variable declaration (assuming globals are rare or easily recognizable) +-- but in Python, there are no local variable declarations, so you'd have to +look up the class definition to be sure. Some C++ and Java coding standards +call for instance attributes to have an ``m_`` prefix, so this explicitness is +still useful in those languages, too. + +Second, it means that no special syntax is necessary if you want to explicitly +reference or call the method from a particular class. In C++, if you want to +use a method from a base class which is overridden in a derived class, you have +to use the ``::`` operator -- in Python you can write +``baseclass.methodname(self, <argument list>)``. This is particularly useful +for :meth:`__init__` methods, and in general in cases where a derived class +method wants to extend the base class method of the same name and thus has to +call the base class method somehow. + +Finally, for instance variables it solves a syntactic problem with assignment: +since local variables in Python are (by definition!) those variables to which a +value is assigned in a function body (and that aren't explicitly declared +global), there has to be some way to tell the interpreter that an assignment was +meant to assign to an instance variable instead of to a local variable, and it +should preferably be syntactic (for efficiency reasons). C++ does this through +declarations, but Python doesn't have declarations and it would be a pity having +to introduce them just for this purpose. Using the explicit ``self.var`` solves +this nicely. Similarly, for using instance variables, having to write +``self.var`` means that references to unqualified names inside a method don't +have to search the instance's directories. To put it another way, local +variables and instance variables live in two different namespaces, and you need +to tell Python which namespace to use. + + +.. _why-can-t-i-use-an-assignment-in-an-expression: + +Why can't I use an assignment in an expression? +----------------------------------------------- + +Starting in Python 3.8, you can! + +Assignment expressions using the walrus operator `:=` assign a variable in an +expression:: + + while chunk := fp.read(200): + print(chunk) + +See :pep:`572` for more information. + + + +Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))? +---------------------------------------------------------------------------------------------------------------- + +As Guido said: + + (a) For some operations, prefix notation just reads better than + postfix -- prefix (and infix!) operations have a long tradition in + mathematics which likes notations where the visuals help the + mathematician thinking about a problem. Compare the easy with which we + rewrite a formula like x*(a+b) into x*a + x*b to the clumsiness of + doing the same thing using a raw OO notation. + + (b) When I read code that says len(x) I *know* that it is asking for + the length of something. This tells me two things: the result is an + integer, and the argument is some kind of container. To the contrary, + when I read x.len(), I have to already know that x is some kind of + container implementing an interface or inheriting from a class that + has a standard len(). Witness the confusion we occasionally have when + a class that is not implementing a mapping has a get() or keys() + method, or something that isn't a file has a write() method. + + -- https://mail.python.org/pipermail/python-3000/2006-November/004643.html + + +Why is join() a string method instead of a list or tuple method? +---------------------------------------------------------------- + +Strings became much more like other standard types starting in Python 1.6, when +methods were added which give the same functionality that has always been +available using the functions of the string module. Most of these new methods +have been widely accepted, but the one which appears to make some programmers +feel uncomfortable is:: + + ", ".join(['1', '2', '4', '8', '16']) + +which gives the result:: + + "1, 2, 4, 8, 16" + +There are two common arguments against this usage. + +The first runs along the lines of: "It looks really ugly using a method of a +string literal (string constant)", to which the answer is that it might, but a +string literal is just a fixed value. If the methods are to be allowed on names +bound to strings there is no logical reason to make them unavailable on +literals. + +The second objection is typically cast as: "I am really telling a sequence to +join its members together with a string constant". Sadly, you aren't. For some +reason there seems to be much less difficulty with having :meth:`~str.split` as +a string method, since in that case it is easy to see that :: + + "1, 2, 4, 8, 16".split(", ") + +is an instruction to a string literal to return the substrings delimited by the +given separator (or, by default, arbitrary runs of white space). + +:meth:`~str.join` is a string method because in using it you are telling the +separator string to iterate over a sequence of strings and insert itself between +adjacent elements. This method can be used with any argument which obeys the +rules for sequence objects, including any new classes you might define yourself. +Similar methods exist for bytes and bytearray objects. + + +How fast are exceptions? +------------------------ + +A try/except block is extremely efficient if no exceptions are raised. Actually +catching an exception is expensive. In versions of Python prior to 2.0 it was +common to use this idiom:: + + try: + value = mydict[key] + except KeyError: + mydict[key] = getvalue(key) + value = mydict[key] + +This only made sense when you expected the dict to have the key almost all the +time. If that wasn't the case, you coded it like this:: + + if key in mydict: + value = mydict[key] + else: + value = mydict[key] = getvalue(key) + +For this specific case, you could also use ``value = dict.setdefault(key, +getvalue(key))``, but only if the ``getvalue()`` call is cheap enough because it +is evaluated in all cases. + + +Why isn't there a switch or case statement in Python? +----------------------------------------------------- + +You can do this easily enough with a sequence of ``if... elif... elif... else``. +There have been some proposals for switch statement syntax, but there is no +consensus (yet) on whether and how to do range tests. See :pep:`275` for +complete details and the current status. + +For cases where you need to choose from a very large number of possibilities, +you can create a dictionary mapping case values to functions to call. For +example:: + + def function_1(...): + ... + + functions = {'a': function_1, + 'b': function_2, + 'c': self.method_1, ...} + + func = functions[value] + func() + +For calling methods on objects, you can simplify yet further by using the +:func:`getattr` built-in to retrieve methods with a particular name:: + + def visit_a(self, ...): + ... + ... + + def dispatch(self, value): + method_name = 'visit_' + str(value) + method = getattr(self, method_name) + method() + +It's suggested that you use a prefix for the method names, such as ``visit_`` in +this example. Without such a prefix, if values are coming from an untrusted +source, an attacker would be able to call any method on your object. + + +Can't you emulate threads in the interpreter instead of relying on an OS-specific thread implementation? +-------------------------------------------------------------------------------------------------------- + +Answer 1: Unfortunately, the interpreter pushes at least one C stack frame for +each Python stack frame. Also, extensions can call back into Python at almost +random moments. Therefore, a complete threads implementation requires thread +support for C. + +Answer 2: Fortunately, there is `Stackless Python <https://github.com/stackless-dev/stackless/wiki>`_, +which has a completely redesigned interpreter loop that avoids the C stack. + + +Why can't lambda expressions contain statements? +------------------------------------------------ + +Python lambda expressions cannot contain statements because Python's syntactic +framework can't handle statements nested inside expressions. However, in +Python, this is not a serious problem. Unlike lambda forms in other languages, +where they add functionality, Python lambdas are only a shorthand notation if +you're too lazy to define a function. + +Functions are already first class objects in Python, and can be declared in a +local scope. Therefore the only advantage of using a lambda instead of a +locally-defined function is that you don't need to invent a name for the +function -- but that's just a local variable to which the function object (which +is exactly the same type of object that a lambda expression yields) is assigned! + + +Can Python be compiled to machine code, C or some other language? +----------------------------------------------------------------- + +`Cython <http://cython.org/>`_ compiles a modified version of Python with +optional annotations into C extensions. `Nuitka <http://www.nuitka.net/>`_ is +an up-and-coming compiler of Python into C++ code, aiming to support the full +Python language. For compiling to Java you can consider +`VOC <https://voc.readthedocs.io>`_. + + +How does Python manage memory? +------------------------------ + +The details of Python memory management depend on the implementation. The +standard implementation of Python, :term:`CPython`, uses reference counting to +detect inaccessible objects, and another mechanism to collect reference cycles, +periodically executing a cycle detection algorithm which looks for inaccessible +cycles and deletes the objects involved. The :mod:`gc` module provides functions +to perform a garbage collection, obtain debugging statistics, and tune the +collector's parameters. + +Other implementations (such as `Jython <http://www.jython.org>`_ or +`PyPy <http://www.pypy.org>`_), however, can rely on a different mechanism +such as a full-blown garbage collector. This difference can cause some +subtle porting problems if your Python code depends on the behavior of the +reference counting implementation. + +In some Python implementations, the following code (which is fine in CPython) +will probably run out of file descriptors:: + + for file in very_long_list_of_files: + f = open(file) + c = f.read(1) + +Indeed, using CPython's reference counting and destructor scheme, each new +assignment to *f* closes the previous file. With a traditional GC, however, +those file objects will only get collected (and closed) at varying and possibly +long intervals. + +If you want to write code that will work with any Python implementation, +you should explicitly close the file or use the :keyword:`with` statement; +this will work regardless of memory management scheme:: + + for file in very_long_list_of_files: + with open(file) as f: + c = f.read(1) + + +Why doesn't CPython use a more traditional garbage collection scheme? +--------------------------------------------------------------------- + +For one thing, this is not a C standard feature and hence it's not portable. +(Yes, we know about the Boehm GC library. It has bits of assembler code for +*most* common platforms, not for all of them, and although it is mostly +transparent, it isn't completely transparent; patches are required to get +Python to work with it.) + +Traditional GC also becomes a problem when Python is embedded into other +applications. While in a standalone Python it's fine to replace the standard +malloc() and free() with versions provided by the GC library, an application +embedding Python may want to have its *own* substitute for malloc() and free(), +and may not want Python's. Right now, CPython works with anything that +implements malloc() and free() properly. + + +Why isn't all memory freed when CPython exits? +---------------------------------------------- + +Objects referenced from the global namespaces of Python modules are not always +deallocated when Python exits. This may happen if there are circular +references. There are also certain bits of memory that are allocated by the C +library that are impossible to free (e.g. a tool like Purify will complain about +these). Python is, however, aggressive about cleaning up memory on exit and +does try to destroy every single object. + +If you want to force Python to delete certain things on deallocation use the +:mod:`atexit` module to run a function that will force those deletions. + + +Why are there separate tuple and list data types? +------------------------------------------------- + +Lists and tuples, while similar in many respects, are generally used in +fundamentally different ways. Tuples can be thought of as being similar to +Pascal records or C structs; they're small collections of related data which may +be of different types which are operated on as a group. For example, a +Cartesian coordinate is appropriately represented as a tuple of two or three +numbers. + +Lists, on the other hand, are more like arrays in other languages. They tend to +hold a varying number of objects all of which have the same type and which are +operated on one-by-one. For example, ``os.listdir('.')`` returns a list of +strings representing the files in the current directory. Functions which +operate on this output would generally not break if you added another file or +two to the directory. + +Tuples are immutable, meaning that once a tuple has been created, you can't +replace any of its elements with a new value. Lists are mutable, meaning that +you can always change a list's elements. Only immutable elements can be used as +dictionary keys, and hence only tuples and not lists can be used as keys. + + +How are lists implemented in CPython? +------------------------------------- + +CPython's lists are really variable-length arrays, not Lisp-style linked lists. +The implementation uses a contiguous array of references to other objects, and +keeps a pointer to this array and the array's length in a list head structure. + +This makes indexing a list ``a[i]`` an operation whose cost is independent of +the size of the list or the value of the index. + +When items are appended or inserted, the array of references is resized. Some +cleverness is applied to improve the performance of appending items repeatedly; +when the array must be grown, some extra space is allocated so the next few +times don't require an actual resize. + + +How are dictionaries implemented in CPython? +-------------------------------------------- + +CPython's dictionaries are implemented as resizable hash tables. Compared to +B-trees, this gives better performance for lookup (the most common operation by +far) under most circumstances, and the implementation is simpler. + +Dictionaries work by computing a hash code for each key stored in the dictionary +using the :func:`hash` built-in function. The hash code varies widely depending +on the key and a per-process seed; for example, "Python" could hash to +-539294296 while "python", a string that differs by a single bit, could hash +to 1142331976. The hash code is then used to calculate a location in an +internal array where the value will be stored. Assuming that you're storing +keys that all have different hash values, this means that dictionaries take +constant time -- O(1), in Big-O notation -- to retrieve a key. + + +Why must dictionary keys be immutable? +-------------------------------------- + +The hash table implementation of dictionaries uses a hash value calculated from +the key value to find the key. If the key were a mutable object, its value +could change, and thus its hash could also change. But since whoever changes +the key object can't tell that it was being used as a dictionary key, it can't +move the entry around in the dictionary. Then, when you try to look up the same +object in the dictionary it won't be found because its hash value is different. +If you tried to look up the old value it wouldn't be found either, because the +value of the object found in that hash bin would be different. + +If you want a dictionary indexed with a list, simply convert the list to a tuple +first; the function ``tuple(L)`` creates a tuple with the same entries as the +list ``L``. Tuples are immutable and can therefore be used as dictionary keys. + +Some unacceptable solutions that have been proposed: + +- Hash lists by their address (object ID). This doesn't work because if you + construct a new list with the same value it won't be found; e.g.:: + + mydict = {[1, 2]: '12'} + print(mydict[[1, 2]]) + + would raise a :exc:`KeyError` exception because the id of the ``[1, 2]`` used in the + second line differs from that in the first line. In other words, dictionary + keys should be compared using ``==``, not using :keyword:`is`. + +- Make a copy when using a list as a key. This doesn't work because the list, + being a mutable object, could contain a reference to itself, and then the + copying code would run into an infinite loop. + +- Allow lists as keys but tell the user not to modify them. This would allow a + class of hard-to-track bugs in programs when you forgot or modified a list by + accident. It also invalidates an important invariant of dictionaries: every + value in ``d.keys()`` is usable as a key of the dictionary. + +- Mark lists as read-only once they are used as a dictionary key. The problem + is that it's not just the top-level object that could change its value; you + could use a tuple containing a list as a key. Entering anything as a key into + a dictionary would require marking all objects reachable from there as + read-only -- and again, self-referential objects could cause an infinite loop. + +There is a trick to get around this if you need to, but use it at your own risk: +You can wrap a mutable structure inside a class instance which has both a +:meth:`__eq__` and a :meth:`__hash__` method. You must then make sure that the +hash value for all such wrapper objects that reside in a dictionary (or other +hash based structure), remain fixed while the object is in the dictionary (or +other structure). :: + + class ListWrapper: + def __init__(self, the_list): + self.the_list = the_list + + def __eq__(self, other): + return self.the_list == other.the_list + + def __hash__(self): + l = self.the_list + result = 98767 - len(l)*555 + for i, el in enumerate(l): + try: + result = result + (hash(el) % 9999999) * 1001 + i + except Exception: + result = (result % 7777777) + i * 333 + return result + +Note that the hash computation is complicated by the possibility that some +members of the list may be unhashable and also by the possibility of arithmetic +overflow. + +Furthermore it must always be the case that if ``o1 == o2`` (ie ``o1.__eq__(o2) +is True``) then ``hash(o1) == hash(o2)`` (ie, ``o1.__hash__() == o2.__hash__()``), +regardless of whether the object is in a dictionary or not. If you fail to meet +these restrictions dictionaries and other hash based structures will misbehave. + +In the case of ListWrapper, whenever the wrapper object is in a dictionary the +wrapped list must not change to avoid anomalies. Don't do this unless you are +prepared to think hard about the requirements and the consequences of not +meeting them correctly. Consider yourself warned. + + +Why doesn't list.sort() return the sorted list? +----------------------------------------------- + +In situations where performance matters, making a copy of the list just to sort +it would be wasteful. Therefore, :meth:`list.sort` sorts the list in place. In +order to remind you of that fact, it does not return the sorted list. This way, +you won't be fooled into accidentally overwriting a list when you need a sorted +copy but also need to keep the unsorted version around. + +If you want to return a new list, use the built-in :func:`sorted` function +instead. This function creates a new list from a provided iterable, sorts +it and returns it. For example, here's how to iterate over the keys of a +dictionary in sorted order:: + + for key in sorted(mydict): + ... # do whatever with mydict[key]... + + +How do you specify and enforce an interface spec in Python? +----------------------------------------------------------- + +An interface specification for a module as provided by languages such as C++ and +Java describes the prototypes for the methods and functions of the module. Many +feel that compile-time enforcement of interface specifications helps in the +construction of large programs. + +Python 2.6 adds an :mod:`abc` module that lets you define Abstract Base Classes +(ABCs). You can then use :func:`isinstance` and :func:`issubclass` to check +whether an instance or a class implements a particular ABC. The +:mod:`collections.abc` module defines a set of useful ABCs such as +:class:`~collections.abc.Iterable`, :class:`~collections.abc.Container`, and +:class:`~collections.abc.MutableMapping`. + +For Python, many of the advantages of interface specifications can be obtained +by an appropriate test discipline for components. There is also a tool, +PyChecker, which can be used to find problems due to subclassing. + +A good test suite for a module can both provide a regression test and serve as a +module interface specification and a set of examples. Many Python modules can +be run as a script to provide a simple "self test." Even modules which use +complex external interfaces can often be tested in isolation using trivial +"stub" emulations of the external interface. The :mod:`doctest` and +:mod:`unittest` modules or third-party test frameworks can be used to construct +exhaustive test suites that exercise every line of code in a module. + +An appropriate testing discipline can help build large complex applications in +Python as well as having interface specifications would. In fact, it can be +better because an interface specification cannot test certain properties of a +program. For example, the :meth:`append` method is expected to add new elements +to the end of some internal list; an interface specification cannot test that +your :meth:`append` implementation will actually do this correctly, but it's +trivial to check this property in a test suite. + +Writing test suites is very helpful, and you might want to design your code to +make it easily tested. One increasingly popular technique, test-driven +development, calls for writing parts of the test suite first, before you write +any of the actual code. Of course Python allows you to be sloppy and not write +test cases at all. + + +Why is there no goto? +--------------------- + +You can use exceptions to provide a "structured goto" that even works across +function calls. Many feel that exceptions can conveniently emulate all +reasonable uses of the "go" or "goto" constructs of C, Fortran, and other +languages. For example:: + + class label(Exception): pass # declare a label + + try: + ... + if condition: raise label() # goto label + ... + except label: # where to goto + pass + ... + +This doesn't allow you to jump into the middle of a loop, but that's usually +considered an abuse of goto anyway. Use sparingly. + + +Why can't raw strings (r-strings) end with a backslash? +------------------------------------------------------- + +More precisely, they can't end with an odd number of backslashes: the unpaired +backslash at the end escapes the closing quote character, leaving an +unterminated string. + +Raw strings were designed to ease creating input for processors (chiefly regular +expression engines) that want to do their own backslash escape processing. Such +processors consider an unmatched trailing backslash to be an error anyway, so +raw strings disallow that. In return, they allow you to pass on the string +quote character by escaping it with a backslash. These rules work well when +r-strings are used for their intended purpose. + +If you're trying to build Windows pathnames, note that all Windows system calls +accept forward slashes too:: + + f = open("/mydir/file.txt") # works fine! + +If you're trying to build a pathname for a DOS command, try e.g. one of :: + + dir = r"\this\is\my\dos\dir" "\\" + dir = r"\this\is\my\dos\dir\ "[:-1] + dir = "\\this\\is\\my\\dos\\dir\\" + + +Why doesn't Python have a "with" statement for attribute assignments? +--------------------------------------------------------------------- + +Python has a 'with' statement that wraps the execution of a block, calling code +on the entrance and exit from the block. Some languages have a construct that +looks like this:: + + with obj: + a = 1 # equivalent to obj.a = 1 + total = total + 1 # obj.total = obj.total + 1 + +In Python, such a construct would be ambiguous. + +Other languages, such as Object Pascal, Delphi, and C++, use static types, so +it's possible to know, in an unambiguous way, what member is being assigned +to. This is the main point of static typing -- the compiler *always* knows the +scope of every variable at compile time. + +Python uses dynamic types. It is impossible to know in advance which attribute +will be referenced at runtime. Member attributes may be added or removed from +objects on the fly. This makes it impossible to know, from a simple reading, +what attribute is being referenced: a local one, a global one, or a member +attribute? + +For instance, take the following incomplete snippet:: + + def foo(a): + with a: + print(x) + +The snippet assumes that "a" must have a member attribute called "x". However, +there is nothing in Python that tells the interpreter this. What should happen +if "a" is, let us say, an integer? If there is a global variable named "x", +will it be used inside the with block? As you see, the dynamic nature of Python +makes such choices much harder. + +The primary benefit of "with" and similar language features (reduction of code +volume) can, however, easily be achieved in Python by assignment. Instead of:: + + function(args).mydict[index][index].a = 21 + function(args).mydict[index][index].b = 42 + function(args).mydict[index][index].c = 63 + +write this:: + + ref = function(args).mydict[index][index] + ref.a = 21 + ref.b = 42 + ref.c = 63 + +This also has the side-effect of increasing execution speed because name +bindings are resolved at run-time in Python, and the second version only needs +to perform the resolution once. + + +Why are colons required for the if/while/def/class statements? +-------------------------------------------------------------- + +The colon is required primarily to enhance readability (one of the results of +the experimental ABC language). Consider this:: + + if a == b + print(a) + +versus :: + + if a == b: + print(a) + +Notice how the second one is slightly easier to read. Notice further how a +colon sets off the example in this FAQ answer; it's a standard usage in English. + +Another minor reason is that the colon makes it easier for editors with syntax +highlighting; they can look for colons to decide when indentation needs to be +increased instead of having to do a more elaborate parsing of the program text. + + +Why does Python allow commas at the end of lists and tuples? +------------------------------------------------------------ + +Python lets you add a trailing comma at the end of lists, tuples, and +dictionaries:: + + [1, 2, 3,] + ('a', 'b', 'c',) + d = { + "A": [1, 5], + "B": [6, 7], # last trailing comma is optional but good style + } + + +There are several reasons to allow this. + +When you have a literal value for a list, tuple, or dictionary spread across +multiple lines, it's easier to add more elements because you don't have to +remember to add a comma to the previous line. The lines can also be reordered +without creating a syntax error. + +Accidentally omitting the comma can lead to errors that are hard to diagnose. +For example:: + + x = [ + "fee", + "fie" + "foo", + "fum" + ] + +This list looks like it has four elements, but it actually contains three: +"fee", "fiefoo" and "fum". Always adding the comma avoids this source of error. + +Allowing the trailing comma may also make programmatic code generation easier. diff --git a/cpython_2/environment/repo/Doc/faq/extending.rst b/cpython_2/environment/repo/Doc/faq/extending.rst new file mode 100644 index 0000000000000000000000000000000000000000..aecb56eaa4fd2f3d4ee7a62db06c982ffd1b4412 --- /dev/null +++ b/cpython_2/environment/repo/Doc/faq/extending.rst @@ -0,0 +1,447 @@ +======================= +Extending/Embedding FAQ +======================= + +.. only:: html + + .. contents:: + +.. highlight:: c + + +.. XXX need review for Python 3. + + +Can I create my own functions in C? +----------------------------------- + +Yes, you can create built-in modules containing functions, variables, exceptions +and even new types in C. This is explained in the document +:ref:`extending-index`. + +Most intermediate or advanced Python books will also cover this topic. + + +Can I create my own functions in C++? +------------------------------------- + +Yes, using the C compatibility features found in C++. Place ``extern "C" { +... }`` around the Python include files and put ``extern "C"`` before each +function that is going to be called by the Python interpreter. Global or static +C++ objects with constructors are probably not a good idea. + + +.. _c-wrapper-software: + +Writing C is hard; are there any alternatives? +---------------------------------------------- + +There are a number of alternatives to writing your own C extensions, depending +on what you're trying to do. + +.. XXX make sure these all work + +`Cython <http://cython.org>`_ and its relative `Pyrex +<https://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/>`_ are compilers +that accept a slightly modified form of Python and generate the corresponding +C code. Cython and Pyrex make it possible to write an extension without having +to learn Python's C API. + +If you need to interface to some C or C++ library for which no Python extension +currently exists, you can try wrapping the library's data types and functions +with a tool such as `SWIG <http://www.swig.org>`_. `SIP +<https://riverbankcomputing.com/software/sip/intro>`__, `CXX +<http://cxx.sourceforge.net/>`_ `Boost +<http://www.boost.org/libs/python/doc/index.html>`_, or `Weave +<https://github.com/scipy/weave>`_ are also +alternatives for wrapping C++ libraries. + + +How can I execute arbitrary Python statements from C? +----------------------------------------------------- + +The highest-level function to do this is :c:func:`PyRun_SimpleString` which takes +a single string argument to be executed in the context of the module +``__main__`` and returns ``0`` for success and ``-1`` when an exception occurred +(including :exc:`SyntaxError`). If you want more control, use +:c:func:`PyRun_String`; see the source for :c:func:`PyRun_SimpleString` in +``Python/pythonrun.c``. + + +How can I evaluate an arbitrary Python expression from C? +--------------------------------------------------------- + +Call the function :c:func:`PyRun_String` from the previous question with the +start symbol :c:data:`Py_eval_input`; it parses an expression, evaluates it and +returns its value. + + +How do I extract C values from a Python object? +----------------------------------------------- + +That depends on the object's type. If it's a tuple, :c:func:`PyTuple_Size` +returns its length and :c:func:`PyTuple_GetItem` returns the item at a specified +index. Lists have similar functions, :c:func:`PyListSize` and +:c:func:`PyList_GetItem`. + +For bytes, :c:func:`PyBytes_Size` returns its length and +:c:func:`PyBytes_AsStringAndSize` provides a pointer to its value and its +length. Note that Python bytes objects may contain null bytes so C's +:c:func:`strlen` should not be used. + +To test the type of an object, first make sure it isn't ``NULL``, and then use +:c:func:`PyBytes_Check`, :c:func:`PyTuple_Check`, :c:func:`PyList_Check`, etc. + +There is also a high-level API to Python objects which is provided by the +so-called 'abstract' interface -- read ``Include/abstract.h`` for further +details. It allows interfacing with any kind of Python sequence using calls +like :c:func:`PySequence_Length`, :c:func:`PySequence_GetItem`, etc. as well +as many other useful protocols such as numbers (:c:func:`PyNumber_Index` et +al.) and mappings in the PyMapping APIs. + + +How do I use Py_BuildValue() to create a tuple of arbitrary length? +------------------------------------------------------------------- + +You can't. Use :c:func:`PyTuple_Pack` instead. + + +How do I call an object's method from C? +---------------------------------------- + +The :c:func:`PyObject_CallMethod` function can be used to call an arbitrary +method of an object. The parameters are the object, the name of the method to +call, a format string like that used with :c:func:`Py_BuildValue`, and the +argument values:: + + PyObject * + PyObject_CallMethod(PyObject *object, const char *method_name, + const char *arg_format, ...); + +This works for any object that has methods -- whether built-in or user-defined. +You are responsible for eventually :c:func:`Py_DECREF`\ 'ing the return value. + +To call, e.g., a file object's "seek" method with arguments 10, 0 (assuming the +file object pointer is "f"):: + + res = PyObject_CallMethod(f, "seek", "(ii)", 10, 0); + if (res == NULL) { + ... an exception occurred ... + } + else { + Py_DECREF(res); + } + +Note that since :c:func:`PyObject_CallObject` *always* wants a tuple for the +argument list, to call a function without arguments, pass "()" for the format, +and to call a function with one argument, surround the argument in parentheses, +e.g. "(i)". + + +How do I catch the output from PyErr_Print() (or anything that prints to stdout/stderr)? +---------------------------------------------------------------------------------------- + +In Python code, define an object that supports the ``write()`` method. Assign +this object to :data:`sys.stdout` and :data:`sys.stderr`. Call print_error, or +just allow the standard traceback mechanism to work. Then, the output will go +wherever your ``write()`` method sends it. + +The easiest way to do this is to use the :class:`io.StringIO` class: + +.. code-block:: pycon + + >>> import io, sys + >>> sys.stdout = io.StringIO() + >>> print('foo') + >>> print('hello world!') + >>> sys.stderr.write(sys.stdout.getvalue()) + foo + hello world! + +A custom object to do the same would look like this: + +.. code-block:: pycon + + >>> import io, sys + >>> class StdoutCatcher(io.TextIOBase): + ... def __init__(self): + ... self.data = [] + ... def write(self, stuff): + ... self.data.append(stuff) + ... + >>> import sys + >>> sys.stdout = StdoutCatcher() + >>> print('foo') + >>> print('hello world!') + >>> sys.stderr.write(''.join(sys.stdout.data)) + foo + hello world! + + +How do I access a module written in Python from C? +-------------------------------------------------- + +You can get a pointer to the module object as follows:: + + module = PyImport_ImportModule("<modulename>"); + +If the module hasn't been imported yet (i.e. it is not yet present in +:data:`sys.modules`), this initializes the module; otherwise it simply returns +the value of ``sys.modules["<modulename>"]``. Note that it doesn't enter the +module into any namespace -- it only ensures it has been initialized and is +stored in :data:`sys.modules`. + +You can then access the module's attributes (i.e. any name defined in the +module) as follows:: + + attr = PyObject_GetAttrString(module, "<attrname>"); + +Calling :c:func:`PyObject_SetAttrString` to assign to variables in the module +also works. + + +How do I interface to C++ objects from Python? +---------------------------------------------- + +Depending on your requirements, there are many approaches. To do this manually, +begin by reading :ref:`the "Extending and Embedding" document +<extending-index>`. Realize that for the Python run-time system, there isn't a +whole lot of difference between C and C++ -- so the strategy of building a new +Python type around a C structure (pointer) type will also work for C++ objects. + +For C++ libraries, see :ref:`c-wrapper-software`. + + +I added a module using the Setup file and the make fails; why? +-------------------------------------------------------------- + +Setup must end in a newline, if there is no newline there, the build process +fails. (Fixing this requires some ugly shell script hackery, and this bug is so +minor that it doesn't seem worth the effort.) + + +How do I debug an extension? +---------------------------- + +When using GDB with dynamically loaded extensions, you can't set a breakpoint in +your extension until your extension is loaded. + +In your ``.gdbinit`` file (or interactively), add the command: + +.. code-block:: none + + br _PyImport_LoadDynamicModule + +Then, when you run GDB: + +.. code-block:: shell-session + + $ gdb /local/bin/python + gdb) run myscript.py + gdb) continue # repeat until your extension is loaded + gdb) finish # so that your extension is loaded + gdb) br myfunction.c:50 + gdb) continue + +I want to compile a Python module on my Linux system, but some files are missing. Why? +-------------------------------------------------------------------------------------- + +Most packaged versions of Python don't include the +:file:`/usr/lib/python2.{x}/config/` directory, which contains various files +required for compiling Python extensions. + +For Red Hat, install the python-devel RPM to get the necessary files. + +For Debian, run ``apt-get install python-dev``. + + +How do I tell "incomplete input" from "invalid input"? +------------------------------------------------------ + +Sometimes you want to emulate the Python interactive interpreter's behavior, +where it gives you a continuation prompt when the input is incomplete (e.g. you +typed the start of an "if" statement or you didn't close your parentheses or +triple string quotes), but it gives you a syntax error message immediately when +the input is invalid. + +In Python you can use the :mod:`codeop` module, which approximates the parser's +behavior sufficiently. IDLE uses this, for example. + +The easiest way to do it in C is to call :c:func:`PyRun_InteractiveLoop` (perhaps +in a separate thread) and let the Python interpreter handle the input for +you. You can also set the :c:func:`PyOS_ReadlineFunctionPointer` to point at your +custom input function. See ``Modules/readline.c`` and ``Parser/myreadline.c`` +for more hints. + +However sometimes you have to run the embedded Python interpreter in the same +thread as your rest application and you can't allow the +:c:func:`PyRun_InteractiveLoop` to stop while waiting for user input. The one +solution then is to call :c:func:`PyParser_ParseString` and test for ``e.error`` +equal to ``E_EOF``, which means the input is incomplete. Here's a sample code +fragment, untested, inspired by code from Alex Farber:: + + #define PY_SSIZE_T_CLEAN + #include <Python.h> + #include <node.h> + #include <errcode.h> + #include <grammar.h> + #include <parsetok.h> + #include <compile.h> + + int testcomplete(char *code) + /* code should end in \n */ + /* return -1 for error, 0 for incomplete, 1 for complete */ + { + node *n; + perrdetail e; + + n = PyParser_ParseString(code, &_PyParser_Grammar, + Py_file_input, &e); + if (n == NULL) { + if (e.error == E_EOF) + return 0; + return -1; + } + + PyNode_Free(n); + return 1; + } + +Another solution is trying to compile the received string with +:c:func:`Py_CompileString`. If it compiles without errors, try to execute the +returned code object by calling :c:func:`PyEval_EvalCode`. Otherwise save the +input for later. If the compilation fails, find out if it's an error or just +more input is required - by extracting the message string from the exception +tuple and comparing it to the string "unexpected EOF while parsing". Here is a +complete example using the GNU readline library (you may want to ignore +**SIGINT** while calling readline()):: + + #include <stdio.h> + #include <readline.h> + + #define PY_SSIZE_T_CLEAN + #include <Python.h> + #include <object.h> + #include <compile.h> + #include <eval.h> + + int main (int argc, char* argv[]) + { + int i, j, done = 0; /* lengths of line, code */ + char ps1[] = ">>> "; + char ps2[] = "... "; + char *prompt = ps1; + char *msg, *line, *code = NULL; + PyObject *src, *glb, *loc; + PyObject *exc, *val, *trb, *obj, *dum; + + Py_Initialize (); + loc = PyDict_New (); + glb = PyDict_New (); + PyDict_SetItemString (glb, "__builtins__", PyEval_GetBuiltins ()); + + while (!done) + { + line = readline (prompt); + + if (NULL == line) /* Ctrl-D pressed */ + { + done = 1; + } + else + { + i = strlen (line); + + if (i > 0) + add_history (line); /* save non-empty lines */ + + if (NULL == code) /* nothing in code yet */ + j = 0; + else + j = strlen (code); + + code = realloc (code, i + j + 2); + if (NULL == code) /* out of memory */ + exit (1); + + if (0 == j) /* code was empty, so */ + code[0] = '\0'; /* keep strncat happy */ + + strncat (code, line, i); /* append line to code */ + code[i + j] = '\n'; /* append '\n' to code */ + code[i + j + 1] = '\0'; + + src = Py_CompileString (code, "<stdin>", Py_single_input); + + if (NULL != src) /* compiled just fine - */ + { + if (ps1 == prompt || /* ">>> " or */ + '\n' == code[i + j - 1]) /* "... " and double '\n' */ + { /* so execute it */ + dum = PyEval_EvalCode (src, glb, loc); + Py_XDECREF (dum); + Py_XDECREF (src); + free (code); + code = NULL; + if (PyErr_Occurred ()) + PyErr_Print (); + prompt = ps1; + } + } /* syntax error or E_EOF? */ + else if (PyErr_ExceptionMatches (PyExc_SyntaxError)) + { + PyErr_Fetch (&exc, &val, &trb); /* clears exception! */ + + if (PyArg_ParseTuple (val, "sO", &msg, &obj) && + !strcmp (msg, "unexpected EOF while parsing")) /* E_EOF */ + { + Py_XDECREF (exc); + Py_XDECREF (val); + Py_XDECREF (trb); + prompt = ps2; + } + else /* some other syntax error */ + { + PyErr_Restore (exc, val, trb); + PyErr_Print (); + free (code); + code = NULL; + prompt = ps1; + } + } + else /* some non-syntax error */ + { + PyErr_Print (); + free (code); + code = NULL; + prompt = ps1; + } + + free (line); + } + } + + Py_XDECREF(glb); + Py_XDECREF(loc); + Py_Finalize(); + exit(0); + } + + +How do I find undefined g++ symbols __builtin_new or __pure_virtual? +-------------------------------------------------------------------- + +To dynamically load g++ extension modules, you must recompile Python, relink it +using g++ (change LINKCC in the Python Modules Makefile), and link your +extension module using g++ (e.g., ``g++ -shared -o mymodule.so mymodule.o``). + + +Can I create an object class with some methods implemented in C and others in Python (e.g. through inheritance)? +---------------------------------------------------------------------------------------------------------------- + +Yes, you can inherit from built-in classes such as :class:`int`, :class:`list`, +:class:`dict`, etc. + +The Boost Python Library (BPL, http://www.boost.org/libs/python/doc/index.html) +provides a way of doing this from C++ (i.e. you can inherit from an extension +class written in C++ using the BPL). diff --git a/cpython_2/environment/repo/Doc/faq/general.rst b/cpython_2/environment/repo/Doc/faq/general.rst new file mode 100644 index 0000000000000000000000000000000000000000..3ef553e8acb43cb85a52d19c8df92af9e3948ec0 --- /dev/null +++ b/cpython_2/environment/repo/Doc/faq/general.rst @@ -0,0 +1,446 @@ +:tocdepth: 2 + +================== +General Python FAQ +================== + +.. only:: html + + .. contents:: + + +General Information +=================== + +What is Python? +--------------- + +Python is an interpreted, interactive, object-oriented programming language. It +incorporates modules, exceptions, dynamic typing, very high level dynamic data +types, and classes. Python combines remarkable power with very clear syntax. +It has interfaces to many system calls and libraries, as well as to various +window systems, and is extensible in C or C++. It is also usable as an +extension language for applications that need a programmable interface. +Finally, Python is portable: it runs on many Unix variants, on the Mac, and on +Windows 2000 and later. + +To find out more, start with :ref:`tutorial-index`. The `Beginner's Guide to +Python <https://wiki.python.org/moin/BeginnersGuide>`_ links to other +introductory tutorials and resources for learning Python. + + +What is the Python Software Foundation? +--------------------------------------- + +The Python Software Foundation is an independent non-profit organization that +holds the copyright on Python versions 2.1 and newer. The PSF's mission is to +advance open source technology related to the Python programming language and to +publicize the use of Python. The PSF's home page is at +https://www.python.org/psf/. + +Donations to the PSF are tax-exempt in the US. If you use Python and find it +helpful, please contribute via `the PSF donation page +<https://www.python.org/psf/donations/>`_. + + +Are there copyright restrictions on the use of Python? +------------------------------------------------------ + +You can do anything you want with the source, as long as you leave the +copyrights in and display those copyrights in any documentation about Python +that you produce. If you honor the copyright rules, it's OK to use Python for +commercial use, to sell copies of Python in source or binary form (modified or +unmodified), or to sell products that incorporate Python in some form. We would +still like to know about all commercial use of Python, of course. + +See `the PSF license page <https://www.python.org/psf/license/>`_ to find further +explanations and a link to the full text of the license. + +The Python logo is trademarked, and in certain cases permission is required to +use it. Consult `the Trademark Usage Policy +<https://www.python.org/psf/trademarks/>`__ for more information. + + +Why was Python created in the first place? +------------------------------------------ + +Here's a *very* brief summary of what started it all, written by Guido van +Rossum: + + I had extensive experience with implementing an interpreted language in the + ABC group at CWI, and from working with this group I had learned a lot about + language design. This is the origin of many Python features, including the + use of indentation for statement grouping and the inclusion of + very-high-level data types (although the details are all different in + Python). + + I had a number of gripes about the ABC language, but also liked many of its + features. It was impossible to extend the ABC language (or its + implementation) to remedy my complaints -- in fact its lack of extensibility + was one of its biggest problems. I had some experience with using Modula-2+ + and talked with the designers of Modula-3 and read the Modula-3 report. + Modula-3 is the origin of the syntax and semantics used for exceptions, and + some other Python features. + + I was working in the Amoeba distributed operating system group at CWI. We + needed a better way to do system administration than by writing either C + programs or Bourne shell scripts, since Amoeba had its own system call + interface which wasn't easily accessible from the Bourne shell. My + experience with error handling in Amoeba made me acutely aware of the + importance of exceptions as a programming language feature. + + It occurred to me that a scripting language with a syntax like ABC but with + access to the Amoeba system calls would fill the need. I realized that it + would be foolish to write an Amoeba-specific language, so I decided that I + needed a language that was generally extensible. + + During the 1989 Christmas holidays, I had a lot of time on my hand, so I + decided to give it a try. During the next year, while still mostly working + on it in my own time, Python was used in the Amoeba project with increasing + success, and the feedback from colleagues made me add many early + improvements. + + In February 1991, after just over a year of development, I decided to post to + USENET. The rest is in the ``Misc/HISTORY`` file. + + +What is Python good for? +------------------------ + +Python is a high-level general-purpose programming language that can be applied +to many different classes of problems. + +The language comes with a large standard library that covers areas such as +string processing (regular expressions, Unicode, calculating differences between +files), Internet protocols (HTTP, FTP, SMTP, XML-RPC, POP, IMAP, CGI +programming), software engineering (unit testing, logging, profiling, parsing +Python code), and operating system interfaces (system calls, filesystems, TCP/IP +sockets). Look at the table of contents for :ref:`library-index` to get an idea +of what's available. A wide variety of third-party extensions are also +available. Consult `the Python Package Index <https://pypi.org>`_ to +find packages of interest to you. + + +How does the Python version numbering scheme work? +-------------------------------------------------- + +Python versions are numbered A.B.C or A.B. A is the major version number -- it +is only incremented for really major changes in the language. B is the minor +version number, incremented for less earth-shattering changes. C is the +micro-level -- it is incremented for each bugfix release. See :pep:`6` for more +information about bugfix releases. + +Not all releases are bugfix releases. In the run-up to a new major release, a +series of development releases are made, denoted as alpha, beta, or release +candidate. Alphas are early releases in which interfaces aren't yet finalized; +it's not unexpected to see an interface change between two alpha releases. +Betas are more stable, preserving existing interfaces but possibly adding new +modules, and release candidates are frozen, making no changes except as needed +to fix critical bugs. + +Alpha, beta and release candidate versions have an additional suffix. The +suffix for an alpha version is "aN" for some small number N, the suffix for a +beta version is "bN" for some small number N, and the suffix for a release +candidate version is "cN" for some small number N. In other words, all versions +labeled 2.0aN precede the versions labeled 2.0bN, which precede versions labeled +2.0cN, and *those* precede 2.0. + +You may also find version numbers with a "+" suffix, e.g. "2.2+". These are +unreleased versions, built directly from the CPython development repository. In +practice, after a final minor release is made, the version is incremented to the +next minor version, which becomes the "a0" version, e.g. "2.4a0". + +See also the documentation for :data:`sys.version`, :data:`sys.hexversion`, and +:data:`sys.version_info`. + + +How do I obtain a copy of the Python source? +-------------------------------------------- + +The latest Python source distribution is always available from python.org, at +https://www.python.org/downloads/. The latest development sources can be obtained +at https://github.com/python/cpython/. + +The source distribution is a gzipped tar file containing the complete C source, +Sphinx-formatted documentation, Python library modules, example programs, and +several useful pieces of freely distributable software. The source will compile +and run out of the box on most UNIX platforms. + +Consult the `Getting Started section of the Python Developer's Guide +<https://devguide.python.org/setup/>`__ for more +information on getting the source code and compiling it. + + +How do I get documentation on Python? +------------------------------------- + +.. XXX mention py3k + +The standard documentation for the current stable version of Python is available +at https://docs.python.org/3/. PDF, plain text, and downloadable HTML versions are +also available at https://docs.python.org/3/download.html. + +The documentation is written in reStructuredText and processed by `the Sphinx +documentation tool <http://sphinx-doc.org/>`__. The reStructuredText source for +the documentation is part of the Python source distribution. + + +I've never programmed before. Is there a Python tutorial? +--------------------------------------------------------- + +There are numerous tutorials and books available. The standard documentation +includes :ref:`tutorial-index`. + +Consult `the Beginner's Guide <https://wiki.python.org/moin/BeginnersGuide>`_ to +find information for beginning Python programmers, including lists of tutorials. + + +Is there a newsgroup or mailing list devoted to Python? +------------------------------------------------------- + +There is a newsgroup, :newsgroup:`comp.lang.python`, and a mailing list, +`python-list <https://mail.python.org/mailman/listinfo/python-list>`_. The +newsgroup and mailing list are gatewayed into each other -- if you can read news +it's unnecessary to subscribe to the mailing list. +:newsgroup:`comp.lang.python` is high-traffic, receiving hundreds of postings +every day, and Usenet readers are often more able to cope with this volume. + +Announcements of new software releases and events can be found in +comp.lang.python.announce, a low-traffic moderated list that receives about five +postings per day. It's available as `the python-announce mailing list +<https://mail.python.org/mailman/listinfo/python-announce-list>`_. + +More info about other mailing lists and newsgroups +can be found at https://www.python.org/community/lists/. + + +How do I get a beta test version of Python? +------------------------------------------- + +Alpha and beta releases are available from https://www.python.org/downloads/. All +releases are announced on the comp.lang.python and comp.lang.python.announce +newsgroups and on the Python home page at https://www.python.org/; an RSS feed of +news is available. + +You can also access the development version of Python through Git. See +`The Python Developer's Guide <https://devguide.python.org/>`_ for details. + + +How do I submit bug reports and patches for Python? +--------------------------------------------------- + +To report a bug or submit a patch, please use the Roundup installation at +https://bugs.python.org/. + +You must have a Roundup account to report bugs; this makes it possible for us to +contact you if we have follow-up questions. It will also enable Roundup to send +you updates as we act on your bug. If you had previously used SourceForge to +report bugs to Python, you can obtain your Roundup password through Roundup's +`password reset procedure <https://bugs.python.org/user?@template=forgotten>`_. + +For more information on how Python is developed, consult `the Python Developer's +Guide <https://devguide.python.org/>`_. + + +Are there any published articles about Python that I can reference? +------------------------------------------------------------------- + +It's probably best to cite your favorite book about Python. + +The very first article about Python was written in 1991 and is now quite +outdated. + + Guido van Rossum and Jelke de Boer, "Interactively Testing Remote Servers + Using the Python Programming Language", CWI Quarterly, Volume 4, Issue 4 + (December 1991), Amsterdam, pp 283--303. + + +Are there any books on Python? +------------------------------ + +Yes, there are many, and more are being published. See the python.org wiki at +https://wiki.python.org/moin/PythonBooks for a list. + +You can also search online bookstores for "Python" and filter out the Monty +Python references; or perhaps search for "Python" and "language". + + +Where in the world is www.python.org located? +--------------------------------------------- + +The Python project's infrastructure is located all over the world and is managed +by the Python Infrastructure Team. Details `here <http://infra.psf.io>`__. + + +Why is it called Python? +------------------------ + +When he began implementing Python, Guido van Rossum was also reading the +published scripts from `"Monty Python's Flying Circus" +<https://en.wikipedia.org/wiki/Monty_Python>`__, a BBC comedy series from the 1970s. Van Rossum +thought he needed a name that was short, unique, and slightly mysterious, so he +decided to call the language Python. + + +Do I have to like "Monty Python's Flying Circus"? +------------------------------------------------- + +No, but it helps. :) + + +Python in the real world +======================== + +How stable is Python? +--------------------- + +Very stable. New, stable releases have been coming out roughly every 6 to 18 +months since 1991, and this seems likely to continue. Currently there are +usually around 18 months between major releases. + +The developers issue "bugfix" releases of older versions, so the stability of +existing releases gradually improves. Bugfix releases, indicated by a third +component of the version number (e.g. 3.5.3, 3.6.2), are managed for stability; +only fixes for known problems are included in a bugfix release, and it's +guaranteed that interfaces will remain the same throughout a series of bugfix +releases. + +The latest stable releases can always be found on the `Python download page +<https://www.python.org/downloads/>`_. There are two production-ready versions +of Python: 2.x and 3.x. The recommended version is 3.x, which is supported by +most widely used libraries. Although 2.x is still widely used, `it will not +be maintained after January 1, 2020 <https://www.python.org/dev/peps/pep-0373/>`_. + +How many people are using Python? +--------------------------------- + +There are probably tens of thousands of users, though it's difficult to obtain +an exact count. + +Python is available for free download, so there are no sales figures, and it's +available from many different sites and packaged with many Linux distributions, +so download statistics don't tell the whole story either. + +The comp.lang.python newsgroup is very active, but not all Python users post to +the group or even read it. + + +Have any significant projects been done in Python? +-------------------------------------------------- + +See https://www.python.org/about/success for a list of projects that use Python. +Consulting the proceedings for `past Python conferences +<https://www.python.org/community/workshops/>`_ will reveal contributions from many +different companies and organizations. + +High-profile Python projects include `the Mailman mailing list manager +<http://www.list.org>`_ and `the Zope application server +<http://www.zope.org>`_. Several Linux distributions, most notably `Red Hat +<https://www.redhat.com>`_, have written part or all of their installer and +system administration software in Python. Companies that use Python internally +include Google, Yahoo, and Lucasfilm Ltd. + + +What new developments are expected for Python in the future? +------------------------------------------------------------ + +See https://www.python.org/dev/peps/ for the Python Enhancement Proposals +(PEPs). PEPs are design documents describing a suggested new feature for Python, +providing a concise technical specification and a rationale. Look for a PEP +titled "Python X.Y Release Schedule", where X.Y is a version that hasn't been +publicly released yet. + +New development is discussed on `the python-dev mailing list +<https://mail.python.org/mailman/listinfo/python-dev/>`_. + + +Is it reasonable to propose incompatible changes to Python? +----------------------------------------------------------- + +In general, no. There are already millions of lines of Python code around the +world, so any change in the language that invalidates more than a very small +fraction of existing programs has to be frowned upon. Even if you can provide a +conversion program, there's still the problem of updating all documentation; +many books have been written about Python, and we don't want to invalidate them +all at a single stroke. + +Providing a gradual upgrade path is necessary if a feature has to be changed. +:pep:`5` describes the procedure followed for introducing backward-incompatible +changes while minimizing disruption for users. + + +Is Python a good language for beginning programmers? +---------------------------------------------------- + +Yes. + +It is still common to start students with a procedural and statically typed +language such as Pascal, C, or a subset of C++ or Java. Students may be better +served by learning Python as their first language. Python has a very simple and +consistent syntax and a large standard library and, most importantly, using +Python in a beginning programming course lets students concentrate on important +programming skills such as problem decomposition and data type design. With +Python, students can be quickly introduced to basic concepts such as loops and +procedures. They can probably even work with user-defined objects in their very +first course. + +For a student who has never programmed before, using a statically typed language +seems unnatural. It presents additional complexity that the student must master +and slows the pace of the course. The students are trying to learn to think +like a computer, decompose problems, design consistent interfaces, and +encapsulate data. While learning to use a statically typed language is +important in the long term, it is not necessarily the best topic to address in +the students' first programming course. + +Many other aspects of Python make it a good first language. Like Java, Python +has a large standard library so that students can be assigned programming +projects very early in the course that *do* something. Assignments aren't +restricted to the standard four-function calculator and check balancing +programs. By using the standard library, students can gain the satisfaction of +working on realistic applications as they learn the fundamentals of programming. +Using the standard library also teaches students about code reuse. Third-party +modules such as PyGame are also helpful in extending the students' reach. + +Python's interactive interpreter enables students to test language features +while they're programming. They can keep a window with the interpreter running +while they enter their program's source in another window. If they can't +remember the methods for a list, they can do something like this:: + + >>> L = [] + >>> dir(L) # doctest: +NORMALIZE_WHITESPACE + ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', + '__dir__', '__doc__', '__eq__', '__format__', '__ge__', + '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', + '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', + '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', + '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', + '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', + 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', + 'reverse', 'sort'] + >>> [d for d in dir(L) if '__' not in d] + ['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] + + >>> help(L.append) + Help on built-in function append: + <BLANKLINE> + append(...) + L.append(object) -> None -- append object to end + <BLANKLINE> + >>> L.append(1) + >>> L + [1] + +With the interpreter, documentation is never far from the student as they are +programming. + +There are also good IDEs for Python. IDLE is a cross-platform IDE for Python +that is written in Python using Tkinter. PythonWin is a Windows-specific IDE. +Emacs users will be happy to know that there is a very good Python mode for +Emacs. All of these programming environments provide syntax highlighting, +auto-indenting, and access to the interactive interpreter while coding. Consult +`the Python wiki <https://wiki.python.org/moin/PythonEditors>`_ for a full list +of Python editing environments. + +If you want to discuss Python's use in education, you may be interested in +joining `the edu-sig mailing list +<https://www.python.org/community/sigs/current/edu-sig>`_. diff --git a/cpython_2/environment/repo/Doc/faq/gui.rst b/cpython_2/environment/repo/Doc/faq/gui.rst new file mode 100644 index 0000000000000000000000000000000000000000..781da467d1801308a67831356e7a59b1cdefdaf4 --- /dev/null +++ b/cpython_2/environment/repo/Doc/faq/gui.rst @@ -0,0 +1,159 @@ +:tocdepth: 2 + +========================== +Graphic User Interface FAQ +========================== + +.. only:: html + + .. contents:: + +.. XXX need review for Python 3. + + +General GUI Questions +===================== + +What platform-independent GUI toolkits exist for Python? +======================================================== + +Depending on what platform(s) you are aiming at, there are several. Some +of them haven't been ported to Python 3 yet. At least `Tkinter`_ and `Qt`_ +are known to be Python 3-compatible. + +.. XXX check links + +Tkinter +------- + +Standard builds of Python include an object-oriented interface to the Tcl/Tk +widget set, called :ref:`tkinter <Tkinter>`. This is probably the easiest to +install (since it comes included with most +`binary distributions <https://www.python.org/downloads/>`_ of Python) and use. +For more info about Tk, including pointers to the source, see the +`Tcl/Tk home page <https://www.tcl.tk>`_. Tcl/Tk is fully portable to the +Mac OS X, Windows, and Unix platforms. + +wxWidgets +--------- + +wxWidgets (https://www.wxwidgets.org) is a free, portable GUI class +library written in C++ that provides a native look and feel on a +number of platforms, with Windows, Mac OS X, GTK, X11, all listed as +current stable targets. Language bindings are available for a number +of languages including Python, Perl, Ruby, etc. + +`wxPython <https://www.wxpython.org>`_ is the Python binding for +wxwidgets. While it often lags slightly behind the official wxWidgets +releases, it also offers a number of features via pure Python +extensions that are not available in other language bindings. There +is an active wxPython user and developer community. + +Both wxWidgets and wxPython are free, open source, software with +permissive licences that allow their use in commercial products as +well as in freeware or shareware. + + +Qt +--- + +There are bindings available for the Qt toolkit (using either `PyQt +<https://riverbankcomputing.com/software/pyqt/intro>`_ or `PySide +<https://wiki.qt.io/PySide>`_) and for KDE (`PyKDE4 <https://techbase.kde.org/Languages/Python/Using_PyKDE_4>`__). +PyQt is currently more mature than PySide, but you must buy a PyQt license from +`Riverbank Computing <https://www.riverbankcomputing.com/commercial/license-faq>`_ +if you want to write proprietary applications. PySide is free for all applications. + +Qt 4.5 upwards is licensed under the LGPL license; also, commercial licenses +are available from `The Qt Company <https://www.qt.io/licensing/>`_. + +Gtk+ +---- + +The `GObject introspection bindings <https://wiki.gnome.org/Projects/PyGObject>`_ +for Python allow you to write GTK+ 3 applications. There is also a +`Python GTK+ 3 Tutorial <https://python-gtk-3-tutorial.readthedocs.io>`_. + +The older PyGtk bindings for the `Gtk+ 2 toolkit <https://www.gtk.org>`_ have +been implemented by James Henstridge; see <http://www.pygtk.org>. + +Kivy +---- + +`Kivy <https://kivy.org/>`_ is a cross-platform GUI library supporting both +desktop operating systems (Windows, macOS, Linux) and mobile devices (Android, +iOS). It is written in Python and Cython, and can use a range of windowing +backends. + +Kivy is free and open source software distributed under the MIT license. + +FLTK +---- + +Python bindings for `the FLTK toolkit <http://www.fltk.org>`_, a simple yet +powerful and mature cross-platform windowing system, are available from `the +PyFLTK project <http://pyfltk.sourceforge.net>`_. + +OpenGL +------ + +For OpenGL bindings, see `PyOpenGL <http://pyopengl.sourceforge.net>`_. + + +What platform-specific GUI toolkits exist for Python? +======================================================== + +By installing the `PyObjc Objective-C bridge +<https://pypi.org/project/pyobjc/>`_, Python programs can use Mac OS X's +Cocoa libraries. + +:ref:`Pythonwin <windows-faq>` by Mark Hammond includes an interface to the +Microsoft Foundation Classes and a Python programming environment +that's written mostly in Python using the MFC classes. + + +Tkinter questions +================= + +How do I freeze Tkinter applications? +------------------------------------- + +Freeze is a tool to create stand-alone applications. When freezing Tkinter +applications, the applications will not be truly stand-alone, as the application +will still need the Tcl and Tk libraries. + +One solution is to ship the application with the Tcl and Tk libraries, and point +to them at run-time using the :envvar:`TCL_LIBRARY` and :envvar:`TK_LIBRARY` +environment variables. + +To get truly stand-alone applications, the Tcl scripts that form the library +have to be integrated into the application as well. One tool supporting that is +SAM (stand-alone modules), which is part of the Tix distribution +(http://tix.sourceforge.net/). + +Build Tix with SAM enabled, perform the appropriate call to +:c:func:`Tclsam_init`, etc. inside Python's +:file:`Modules/tkappinit.c`, and link with libtclsam and libtksam (you +might include the Tix libraries as well). + + +Can I have Tk events handled while waiting for I/O? +--------------------------------------------------- + +On platforms other than Windows, yes, and you don't even +need threads! But you'll have to restructure your I/O +code a bit. Tk has the equivalent of Xt's :c:func:`XtAddInput()` call, which allows you +to register a callback function which will be called from the Tk mainloop when +I/O is possible on a file descriptor. See :ref:`tkinter-file-handlers`. + + +I can't get key bindings to work in Tkinter: why? +------------------------------------------------- + +An often-heard complaint is that event handlers bound to events with the +:meth:`bind` method don't get handled even when the appropriate key is pressed. + +The most common cause is that the widget to which the binding applies doesn't +have "keyboard focus". Check out the Tk documentation for the focus command. +Usually a widget is given the keyboard focus by clicking in it (but not for +labels; see the takefocus option). diff --git a/cpython_2/environment/repo/Doc/faq/index.rst b/cpython_2/environment/repo/Doc/faq/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..46ed3db2203d3a4f8b071281d058723336f2645c --- /dev/null +++ b/cpython_2/environment/repo/Doc/faq/index.rst @@ -0,0 +1,17 @@ +.. _faq-index: + +################################### + Python Frequently Asked Questions +################################### + +.. toctree:: + :maxdepth: 1 + + general.rst + programming.rst + design.rst + library.rst + extending.rst + windows.rst + gui.rst + installed.rst diff --git a/cpython_2/environment/repo/Doc/faq/installed.rst b/cpython_2/environment/repo/Doc/faq/installed.rst new file mode 100644 index 0000000000000000000000000000000000000000..42296533e26f3202fa696eab1b805e73a3d385bb --- /dev/null +++ b/cpython_2/environment/repo/Doc/faq/installed.rst @@ -0,0 +1,53 @@ +============================================= +"Why is Python Installed on my Computer?" FAQ +============================================= + +What is Python? +--------------- + +Python is a programming language. It's used for many different applications. +It's used in some high schools and colleges as an introductory programming +language because Python is easy to learn, but it's also used by professional +software developers at places such as Google, NASA, and Lucasfilm Ltd. + +If you wish to learn more about Python, start with the `Beginner's Guide to +Python <https://wiki.python.org/moin/BeginnersGuide>`_. + + +Why is Python installed on my machine? +-------------------------------------- + +If you find Python installed on your system but don't remember installing it, +there are several possible ways it could have gotten there. + +* Perhaps another user on the computer wanted to learn programming and installed + it; you'll have to figure out who's been using the machine and might have + installed it. +* A third-party application installed on the machine might have been written in + Python and included a Python installation. There are many such applications, + from GUI programs to network servers and administrative scripts. +* Some Windows machines also have Python installed. At this writing we're aware + of computers from Hewlett-Packard and Compaq that include Python. Apparently + some of HP/Compaq's administrative tools are written in Python. +* Many Unix-compatible operating systems, such as Mac OS X and some Linux + distributions, have Python installed by default; it's included in the base + installation. + + +Can I delete Python? +-------------------- + +That depends on where Python came from. + +If someone installed it deliberately, you can remove it without hurting +anything. On Windows, use the Add/Remove Programs icon in the Control Panel. + +If Python was installed by a third-party application, you can also remove it, +but that application will no longer work. You should use that application's +uninstaller rather than removing Python directly. + +If Python came with your operating system, removing it is not recommended. If +you remove it, whatever tools were written in Python will no longer run, and +some of them might be important to you. Reinstalling the whole system would +then be required to fix things again. + diff --git a/cpython_2/environment/repo/Doc/faq/library.rst b/cpython_2/environment/repo/Doc/faq/library.rst new file mode 100644 index 0000000000000000000000000000000000000000..97058b5806a35c30d34b4568d9f1073902769983 --- /dev/null +++ b/cpython_2/environment/repo/Doc/faq/library.rst @@ -0,0 +1,840 @@ +:tocdepth: 2 + +========================= +Library and Extension FAQ +========================= + +.. only:: html + + .. contents:: + +General Library Questions +========================= + +How do I find a module or application to perform task X? +-------------------------------------------------------- + +Check :ref:`the Library Reference <library-index>` to see if there's a relevant +standard library module. (Eventually you'll learn what's in the standard +library and will be able to skip this step.) + +For third-party packages, search the `Python Package Index +<https://pypi.org>`_ or try `Google <https://www.google.com>`_ or +another Web search engine. Searching for "Python" plus a keyword or two for +your topic of interest will usually find something helpful. + + +Where is the math.py (socket.py, regex.py, etc.) source file? +------------------------------------------------------------- + +If you can't find a source file for a module it may be a built-in or +dynamically loaded module implemented in C, C++ or other compiled language. +In this case you may not have the source file or it may be something like +:file:`mathmodule.c`, somewhere in a C source directory (not on the Python Path). + +There are (at least) three kinds of modules in Python: + +1) modules written in Python (.py); +2) modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc); +3) modules written in C and linked with the interpreter; to get a list of these, + type:: + + import sys + print(sys.builtin_module_names) + + +How do I make a Python script executable on Unix? +------------------------------------------------- + +You need to do two things: the script file's mode must be executable and the +first line must begin with ``#!`` followed by the path of the Python +interpreter. + +The first is done by executing ``chmod +x scriptfile`` or perhaps ``chmod 755 +scriptfile``. + +The second can be done in a number of ways. The most straightforward way is to +write :: + + #!/usr/local/bin/python + +as the very first line of your file, using the pathname for where the Python +interpreter is installed on your platform. + +If you would like the script to be independent of where the Python interpreter +lives, you can use the :program:`env` program. Almost all Unix variants support +the following, assuming the Python interpreter is in a directory on the user's +:envvar:`PATH`:: + + #!/usr/bin/env python + +*Don't* do this for CGI scripts. The :envvar:`PATH` variable for CGI scripts is +often very minimal, so you need to use the actual absolute pathname of the +interpreter. + +Occasionally, a user's environment is so full that the :program:`/usr/bin/env` +program fails; or there's no env program at all. In that case, you can try the +following hack (due to Alex Rezinsky): + +.. code-block:: sh + + #! /bin/sh + """:" + exec python $0 ${1+"$@"} + """ + +The minor disadvantage is that this defines the script's __doc__ string. +However, you can fix that by adding :: + + __doc__ = """...Whatever...""" + + + +Is there a curses/termcap package for Python? +--------------------------------------------- + +.. XXX curses *is* built by default, isn't it? + +For Unix variants: The standard Python source distribution comes with a curses +module in the :source:`Modules` subdirectory, though it's not compiled by default. +(Note that this is not available in the Windows distribution -- there is no +curses module for Windows.) + +The :mod:`curses` module supports basic curses features as well as many additional +functions from ncurses and SYSV curses such as colour, alternative character set +support, pads, and mouse support. This means the module isn't compatible with +operating systems that only have BSD curses, but there don't seem to be any +currently maintained OSes that fall into this category. + +For Windows: use `the consolelib module +<http://effbot.org/zone/console-index.htm>`_. + + +Is there an equivalent to C's onexit() in Python? +------------------------------------------------- + +The :mod:`atexit` module provides a register function that is similar to C's +:c:func:`onexit`. + + +Why don't my signal handlers work? +---------------------------------- + +The most common problem is that the signal handler is declared with the wrong +argument list. It is called as :: + + handler(signum, frame) + +so it should be declared with two parameters:: + + def handler(signum, frame): + ... + + +Common tasks +============ + +How do I test a Python program or component? +-------------------------------------------- + +Python comes with two testing frameworks. The :mod:`doctest` module finds +examples in the docstrings for a module and runs them, comparing the output with +the expected output given in the docstring. + +The :mod:`unittest` module is a fancier testing framework modelled on Java and +Smalltalk testing frameworks. + +To make testing easier, you should use good modular design in your program. +Your program should have almost all functionality +encapsulated in either functions or class methods -- and this sometimes has the +surprising and delightful effect of making the program run faster (because local +variable accesses are faster than global accesses). Furthermore the program +should avoid depending on mutating global variables, since this makes testing +much more difficult to do. + +The "global main logic" of your program may be as simple as :: + + if __name__ == "__main__": + main_logic() + +at the bottom of the main module of your program. + +Once your program is organized as a tractable collection of function and class +behaviours, you should write test functions that exercise the behaviours. A +test suite that automates a sequence of tests can be associated with each module. +This sounds like a lot of work, but since Python is so terse and flexible it's +surprisingly easy. You can make coding much more pleasant and fun by writing +your test functions in parallel with the "production code", since this makes it +easy to find bugs and even design flaws earlier. + +"Support modules" that are not intended to be the main module of a program may +include a self-test of the module. :: + + if __name__ == "__main__": + self_test() + +Even programs that interact with complex external interfaces may be tested when +the external interfaces are unavailable by using "fake" interfaces implemented +in Python. + + +How do I create documentation from doc strings? +----------------------------------------------- + +The :mod:`pydoc` module can create HTML from the doc strings in your Python +source code. An alternative for creating API documentation purely from +docstrings is `epydoc <http://epydoc.sourceforge.net/>`_. `Sphinx +<http://sphinx-doc.org>`_ can also include docstring content. + + +How do I get a single keypress at a time? +----------------------------------------- + +For Unix variants there are several solutions. It's straightforward to do this +using curses, but curses is a fairly large module to learn. + +.. XXX this doesn't work out of the box, some IO expert needs to check why + + Here's a solution without curses:: + + import termios, fcntl, sys, os + fd = sys.stdin.fileno() + + oldterm = termios.tcgetattr(fd) + newattr = termios.tcgetattr(fd) + newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO + termios.tcsetattr(fd, termios.TCSANOW, newattr) + + oldflags = fcntl.fcntl(fd, fcntl.F_GETFL) + fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK) + + try: + while True: + try: + c = sys.stdin.read(1) + print("Got character", repr(c)) + except OSError: + pass + finally: + termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm) + fcntl.fcntl(fd, fcntl.F_SETFL, oldflags) + + You need the :mod:`termios` and the :mod:`fcntl` module for any of this to + work, and I've only tried it on Linux, though it should work elsewhere. In + this code, characters are read and printed one at a time. + + :func:`termios.tcsetattr` turns off stdin's echoing and disables canonical + mode. :func:`fcntl.fnctl` is used to obtain stdin's file descriptor flags + and modify them for non-blocking mode. Since reading stdin when it is empty + results in an :exc:`OSError`, this error is caught and ignored. + + .. versionchanged:: 3.3 + *sys.stdin.read* used to raise :exc:`IOError`. Starting from Python 3.3 + :exc:`IOError` is alias for :exc:`OSError`. + + +Threads +======= + +How do I program using threads? +------------------------------- + +Be sure to use the :mod:`threading` module and not the :mod:`_thread` module. +The :mod:`threading` module builds convenient abstractions on top of the +low-level primitives provided by the :mod:`_thread` module. + +Aahz has a set of slides from his threading tutorial that are helpful; see +http://www.pythoncraft.com/OSCON2001/. + + +None of my threads seem to run: why? +------------------------------------ + +As soon as the main thread exits, all threads are killed. Your main thread is +running too quickly, giving the threads no time to do any work. + +A simple fix is to add a sleep to the end of the program that's long enough for +all the threads to finish:: + + import threading, time + + def thread_task(name, n): + for i in range(n): + print(name, i) + + for i in range(10): + T = threading.Thread(target=thread_task, args=(str(i), i)) + T.start() + + time.sleep(10) # <---------------------------! + +But now (on many platforms) the threads don't run in parallel, but appear to run +sequentially, one at a time! The reason is that the OS thread scheduler doesn't +start a new thread until the previous thread is blocked. + +A simple fix is to add a tiny sleep to the start of the run function:: + + def thread_task(name, n): + time.sleep(0.001) # <--------------------! + for i in range(n): + print(name, i) + + for i in range(10): + T = threading.Thread(target=thread_task, args=(str(i), i)) + T.start() + + time.sleep(10) + +Instead of trying to guess a good delay value for :func:`time.sleep`, +it's better to use some kind of semaphore mechanism. One idea is to use the +:mod:`queue` module to create a queue object, let each thread append a token to +the queue when it finishes, and let the main thread read as many tokens from the +queue as there are threads. + + +How do I parcel out work among a bunch of worker threads? +--------------------------------------------------------- + +The easiest way is to use the :mod:`concurrent.futures` module, +especially the :mod:`~concurrent.futures.ThreadPoolExecutor` class. + +Or, if you want fine control over the dispatching algorithm, you can write +your own logic manually. Use the :mod:`queue` module to create a queue +containing a list of jobs. The :class:`~queue.Queue` class maintains a +list of objects and has a ``.put(obj)`` method that adds items to the queue and +a ``.get()`` method to return them. The class will take care of the locking +necessary to ensure that each job is handed out exactly once. + +Here's a trivial example:: + + import threading, queue, time + + # The worker thread gets jobs off the queue. When the queue is empty, it + # assumes there will be no more work and exits. + # (Realistically workers will run until terminated.) + def worker(): + print('Running worker') + time.sleep(0.1) + while True: + try: + arg = q.get(block=False) + except queue.Empty: + print('Worker', threading.currentThread(), end=' ') + print('queue empty') + break + else: + print('Worker', threading.currentThread(), end=' ') + print('running with argument', arg) + time.sleep(0.5) + + # Create queue + q = queue.Queue() + + # Start a pool of 5 workers + for i in range(5): + t = threading.Thread(target=worker, name='worker %i' % (i+1)) + t.start() + + # Begin adding work to the queue + for i in range(50): + q.put(i) + + # Give threads time to run + print('Main thread sleeping') + time.sleep(5) + +When run, this will produce the following output: + +.. code-block:: none + + Running worker + Running worker + Running worker + Running worker + Running worker + Main thread sleeping + Worker <Thread(worker 1, started 130283832797456)> running with argument 0 + Worker <Thread(worker 2, started 130283824404752)> running with argument 1 + Worker <Thread(worker 3, started 130283816012048)> running with argument 2 + Worker <Thread(worker 4, started 130283807619344)> running with argument 3 + Worker <Thread(worker 5, started 130283799226640)> running with argument 4 + Worker <Thread(worker 1, started 130283832797456)> running with argument 5 + ... + +Consult the module's documentation for more details; the :class:`~queue.Queue` +class provides a featureful interface. + + +What kinds of global value mutation are thread-safe? +---------------------------------------------------- + +A :term:`global interpreter lock` (GIL) is used internally to ensure that only one +thread runs in the Python VM at a time. In general, Python offers to switch +among threads only between bytecode instructions; how frequently it switches can +be set via :func:`sys.setswitchinterval`. Each bytecode instruction and +therefore all the C implementation code reached from each instruction is +therefore atomic from the point of view of a Python program. + +In theory, this means an exact accounting requires an exact understanding of the +PVM bytecode implementation. In practice, it means that operations on shared +variables of built-in data types (ints, lists, dicts, etc) that "look atomic" +really are. + +For example, the following operations are all atomic (L, L1, L2 are lists, D, +D1, D2 are dicts, x, y are objects, i, j are ints):: + + L.append(x) + L1.extend(L2) + x = L[i] + x = L.pop() + L1[i:j] = L2 + L.sort() + x = y + x.field = y + D[x] = y + D1.update(D2) + D.keys() + +These aren't:: + + i = i+1 + L.append(L[-1]) + L[i] = L[j] + D[x] = D[x] + 1 + +Operations that replace other objects may invoke those other objects' +:meth:`__del__` method when their reference count reaches zero, and that can +affect things. This is especially true for the mass updates to dictionaries and +lists. When in doubt, use a mutex! + + +Can't we get rid of the Global Interpreter Lock? +------------------------------------------------ + +.. XXX link to dbeazley's talk about GIL? + +The :term:`global interpreter lock` (GIL) is often seen as a hindrance to Python's +deployment on high-end multiprocessor server machines, because a multi-threaded +Python program effectively only uses one CPU, due to the insistence that +(almost) all Python code can only run while the GIL is held. + +Back in the days of Python 1.5, Greg Stein actually implemented a comprehensive +patch set (the "free threading" patches) that removed the GIL and replaced it +with fine-grained locking. Adam Olsen recently did a similar experiment +in his `python-safethread <https://code.google.com/archive/p/python-safethread>`_ +project. Unfortunately, both experiments exhibited a sharp drop in single-thread +performance (at least 30% slower), due to the amount of fine-grained locking +necessary to compensate for the removal of the GIL. + +This doesn't mean that you can't make good use of Python on multi-CPU machines! +You just have to be creative with dividing the work up between multiple +*processes* rather than multiple *threads*. The +:class:`~concurrent.futures.ProcessPoolExecutor` class in the new +:mod:`concurrent.futures` module provides an easy way of doing so; the +:mod:`multiprocessing` module provides a lower-level API in case you want +more control over dispatching of tasks. + +Judicious use of C extensions will also help; if you use a C extension to +perform a time-consuming task, the extension can release the GIL while the +thread of execution is in the C code and allow other threads to get some work +done. Some standard library modules such as :mod:`zlib` and :mod:`hashlib` +already do this. + +It has been suggested that the GIL should be a per-interpreter-state lock rather +than truly global; interpreters then wouldn't be able to share objects. +Unfortunately, this isn't likely to happen either. It would be a tremendous +amount of work, because many object implementations currently have global state. +For example, small integers and short strings are cached; these caches would +have to be moved to the interpreter state. Other object types have their own +free list; these free lists would have to be moved to the interpreter state. +And so on. + +And I doubt that it can even be done in finite time, because the same problem +exists for 3rd party extensions. It is likely that 3rd party extensions are +being written at a faster rate than you can convert them to store all their +global state in the interpreter state. + +And finally, once you have multiple interpreters not sharing any state, what +have you gained over running each interpreter in a separate process? + + +Input and Output +================ + +How do I delete a file? (And other file questions...) +----------------------------------------------------- + +Use ``os.remove(filename)`` or ``os.unlink(filename)``; for documentation, see +the :mod:`os` module. The two functions are identical; :func:`~os.unlink` is simply +the name of the Unix system call for this function. + +To remove a directory, use :func:`os.rmdir`; use :func:`os.mkdir` to create one. +``os.makedirs(path)`` will create any intermediate directories in ``path`` that +don't exist. ``os.removedirs(path)`` will remove intermediate directories as +long as they're empty; if you want to delete an entire directory tree and its +contents, use :func:`shutil.rmtree`. + +To rename a file, use ``os.rename(old_path, new_path)``. + +To truncate a file, open it using ``f = open(filename, "rb+")``, and use +``f.truncate(offset)``; offset defaults to the current seek position. There's +also ``os.ftruncate(fd, offset)`` for files opened with :func:`os.open`, where +*fd* is the file descriptor (a small integer). + +The :mod:`shutil` module also contains a number of functions to work on files +including :func:`~shutil.copyfile`, :func:`~shutil.copytree`, and +:func:`~shutil.rmtree`. + + +How do I copy a file? +--------------------- + +The :mod:`shutil` module contains a :func:`~shutil.copyfile` function. Note +that on MacOS 9 it doesn't copy the resource fork and Finder info. + + +How do I read (or write) binary data? +------------------------------------- + +To read or write complex binary data formats, it's best to use the :mod:`struct` +module. It allows you to take a string containing binary data (usually numbers) +and convert it to Python objects; and vice versa. + +For example, the following code reads two 2-byte integers and one 4-byte integer +in big-endian format from a file:: + + import struct + + with open(filename, "rb") as f: + s = f.read(8) + x, y, z = struct.unpack(">hhl", s) + +The '>' in the format string forces big-endian data; the letter 'h' reads one +"short integer" (2 bytes), and 'l' reads one "long integer" (4 bytes) from the +string. + +For data that is more regular (e.g. a homogeneous list of ints or floats), +you can also use the :mod:`array` module. + +.. note:: + + To read and write binary data, it is mandatory to open the file in + binary mode (here, passing ``"rb"`` to :func:`open`). If you use + ``"r"`` instead (the default), the file will be open in text mode + and ``f.read()`` will return :class:`str` objects rather than + :class:`bytes` objects. + + +I can't seem to use os.read() on a pipe created with os.popen(); why? +--------------------------------------------------------------------- + +:func:`os.read` is a low-level function which takes a file descriptor, a small +integer representing the opened file. :func:`os.popen` creates a high-level +file object, the same type returned by the built-in :func:`open` function. +Thus, to read *n* bytes from a pipe *p* created with :func:`os.popen`, you need to +use ``p.read(n)``. + + +.. XXX update to use subprocess. See the :ref:`subprocess-replacements` section. + + How do I run a subprocess with pipes connected to both input and output? + ------------------------------------------------------------------------ + + Use the :mod:`popen2` module. For example:: + + import popen2 + fromchild, tochild = popen2.popen2("command") + tochild.write("input\n") + tochild.flush() + output = fromchild.readline() + + Warning: in general it is unwise to do this because you can easily cause a + deadlock where your process is blocked waiting for output from the child + while the child is blocked waiting for input from you. This can be caused + by the parent expecting the child to output more text than it does or + by data being stuck in stdio buffers due to lack of flushing. + The Python parent can of course explicitly flush the data it sends to the + child before it reads any output, but if the child is a naive C program it + may have been written to never explicitly flush its output, even if it is + interactive, since flushing is normally automatic. + + Note that a deadlock is also possible if you use :func:`popen3` to read + stdout and stderr. If one of the two is too large for the internal buffer + (increasing the buffer size does not help) and you ``read()`` the other one + first, there is a deadlock, too. + + Note on a bug in popen2: unless your program calls ``wait()`` or + ``waitpid()``, finished child processes are never removed, and eventually + calls to popen2 will fail because of a limit on the number of child + processes. Calling :func:`os.waitpid` with the :data:`os.WNOHANG` option can + prevent this; a good place to insert such a call would be before calling + ``popen2`` again. + + In many cases, all you really need is to run some data through a command and + get the result back. Unless the amount of data is very large, the easiest + way to do this is to write it to a temporary file and run the command with + that temporary file as input. The standard module :mod:`tempfile` exports a + :func:`~tempfile.mktemp` function to generate unique temporary file names. :: + + import tempfile + import os + + class Popen3: + """ + This is a deadlock-safe version of popen that returns + an object with errorlevel, out (a string) and err (a string). + (capturestderr may not work under windows.) + Example: print(Popen3('grep spam','\n\nhere spam\n\n').out) + """ + def __init__(self,command,input=None,capturestderr=None): + outfile=tempfile.mktemp() + command="( %s ) > %s" % (command,outfile) + if input: + infile=tempfile.mktemp() + open(infile,"w").write(input) + command=command+" <"+infile + if capturestderr: + errfile=tempfile.mktemp() + command=command+" 2>"+errfile + self.errorlevel=os.system(command) >> 8 + self.out=open(outfile,"r").read() + os.remove(outfile) + if input: + os.remove(infile) + if capturestderr: + self.err=open(errfile,"r").read() + os.remove(errfile) + + Note that many interactive programs (e.g. vi) don't work well with pipes + substituted for standard input and output. You will have to use pseudo ttys + ("ptys") instead of pipes. Or you can use a Python interface to Don Libes' + "expect" library. A Python extension that interfaces to expect is called + "expy" and available from http://expectpy.sourceforge.net. A pure Python + solution that works like expect is `pexpect + <https://pypi.org/project/pexpect/>`_. + + +How do I access the serial (RS232) port? +---------------------------------------- + +For Win32, POSIX (Linux, BSD, etc.), Jython: + + http://pyserial.sourceforge.net + +For Unix, see a Usenet post by Mitch Chapman: + + https://groups.google.com/groups?selm=34A04430.CF9@ohioee.com + + +Why doesn't closing sys.stdout (stdin, stderr) really close it? +--------------------------------------------------------------- + +Python :term:`file objects <file object>` are a high-level layer of +abstraction on low-level C file descriptors. + +For most file objects you create in Python via the built-in :func:`open` +function, ``f.close()`` marks the Python file object as being closed from +Python's point of view, and also arranges to close the underlying C file +descriptor. This also happens automatically in ``f``'s destructor, when +``f`` becomes garbage. + +But stdin, stdout and stderr are treated specially by Python, because of the +special status also given to them by C. Running ``sys.stdout.close()`` marks +the Python-level file object as being closed, but does *not* close the +associated C file descriptor. + +To close the underlying C file descriptor for one of these three, you should +first be sure that's what you really want to do (e.g., you may confuse +extension modules trying to do I/O). If it is, use :func:`os.close`:: + + os.close(stdin.fileno()) + os.close(stdout.fileno()) + os.close(stderr.fileno()) + +Or you can use the numeric constants 0, 1 and 2, respectively. + + +Network/Internet Programming +============================ + +What WWW tools are there for Python? +------------------------------------ + +See the chapters titled :ref:`internet` and :ref:`netdata` in the Library +Reference Manual. Python has many modules that will help you build server-side +and client-side web systems. + +.. XXX check if wiki page is still up to date + +A summary of available frameworks is maintained by Paul Boddie at +https://wiki.python.org/moin/WebProgramming\ . + +Cameron Laird maintains a useful set of pages about Python web technologies at +http://phaseit.net/claird/comp.lang.python/web_python. + + +How can I mimic CGI form submission (METHOD=POST)? +-------------------------------------------------- + +I would like to retrieve web pages that are the result of POSTing a form. Is +there existing code that would let me do this easily? + +Yes. Here's a simple example that uses :mod:`urllib.request`:: + + #!/usr/local/bin/python + + import urllib.request + + # build the query string + qs = "First=Josephine&MI=Q&Last=Public" + + # connect and send the server a path + req = urllib.request.urlopen('http://www.some-server.out-there' + '/cgi-bin/some-cgi-script', data=qs) + with req: + msg, hdrs = req.read(), req.info() + +Note that in general for percent-encoded POST operations, query strings must be +quoted using :func:`urllib.parse.urlencode`. For example, to send +``name=Guy Steele, Jr.``:: + + >>> import urllib.parse + >>> urllib.parse.urlencode({'name': 'Guy Steele, Jr.'}) + 'name=Guy+Steele%2C+Jr.' + +.. seealso:: :ref:`urllib-howto` for extensive examples. + + +What module should I use to help with generating HTML? +------------------------------------------------------ + +.. XXX add modern template languages + +You can find a collection of useful links on the `Web Programming wiki page +<https://wiki.python.org/moin/WebProgramming>`_. + + +How do I send mail from a Python script? +---------------------------------------- + +Use the standard library module :mod:`smtplib`. + +Here's a very simple interactive mail sender that uses it. This method will +work on any host that supports an SMTP listener. :: + + import sys, smtplib + + fromaddr = input("From: ") + toaddrs = input("To: ").split(',') + print("Enter message, end with ^D:") + msg = '' + while True: + line = sys.stdin.readline() + if not line: + break + msg += line + + # The actual mail send + server = smtplib.SMTP('localhost') + server.sendmail(fromaddr, toaddrs, msg) + server.quit() + +A Unix-only alternative uses sendmail. The location of the sendmail program +varies between systems; sometimes it is ``/usr/lib/sendmail``, sometimes +``/usr/sbin/sendmail``. The sendmail manual page will help you out. Here's +some sample code:: + + import os + + SENDMAIL = "/usr/sbin/sendmail" # sendmail location + p = os.popen("%s -t -i" % SENDMAIL, "w") + p.write("To: receiver@example.com\n") + p.write("Subject: test\n") + p.write("\n") # blank line separating headers from body + p.write("Some text\n") + p.write("some more text\n") + sts = p.close() + if sts != 0: + print("Sendmail exit status", sts) + + +How do I avoid blocking in the connect() method of a socket? +------------------------------------------------------------ + +The :mod:`select` module is commonly used to help with asynchronous I/O on +sockets. + +To prevent the TCP connect from blocking, you can set the socket to non-blocking +mode. Then when you do the :meth:`socket.connect`, you will either connect immediately +(unlikely) or get an exception that contains the error number as ``.errno``. +``errno.EINPROGRESS`` indicates that the connection is in progress, but hasn't +finished yet. Different OSes will return different values, so you're going to +have to check what's returned on your system. + +You can use the :meth:`socket.connect_ex` method to avoid creating an exception. It will +just return the errno value. To poll, you can call :meth:`socket.connect_ex` again later +-- ``0`` or ``errno.EISCONN`` indicate that you're connected -- or you can pass this +socket to :meth:`select.select` to check if it's writable. + +.. note:: + The :mod:`asyncio` module provides a general purpose single-threaded and + concurrent asynchronous library, which can be used for writing non-blocking + network code. + The third-party `Twisted <https://twistedmatrix.com/trac/>`_ library is + a popular and feature-rich alternative. + + +Databases +========= + +Are there any interfaces to database packages in Python? +-------------------------------------------------------- + +Yes. + +Interfaces to disk-based hashes such as :mod:`DBM <dbm.ndbm>` and :mod:`GDBM +<dbm.gnu>` are also included with standard Python. There is also the +:mod:`sqlite3` module, which provides a lightweight disk-based relational +database. + +Support for most relational databases is available. See the +`DatabaseProgramming wiki page +<https://wiki.python.org/moin/DatabaseProgramming>`_ for details. + + +How do you implement persistent objects in Python? +-------------------------------------------------- + +The :mod:`pickle` library module solves this in a very general way (though you +still can't store things like open files, sockets or windows), and the +:mod:`shelve` library module uses pickle and (g)dbm to create persistent +mappings containing arbitrary Python objects. + + +Mathematics and Numerics +======================== + +How do I generate random numbers in Python? +------------------------------------------- + +The standard module :mod:`random` implements a random number generator. Usage +is simple:: + + import random + random.random() + +This returns a random floating point number in the range [0, 1). + +There are also many other specialized generators in this module, such as: + +* ``randrange(a, b)`` chooses an integer in the range [a, b). +* ``uniform(a, b)`` chooses a floating point number in the range [a, b). +* ``normalvariate(mean, sdev)`` samples the normal (Gaussian) distribution. + +Some higher-level functions operate on sequences directly, such as: + +* ``choice(S)`` chooses a random element from a given sequence. +* ``shuffle(L)`` shuffles a list in-place, i.e. permutes it randomly. + +There's also a ``Random`` class you can instantiate to create independent +multiple random number generators. diff --git a/cpython_2/environment/repo/Doc/faq/programming.rst b/cpython_2/environment/repo/Doc/faq/programming.rst new file mode 100644 index 0000000000000000000000000000000000000000..61ffc5dbdaa7736d4c4294663b0847c926786445 --- /dev/null +++ b/cpython_2/environment/repo/Doc/faq/programming.rst @@ -0,0 +1,1897 @@ +:tocdepth: 2 + +=============== +Programming FAQ +=============== + +.. only:: html + + .. contents:: + +General Questions +================= + +Is there a source code level debugger with breakpoints, single-stepping, etc.? +------------------------------------------------------------------------------ + +Yes. + +Several debuggers for Python are described below, and the built-in function +:func:`breakpoint` allows you to drop into any of them. + +The pdb module is a simple but adequate console-mode debugger for Python. It is +part of the standard Python library, and is :mod:`documented in the Library +Reference Manual <pdb>`. You can also write your own debugger by using the code +for pdb as an example. + +The IDLE interactive development environment, which is part of the standard +Python distribution (normally available as Tools/scripts/idle), includes a +graphical debugger. + +PythonWin is a Python IDE that includes a GUI debugger based on pdb. The +Pythonwin debugger colors breakpoints and has quite a few cool features such as +debugging non-Pythonwin programs. Pythonwin is available as part of the `Python +for Windows Extensions <https://sourceforge.net/projects/pywin32/>`__ project and +as a part of the ActivePython distribution (see +https://www.activestate.com/activepython\ ). + +`Boa Constructor <http://boa-constructor.sourceforge.net/>`_ is an IDE and GUI +builder that uses wxWidgets. It offers visual frame creation and manipulation, +an object inspector, many views on the source like object browsers, inheritance +hierarchies, doc string generated html documentation, an advanced debugger, +integrated help, and Zope support. + +`Eric <http://eric-ide.python-projects.org/>`_ is an IDE built on PyQt +and the Scintilla editing component. + +Pydb is a version of the standard Python debugger pdb, modified for use with DDD +(Data Display Debugger), a popular graphical debugger front end. Pydb can be +found at http://bashdb.sourceforge.net/pydb/ and DDD can be found at +https://www.gnu.org/software/ddd. + +There are a number of commercial Python IDEs that include graphical debuggers. +They include: + +* Wing IDE (https://wingware.com/) +* Komodo IDE (https://komodoide.com/) +* PyCharm (https://www.jetbrains.com/pycharm/) + + +Is there a tool to help find bugs or perform static analysis? +------------------------------------------------------------- + +Yes. + +PyChecker is a static analysis tool that finds bugs in Python source code and +warns about code complexity and style. You can get PyChecker from +http://pychecker.sourceforge.net/. + +`Pylint <https://www.pylint.org/>`_ is another tool that checks +if a module satisfies a coding standard, and also makes it possible to write +plug-ins to add a custom feature. In addition to the bug checking that +PyChecker performs, Pylint offers some additional features such as checking line +length, whether variable names are well-formed according to your coding +standard, whether declared interfaces are fully implemented, and more. +https://docs.pylint.org/ provides a full list of Pylint's features. + +Static type checkers such as `Mypy <http://mypy-lang.org/>`_, +`Pyre <https://pyre-check.org/>`_, and +`Pytype <https://github.com/google/pytype>`_ can check type hints in Python +source code. + + +How can I create a stand-alone binary from a Python script? +----------------------------------------------------------- + +You don't need the ability to compile Python to C code if all you want is a +stand-alone program that users can download and run without having to install +the Python distribution first. There are a number of tools that determine the +set of modules required by a program and bind these modules together with a +Python binary to produce a single executable. + +One is to use the freeze tool, which is included in the Python source tree as +``Tools/freeze``. It converts Python byte code to C arrays; a C compiler you can +embed all your modules into a new program, which is then linked with the +standard Python modules. + +It works by scanning your source recursively for import statements (in both +forms) and looking for the modules in the standard Python path as well as in the +source directory (for built-in modules). It then turns the bytecode for modules +written in Python into C code (array initializers that can be turned into code +objects using the marshal module) and creates a custom-made config file that +only contains those built-in modules which are actually used in the program. It +then compiles the generated C code and links it with the rest of the Python +interpreter to form a self-contained binary which acts exactly like your script. + +Obviously, freeze requires a C compiler. There are several other utilities +which don't. One is Thomas Heller's py2exe (Windows only) at + + http://www.py2exe.org/ + +Another tool is Anthony Tuininga's `cx_Freeze <https://anthony-tuininga.github.io/cx_Freeze/>`_. + + +Are there coding standards or a style guide for Python programs? +---------------------------------------------------------------- + +Yes. The coding style required for standard library modules is documented as +:pep:`8`. + + +Core Language +============= + +Why am I getting an UnboundLocalError when the variable has a value? +-------------------------------------------------------------------- + +It can be a surprise to get the UnboundLocalError in previously working +code when it is modified by adding an assignment statement somewhere in +the body of a function. + +This code: + + >>> x = 10 + >>> def bar(): + ... print(x) + >>> bar() + 10 + +works, but this code: + + >>> x = 10 + >>> def foo(): + ... print(x) + ... x += 1 + +results in an UnboundLocalError: + + >>> foo() + Traceback (most recent call last): + ... + UnboundLocalError: local variable 'x' referenced before assignment + +This is because when you make an assignment to a variable in a scope, that +variable becomes local to that scope and shadows any similarly named variable +in the outer scope. Since the last statement in foo assigns a new value to +``x``, the compiler recognizes it as a local variable. Consequently when the +earlier ``print(x)`` attempts to print the uninitialized local variable and +an error results. + +In the example above you can access the outer scope variable by declaring it +global: + + >>> x = 10 + >>> def foobar(): + ... global x + ... print(x) + ... x += 1 + >>> foobar() + 10 + +This explicit declaration is required in order to remind you that (unlike the +superficially analogous situation with class and instance variables) you are +actually modifying the value of the variable in the outer scope: + + >>> print(x) + 11 + +You can do a similar thing in a nested scope using the :keyword:`nonlocal` +keyword: + + >>> def foo(): + ... x = 10 + ... def bar(): + ... nonlocal x + ... print(x) + ... x += 1 + ... bar() + ... print(x) + >>> foo() + 10 + 11 + + +What are the rules for local and global variables in Python? +------------------------------------------------------------ + +In Python, variables that are only referenced inside a function are implicitly +global. If a variable is assigned a value anywhere within the function's body, +it's assumed to be a local unless explicitly declared as global. + +Though a bit surprising at first, a moment's consideration explains this. On +one hand, requiring :keyword:`global` for assigned variables provides a bar +against unintended side-effects. On the other hand, if ``global`` was required +for all global references, you'd be using ``global`` all the time. You'd have +to declare as global every reference to a built-in function or to a component of +an imported module. This clutter would defeat the usefulness of the ``global`` +declaration for identifying side-effects. + + +Why do lambdas defined in a loop with different values all return the same result? +---------------------------------------------------------------------------------- + +Assume you use a for loop to define a few different lambdas (or even plain +functions), e.g.:: + + >>> squares = [] + >>> for x in range(5): + ... squares.append(lambda: x**2) + +This gives you a list that contains 5 lambdas that calculate ``x**2``. You +might expect that, when called, they would return, respectively, ``0``, ``1``, +``4``, ``9``, and ``16``. However, when you actually try you will see that +they all return ``16``:: + + >>> squares[2]() + 16 + >>> squares[4]() + 16 + +This happens because ``x`` is not local to the lambdas, but is defined in +the outer scope, and it is accessed when the lambda is called --- not when it +is defined. At the end of the loop, the value of ``x`` is ``4``, so all the +functions now return ``4**2``, i.e. ``16``. You can also verify this by +changing the value of ``x`` and see how the results of the lambdas change:: + + >>> x = 8 + >>> squares[2]() + 64 + +In order to avoid this, you need to save the values in variables local to the +lambdas, so that they don't rely on the value of the global ``x``:: + + >>> squares = [] + >>> for x in range(5): + ... squares.append(lambda n=x: n**2) + +Here, ``n=x`` creates a new variable ``n`` local to the lambda and computed +when the lambda is defined so that it has the same value that ``x`` had at +that point in the loop. This means that the value of ``n`` will be ``0`` +in the first lambda, ``1`` in the second, ``2`` in the third, and so on. +Therefore each lambda will now return the correct result:: + + >>> squares[2]() + 4 + >>> squares[4]() + 16 + +Note that this behaviour is not peculiar to lambdas, but applies to regular +functions too. + + +How do I share global variables across modules? +------------------------------------------------ + +The canonical way to share information across modules within a single program is +to create a special module (often called config or cfg). Just import the config +module in all modules of your application; the module then becomes available as +a global name. Because there is only one instance of each module, any changes +made to the module object get reflected everywhere. For example: + +config.py:: + + x = 0 # Default value of the 'x' configuration setting + +mod.py:: + + import config + config.x = 1 + +main.py:: + + import config + import mod + print(config.x) + +Note that using a module is also the basis for implementing the Singleton design +pattern, for the same reason. + + +What are the "best practices" for using import in a module? +----------------------------------------------------------- + +In general, don't use ``from modulename import *``. Doing so clutters the +importer's namespace, and makes it much harder for linters to detect undefined +names. + +Import modules at the top of a file. Doing so makes it clear what other modules +your code requires and avoids questions of whether the module name is in scope. +Using one import per line makes it easy to add and delete module imports, but +using multiple imports per line uses less screen space. + +It's good practice if you import modules in the following order: + +1. standard library modules -- e.g. ``sys``, ``os``, ``getopt``, ``re`` +2. third-party library modules (anything installed in Python's site-packages + directory) -- e.g. mx.DateTime, ZODB, PIL.Image, etc. +3. locally-developed modules + +It is sometimes necessary to move imports to a function or class to avoid +problems with circular imports. Gordon McMillan says: + + Circular imports are fine where both modules use the "import <module>" form + of import. They fail when the 2nd module wants to grab a name out of the + first ("from module import name") and the import is at the top level. That's + because names in the 1st are not yet available, because the first module is + busy importing the 2nd. + +In this case, if the second module is only used in one function, then the import +can easily be moved into that function. By the time the import is called, the +first module will have finished initializing, and the second module can do its +import. + +It may also be necessary to move imports out of the top level of code if some of +the modules are platform-specific. In that case, it may not even be possible to +import all of the modules at the top of the file. In this case, importing the +correct modules in the corresponding platform-specific code is a good option. + +Only move imports into a local scope, such as inside a function definition, if +it's necessary to solve a problem such as avoiding a circular import or are +trying to reduce the initialization time of a module. This technique is +especially helpful if many of the imports are unnecessary depending on how the +program executes. You may also want to move imports into a function if the +modules are only ever used in that function. Note that loading a module the +first time may be expensive because of the one time initialization of the +module, but loading a module multiple times is virtually free, costing only a +couple of dictionary lookups. Even if the module name has gone out of scope, +the module is probably available in :data:`sys.modules`. + + +Why are default values shared between objects? +---------------------------------------------- + +This type of bug commonly bites neophyte programmers. Consider this function:: + + def foo(mydict={}): # Danger: shared reference to one dict for all calls + ... compute something ... + mydict[key] = value + return mydict + +The first time you call this function, ``mydict`` contains a single item. The +second time, ``mydict`` contains two items because when ``foo()`` begins +executing, ``mydict`` starts out with an item already in it. + +It is often expected that a function call creates new objects for default +values. This is not what happens. Default values are created exactly once, when +the function is defined. If that object is changed, like the dictionary in this +example, subsequent calls to the function will refer to this changed object. + +By definition, immutable objects such as numbers, strings, tuples, and ``None``, +are safe from change. Changes to mutable objects such as dictionaries, lists, +and class instances can lead to confusion. + +Because of this feature, it is good programming practice to not use mutable +objects as default values. Instead, use ``None`` as the default value and +inside the function, check if the parameter is ``None`` and create a new +list/dictionary/whatever if it is. For example, don't write:: + + def foo(mydict={}): + ... + +but:: + + def foo(mydict=None): + if mydict is None: + mydict = {} # create a new dict for local namespace + +This feature can be useful. When you have a function that's time-consuming to +compute, a common technique is to cache the parameters and the resulting value +of each call to the function, and return the cached value if the same value is +requested again. This is called "memoizing", and can be implemented like this:: + + # Callers can only provide two parameters and optionally pass _cache by keyword + def expensive(arg1, arg2, *, _cache={}): + if (arg1, arg2) in _cache: + return _cache[(arg1, arg2)] + + # Calculate the value + result = ... expensive computation ... + _cache[(arg1, arg2)] = result # Store result in the cache + return result + +You could use a global variable containing a dictionary instead of the default +value; it's a matter of taste. + + +How can I pass optional or keyword parameters from one function to another? +--------------------------------------------------------------------------- + +Collect the arguments using the ``*`` and ``**`` specifiers in the function's +parameter list; this gives you the positional arguments as a tuple and the +keyword arguments as a dictionary. You can then pass these arguments when +calling another function by using ``*`` and ``**``:: + + def f(x, *args, **kwargs): + ... + kwargs['width'] = '14.3c' + ... + g(x, *args, **kwargs) + + +.. index:: + single: argument; difference from parameter + single: parameter; difference from argument + +.. _faq-argument-vs-parameter: + +What is the difference between arguments and parameters? +-------------------------------------------------------- + +:term:`Parameters <parameter>` are defined by the names that appear in a +function definition, whereas :term:`arguments <argument>` are the values +actually passed to a function when calling it. Parameters define what types of +arguments a function can accept. For example, given the function definition:: + + def func(foo, bar=None, **kwargs): + pass + +*foo*, *bar* and *kwargs* are parameters of ``func``. However, when calling +``func``, for example:: + + func(42, bar=314, extra=somevar) + +the values ``42``, ``314``, and ``somevar`` are arguments. + + +Why did changing list 'y' also change list 'x'? +------------------------------------------------ + +If you wrote code like:: + + >>> x = [] + >>> y = x + >>> y.append(10) + >>> y + [10] + >>> x + [10] + +you might be wondering why appending an element to ``y`` changed ``x`` too. + +There are two factors that produce this result: + +1) Variables are simply names that refer to objects. Doing ``y = x`` doesn't + create a copy of the list -- it creates a new variable ``y`` that refers to + the same object ``x`` refers to. This means that there is only one object + (the list), and both ``x`` and ``y`` refer to it. +2) Lists are :term:`mutable`, which means that you can change their content. + +After the call to :meth:`~list.append`, the content of the mutable object has +changed from ``[]`` to ``[10]``. Since both the variables refer to the same +object, using either name accesses the modified value ``[10]``. + +If we instead assign an immutable object to ``x``:: + + >>> x = 5 # ints are immutable + >>> y = x + >>> x = x + 1 # 5 can't be mutated, we are creating a new object here + >>> x + 6 + >>> y + 5 + +we can see that in this case ``x`` and ``y`` are not equal anymore. This is +because integers are :term:`immutable`, and when we do ``x = x + 1`` we are not +mutating the int ``5`` by incrementing its value; instead, we are creating a +new object (the int ``6``) and assigning it to ``x`` (that is, changing which +object ``x`` refers to). After this assignment we have two objects (the ints +``6`` and ``5``) and two variables that refer to them (``x`` now refers to +``6`` but ``y`` still refers to ``5``). + +Some operations (for example ``y.append(10)`` and ``y.sort()``) mutate the +object, whereas superficially similar operations (for example ``y = y + [10]`` +and ``sorted(y)``) create a new object. In general in Python (and in all cases +in the standard library) a method that mutates an object will return ``None`` +to help avoid getting the two types of operations confused. So if you +mistakenly write ``y.sort()`` thinking it will give you a sorted copy of ``y``, +you'll instead end up with ``None``, which will likely cause your program to +generate an easily diagnosed error. + +However, there is one class of operations where the same operation sometimes +has different behaviors with different types: the augmented assignment +operators. For example, ``+=`` mutates lists but not tuples or ints (``a_list ++= [1, 2, 3]`` is equivalent to ``a_list.extend([1, 2, 3])`` and mutates +``a_list``, whereas ``some_tuple += (1, 2, 3)`` and ``some_int += 1`` create +new objects). + +In other words: + +* If we have a mutable object (:class:`list`, :class:`dict`, :class:`set`, + etc.), we can use some specific operations to mutate it and all the variables + that refer to it will see the change. +* If we have an immutable object (:class:`str`, :class:`int`, :class:`tuple`, + etc.), all the variables that refer to it will always see the same value, + but operations that transform that value into a new value always return a new + object. + +If you want to know if two variables refer to the same object or not, you can +use the :keyword:`is` operator, or the built-in function :func:`id`. + + +How do I write a function with output parameters (call by reference)? +--------------------------------------------------------------------- + +Remember that arguments are passed by assignment in Python. Since assignment +just creates references to objects, there's no alias between an argument name in +the caller and callee, and so no call-by-reference per se. You can achieve the +desired effect in a number of ways. + +1) By returning a tuple of the results:: + + def func2(a, b): + a = 'new-value' # a and b are local names + b = b + 1 # assigned to new objects + return a, b # return new values + + x, y = 'old-value', 99 + x, y = func2(x, y) + print(x, y) # output: new-value 100 + + This is almost always the clearest solution. + +2) By using global variables. This isn't thread-safe, and is not recommended. + +3) By passing a mutable (changeable in-place) object:: + + def func1(a): + a[0] = 'new-value' # 'a' references a mutable list + a[1] = a[1] + 1 # changes a shared object + + args = ['old-value', 99] + func1(args) + print(args[0], args[1]) # output: new-value 100 + +4) By passing in a dictionary that gets mutated:: + + def func3(args): + args['a'] = 'new-value' # args is a mutable dictionary + args['b'] = args['b'] + 1 # change it in-place + + args = {'a': 'old-value', 'b': 99} + func3(args) + print(args['a'], args['b']) + +5) Or bundle up values in a class instance:: + + class callByRef: + def __init__(self, /, **args): + for key, value in args.items(): + setattr(self, key, value) + + def func4(args): + args.a = 'new-value' # args is a mutable callByRef + args.b = args.b + 1 # change object in-place + + args = callByRef(a='old-value', b=99) + func4(args) + print(args.a, args.b) + + + There's almost never a good reason to get this complicated. + +Your best choice is to return a tuple containing the multiple results. + + +How do you make a higher order function in Python? +-------------------------------------------------- + +You have two choices: you can use nested scopes or you can use callable objects. +For example, suppose you wanted to define ``linear(a,b)`` which returns a +function ``f(x)`` that computes the value ``a*x+b``. Using nested scopes:: + + def linear(a, b): + def result(x): + return a * x + b + return result + +Or using a callable object:: + + class linear: + + def __init__(self, a, b): + self.a, self.b = a, b + + def __call__(self, x): + return self.a * x + self.b + +In both cases, :: + + taxes = linear(0.3, 2) + +gives a callable object where ``taxes(10e6) == 0.3 * 10e6 + 2``. + +The callable object approach has the disadvantage that it is a bit slower and +results in slightly longer code. However, note that a collection of callables +can share their signature via inheritance:: + + class exponential(linear): + # __init__ inherited + def __call__(self, x): + return self.a * (x ** self.b) + +Object can encapsulate state for several methods:: + + class counter: + + value = 0 + + def set(self, x): + self.value = x + + def up(self): + self.value = self.value + 1 + + def down(self): + self.value = self.value - 1 + + count = counter() + inc, dec, reset = count.up, count.down, count.set + +Here ``inc()``, ``dec()`` and ``reset()`` act like functions which share the +same counting variable. + + +How do I copy an object in Python? +---------------------------------- + +In general, try :func:`copy.copy` or :func:`copy.deepcopy` for the general case. +Not all objects can be copied, but most can. + +Some objects can be copied more easily. Dictionaries have a :meth:`~dict.copy` +method:: + + newdict = olddict.copy() + +Sequences can be copied by slicing:: + + new_l = l[:] + + +How can I find the methods or attributes of an object? +------------------------------------------------------ + +For an instance x of a user-defined class, ``dir(x)`` returns an alphabetized +list of the names containing the instance attributes and methods and attributes +defined by its class. + + +How can my code discover the name of an object? +----------------------------------------------- + +Generally speaking, it can't, because objects don't really have names. +Essentially, assignment always binds a name to a value; the same is true of +``def`` and ``class`` statements, but in that case the value is a +callable. Consider the following code:: + + >>> class A: + ... pass + ... + >>> B = A + >>> a = B() + >>> b = a + >>> print(b) + <__main__.A object at 0x16D07CC> + >>> print(a) + <__main__.A object at 0x16D07CC> + +Arguably the class has a name: even though it is bound to two names and invoked +through the name B the created instance is still reported as an instance of +class A. However, it is impossible to say whether the instance's name is a or +b, since both names are bound to the same value. + +Generally speaking it should not be necessary for your code to "know the names" +of particular values. Unless you are deliberately writing introspective +programs, this is usually an indication that a change of approach might be +beneficial. + +In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to +this question: + + The same way as you get the name of that cat you found on your porch: the cat + (object) itself cannot tell you its name, and it doesn't really care -- so + the only way to find out what it's called is to ask all your neighbours + (namespaces) if it's their cat (object)... + + ....and don't be surprised if you'll find that it's known by many names, or + no name at all! + + +What's up with the comma operator's precedence? +----------------------------------------------- + +Comma is not an operator in Python. Consider this session:: + + >>> "a" in "b", "a" + (False, 'a') + +Since the comma is not an operator, but a separator between expressions the +above is evaluated as if you had entered:: + + ("a" in "b"), "a" + +not:: + + "a" in ("b", "a") + +The same is true of the various assignment operators (``=``, ``+=`` etc). They +are not truly operators but syntactic delimiters in assignment statements. + + +Is there an equivalent of C's "?:" ternary operator? +---------------------------------------------------- + +Yes, there is. The syntax is as follows:: + + [on_true] if [expression] else [on_false] + + x, y = 50, 25 + small = x if x < y else y + +Before this syntax was introduced in Python 2.5, a common idiom was to use +logical operators:: + + [expression] and [on_true] or [on_false] + +However, this idiom is unsafe, as it can give wrong results when *on_true* +has a false boolean value. Therefore, it is always better to use +the ``... if ... else ...`` form. + + +Is it possible to write obfuscated one-liners in Python? +-------------------------------------------------------- + +Yes. Usually this is done by nesting :keyword:`lambda` within +:keyword:`!lambda`. See the following three examples, due to Ulf Bartelt:: + + from functools import reduce + + # Primes < 1000 + print(list(filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0, + map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000))))) + + # First 10 Fibonacci numbers + print(list(map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1: + f(x,f), range(10)))) + + # Mandelbrot set + print((lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y, + Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM, + Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro, + i=i,Sx=Sx,F=lambda xc,yc,x,y,k,f=lambda xc,yc,x,y,k,f:(k<=0)or (x*x+y*y + >=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr( + 64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy + ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24)) + # \___ ___/ \___ ___/ | | |__ lines on screen + # V V | |______ columns on screen + # | | |__________ maximum of "iterations" + # | |_________________ range on y axis + # |____________________________ range on x axis + +Don't try this at home, kids! + + +.. _faq-positional-only-arguments: + +What does the slash(/) in the parameter list of a function mean? +---------------------------------------------------------------- + +A slash in the argument list of a function denotes that the parameters prior to +it are positional-only. Positional-only parameters are the ones without an +externally-usable name. Upon calling a function that accepts positional-only +parameters, arguments are mapped to parameters based solely on their position. +For example, :func:`divmod` is a function that accepts positional-only +parameters. Its documentation looks like this:: + + >>> help(divmod) + Help on built-in function divmod in module builtins: + + divmod(x, y, /) + Return the tuple (x//y, x%y). Invariant: div*y + mod == x. + +The slash at the end of the parameter list means that both parameters are +positional-only. Thus, calling :func:`divmod` with keyword arguments would lead +to an error:: + + >>> divmod(x=3, y=4) + Traceback (most recent call last): + File "<stdin>", line 1, in <module> + TypeError: divmod() takes no keyword arguments + + +Numbers and strings +=================== + +How do I specify hexadecimal and octal integers? +------------------------------------------------ + +To specify an octal digit, precede the octal value with a zero, and then a lower +or uppercase "o". For example, to set the variable "a" to the octal value "10" +(8 in decimal), type:: + + >>> a = 0o10 + >>> a + 8 + +Hexadecimal is just as easy. Simply precede the hexadecimal number with a zero, +and then a lower or uppercase "x". Hexadecimal digits can be specified in lower +or uppercase. For example, in the Python interpreter:: + + >>> a = 0xa5 + >>> a + 165 + >>> b = 0XB2 + >>> b + 178 + + +Why does -22 // 10 return -3? +----------------------------- + +It's primarily driven by the desire that ``i % j`` have the same sign as ``j``. +If you want that, and also want:: + + i == (i // j) * j + (i % j) + +then integer division has to return the floor. C also requires that identity to +hold, and then compilers that truncate ``i // j`` need to make ``i % j`` have +the same sign as ``i``. + +There are few real use cases for ``i % j`` when ``j`` is negative. When ``j`` +is positive, there are many, and in virtually all of them it's more useful for +``i % j`` to be ``>= 0``. If the clock says 10 now, what did it say 200 hours +ago? ``-190 % 12 == 2`` is useful; ``-190 % 12 == -10`` is a bug waiting to +bite. + + +How do I convert a string to a number? +-------------------------------------- + +For integers, use the built-in :func:`int` type constructor, e.g. ``int('144') +== 144``. Similarly, :func:`float` converts to floating-point, +e.g. ``float('144') == 144.0``. + +By default, these interpret the number as decimal, so that ``int('0144') == +144`` holds true, and ``int('0x144')`` raises :exc:`ValueError`. ``int(string, +base)`` takes the base to convert from as a second optional argument, so ``int( +'0x144', 16) == 324``. If the base is specified as 0, the number is interpreted +using Python's rules: a leading '0o' indicates octal, and '0x' indicates a hex +number. + +Do not use the built-in function :func:`eval` if all you need is to convert +strings to numbers. :func:`eval` will be significantly slower and it presents a +security risk: someone could pass you a Python expression that might have +unwanted side effects. For example, someone could pass +``__import__('os').system("rm -rf $HOME")`` which would erase your home +directory. + +:func:`eval` also has the effect of interpreting numbers as Python expressions, +so that e.g. ``eval('09')`` gives a syntax error because Python does not allow +leading '0' in a decimal number (except '0'). + + +How do I convert a number to a string? +-------------------------------------- + +To convert, e.g., the number 144 to the string '144', use the built-in type +constructor :func:`str`. If you want a hexadecimal or octal representation, use +the built-in functions :func:`hex` or :func:`oct`. For fancy formatting, see +the :ref:`f-strings` and :ref:`formatstrings` sections, +e.g. ``"{:04d}".format(144)`` yields +``'0144'`` and ``"{:.3f}".format(1.0/3.0)`` yields ``'0.333'``. + + +How do I modify a string in place? +---------------------------------- + +You can't, because strings are immutable. In most situations, you should +simply construct a new string from the various parts you want to assemble +it from. However, if you need an object with the ability to modify in-place +unicode data, try using an :class:`io.StringIO` object or the :mod:`array` +module:: + + >>> import io + >>> s = "Hello, world" + >>> sio = io.StringIO(s) + >>> sio.getvalue() + 'Hello, world' + >>> sio.seek(7) + 7 + >>> sio.write("there!") + 6 + >>> sio.getvalue() + 'Hello, there!' + + >>> import array + >>> a = array.array('u', s) + >>> print(a) + array('u', 'Hello, world') + >>> a[0] = 'y' + >>> print(a) + array('u', 'yello, world') + >>> a.tounicode() + 'yello, world' + + +How do I use strings to call functions/methods? +----------------------------------------------- + +There are various techniques. + +* The best is to use a dictionary that maps strings to functions. The primary + advantage of this technique is that the strings do not need to match the names + of the functions. This is also the primary technique used to emulate a case + construct:: + + def a(): + pass + + def b(): + pass + + dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs + + dispatch[get_input()]() # Note trailing parens to call function + +* Use the built-in function :func:`getattr`:: + + import foo + getattr(foo, 'bar')() + + Note that :func:`getattr` works on any object, including classes, class + instances, modules, and so on. + + This is used in several places in the standard library, like this:: + + class Foo: + def do_foo(self): + ... + + def do_bar(self): + ... + + f = getattr(foo_instance, 'do_' + opname) + f() + + +* Use :func:`locals` or :func:`eval` to resolve the function name:: + + def myFunc(): + print("hello") + + fname = "myFunc" + + f = locals()[fname] + f() + + f = eval(fname) + f() + + Note: Using :func:`eval` is slow and dangerous. If you don't have absolute + control over the contents of the string, someone could pass a string that + resulted in an arbitrary function being executed. + +Is there an equivalent to Perl's chomp() for removing trailing newlines from strings? +------------------------------------------------------------------------------------- + +You can use ``S.rstrip("\r\n")`` to remove all occurrences of any line +terminator from the end of the string ``S`` without removing other trailing +whitespace. If the string ``S`` represents more than one line, with several +empty lines at the end, the line terminators for all the blank lines will +be removed:: + + >>> lines = ("line 1 \r\n" + ... "\r\n" + ... "\r\n") + >>> lines.rstrip("\n\r") + 'line 1 ' + +Since this is typically only desired when reading text one line at a time, using +``S.rstrip()`` this way works well. + + +Is there a scanf() or sscanf() equivalent? +------------------------------------------ + +Not as such. + +For simple input parsing, the easiest approach is usually to split the line into +whitespace-delimited words using the :meth:`~str.split` method of string objects +and then convert decimal strings to numeric values using :func:`int` or +:func:`float`. ``split()`` supports an optional "sep" parameter which is useful +if the line uses something other than whitespace as a separator. + +For more complicated input parsing, regular expressions are more powerful +than C's :c:func:`sscanf` and better suited for the task. + + +What does 'UnicodeDecodeError' or 'UnicodeEncodeError' error mean? +------------------------------------------------------------------- + +See the :ref:`unicode-howto`. + + +Performance +=========== + +My program is too slow. How do I speed it up? +--------------------------------------------- + +That's a tough one, in general. First, here are a list of things to +remember before diving further: + +* Performance characteristics vary across Python implementations. This FAQ + focuses on :term:`CPython`. +* Behaviour can vary across operating systems, especially when talking about + I/O or multi-threading. +* You should always find the hot spots in your program *before* attempting to + optimize any code (see the :mod:`profile` module). +* Writing benchmark scripts will allow you to iterate quickly when searching + for improvements (see the :mod:`timeit` module). +* It is highly recommended to have good code coverage (through unit testing + or any other technique) before potentially introducing regressions hidden + in sophisticated optimizations. + +That being said, there are many tricks to speed up Python code. Here are +some general principles which go a long way towards reaching acceptable +performance levels: + +* Making your algorithms faster (or changing to faster ones) can yield + much larger benefits than trying to sprinkle micro-optimization tricks + all over your code. + +* Use the right data structures. Study documentation for the :ref:`bltin-types` + and the :mod:`collections` module. + +* When the standard library provides a primitive for doing something, it is + likely (although not guaranteed) to be faster than any alternative you + may come up with. This is doubly true for primitives written in C, such + as builtins and some extension types. For example, be sure to use + either the :meth:`list.sort` built-in method or the related :func:`sorted` + function to do sorting (and see the :ref:`sortinghowto` for examples + of moderately advanced usage). + +* Abstractions tend to create indirections and force the interpreter to work + more. If the levels of indirection outweigh the amount of useful work + done, your program will be slower. You should avoid excessive abstraction, + especially under the form of tiny functions or methods (which are also often + detrimental to readability). + +If you have reached the limit of what pure Python can allow, there are tools +to take you further away. For example, `Cython <http://cython.org>`_ can +compile a slightly modified version of Python code into a C extension, and +can be used on many different platforms. Cython can take advantage of +compilation (and optional type annotations) to make your code significantly +faster than when interpreted. If you are confident in your C programming +skills, you can also :ref:`write a C extension module <extending-index>` +yourself. + +.. seealso:: + The wiki page devoted to `performance tips + <https://wiki.python.org/moin/PythonSpeed/PerformanceTips>`_. + +.. _efficient_string_concatenation: + +What is the most efficient way to concatenate many strings together? +-------------------------------------------------------------------- + +:class:`str` and :class:`bytes` objects are immutable, therefore concatenating +many strings together is inefficient as each concatenation creates a new +object. In the general case, the total runtime cost is quadratic in the +total string length. + +To accumulate many :class:`str` objects, the recommended idiom is to place +them into a list and call :meth:`str.join` at the end:: + + chunks = [] + for s in my_strings: + chunks.append(s) + result = ''.join(chunks) + +(another reasonably efficient idiom is to use :class:`io.StringIO`) + +To accumulate many :class:`bytes` objects, the recommended idiom is to extend +a :class:`bytearray` object using in-place concatenation (the ``+=`` operator):: + + result = bytearray() + for b in my_bytes_objects: + result += b + + +Sequences (Tuples/Lists) +======================== + +How do I convert between tuples and lists? +------------------------------------------ + +The type constructor ``tuple(seq)`` converts any sequence (actually, any +iterable) into a tuple with the same items in the same order. + +For example, ``tuple([1, 2, 3])`` yields ``(1, 2, 3)`` and ``tuple('abc')`` +yields ``('a', 'b', 'c')``. If the argument is a tuple, it does not make a copy +but returns the same object, so it is cheap to call :func:`tuple` when you +aren't sure that an object is already a tuple. + +The type constructor ``list(seq)`` converts any sequence or iterable into a list +with the same items in the same order. For example, ``list((1, 2, 3))`` yields +``[1, 2, 3]`` and ``list('abc')`` yields ``['a', 'b', 'c']``. If the argument +is a list, it makes a copy just like ``seq[:]`` would. + + +What's a negative index? +------------------------ + +Python sequences are indexed with positive numbers and negative numbers. For +positive numbers 0 is the first index 1 is the second index and so forth. For +negative indices -1 is the last index and -2 is the penultimate (next to last) +index and so forth. Think of ``seq[-n]`` as the same as ``seq[len(seq)-n]``. + +Using negative indices can be very convenient. For example ``S[:-1]`` is all of +the string except for its last character, which is useful for removing the +trailing newline from a string. + + +How do I iterate over a sequence in reverse order? +-------------------------------------------------- + +Use the :func:`reversed` built-in function, which is new in Python 2.4:: + + for x in reversed(sequence): + ... # do something with x ... + +This won't touch your original sequence, but build a new copy with reversed +order to iterate over. + +With Python 2.3, you can use an extended slice syntax:: + + for x in sequence[::-1]: + ... # do something with x ... + + +How do you remove duplicates from a list? +----------------------------------------- + +See the Python Cookbook for a long discussion of many ways to do this: + + https://code.activestate.com/recipes/52560/ + +If you don't mind reordering the list, sort it and then scan from the end of the +list, deleting duplicates as you go:: + + if mylist: + mylist.sort() + last = mylist[-1] + for i in range(len(mylist)-2, -1, -1): + if last == mylist[i]: + del mylist[i] + else: + last = mylist[i] + +If all elements of the list may be used as set keys (i.e. they are all +:term:`hashable`) this is often faster :: + + mylist = list(set(mylist)) + +This converts the list into a set, thereby removing duplicates, and then back +into a list. + + +How do you make an array in Python? +----------------------------------- + +Use a list:: + + ["this", 1, "is", "an", "array"] + +Lists are equivalent to C or Pascal arrays in their time complexity; the primary +difference is that a Python list can contain objects of many different types. + +The ``array`` module also provides methods for creating arrays of fixed types +with compact representations, but they are slower to index than lists. Also +note that the Numeric extensions and others define array-like structures with +various characteristics as well. + +To get Lisp-style linked lists, you can emulate cons cells using tuples:: + + lisp_list = ("like", ("this", ("example", None) ) ) + +If mutability is desired, you could use lists instead of tuples. Here the +analogue of lisp car is ``lisp_list[0]`` and the analogue of cdr is +``lisp_list[1]``. Only do this if you're sure you really need to, because it's +usually a lot slower than using Python lists. + + +.. _faq-multidimensional-list: + +How do I create a multidimensional list? +---------------------------------------- + +You probably tried to make a multidimensional array like this:: + + >>> A = [[None] * 2] * 3 + +This looks correct if you print it: + +.. testsetup:: + + A = [[None] * 2] * 3 + +.. doctest:: + + >>> A + [[None, None], [None, None], [None, None]] + +But when you assign a value, it shows up in multiple places: + +.. testsetup:: + + A = [[None] * 2] * 3 + +.. doctest:: + + >>> A[0][0] = 5 + >>> A + [[5, None], [5, None], [5, None]] + +The reason is that replicating a list with ``*`` doesn't create copies, it only +creates references to the existing objects. The ``*3`` creates a list +containing 3 references to the same list of length two. Changes to one row will +show in all rows, which is almost certainly not what you want. + +The suggested approach is to create a list of the desired length first and then +fill in each element with a newly created list:: + + A = [None] * 3 + for i in range(3): + A[i] = [None] * 2 + +This generates a list containing 3 different lists of length two. You can also +use a list comprehension:: + + w, h = 2, 3 + A = [[None] * w for i in range(h)] + +Or, you can use an extension that provides a matrix datatype; `NumPy +<http://www.numpy.org/>`_ is the best known. + + +How do I apply a method to a sequence of objects? +------------------------------------------------- + +Use a list comprehension:: + + result = [obj.method() for obj in mylist] + +.. _faq-augmented-assignment-tuple-error: + +Why does a_tuple[i] += ['item'] raise an exception when the addition works? +--------------------------------------------------------------------------- + +This is because of a combination of the fact that augmented assignment +operators are *assignment* operators, and the difference between mutable and +immutable objects in Python. + +This discussion applies in general when augmented assignment operators are +applied to elements of a tuple that point to mutable objects, but we'll use +a ``list`` and ``+=`` as our exemplar. + +If you wrote:: + + >>> a_tuple = (1, 2) + >>> a_tuple[0] += 1 + Traceback (most recent call last): + ... + TypeError: 'tuple' object does not support item assignment + +The reason for the exception should be immediately clear: ``1`` is added to the +object ``a_tuple[0]`` points to (``1``), producing the result object, ``2``, +but when we attempt to assign the result of the computation, ``2``, to element +``0`` of the tuple, we get an error because we can't change what an element of +a tuple points to. + +Under the covers, what this augmented assignment statement is doing is +approximately this:: + + >>> result = a_tuple[0] + 1 + >>> a_tuple[0] = result + Traceback (most recent call last): + ... + TypeError: 'tuple' object does not support item assignment + +It is the assignment part of the operation that produces the error, since a +tuple is immutable. + +When you write something like:: + + >>> a_tuple = (['foo'], 'bar') + >>> a_tuple[0] += ['item'] + Traceback (most recent call last): + ... + TypeError: 'tuple' object does not support item assignment + +The exception is a bit more surprising, and even more surprising is the fact +that even though there was an error, the append worked:: + + >>> a_tuple[0] + ['foo', 'item'] + +To see why this happens, you need to know that (a) if an object implements an +``__iadd__`` magic method, it gets called when the ``+=`` augmented assignment +is executed, and its return value is what gets used in the assignment statement; +and (b) for lists, ``__iadd__`` is equivalent to calling ``extend`` on the list +and returning the list. That's why we say that for lists, ``+=`` is a +"shorthand" for ``list.extend``:: + + >>> a_list = [] + >>> a_list += [1] + >>> a_list + [1] + +This is equivalent to:: + + >>> result = a_list.__iadd__([1]) + >>> a_list = result + +The object pointed to by a_list has been mutated, and the pointer to the +mutated object is assigned back to ``a_list``. The end result of the +assignment is a no-op, since it is a pointer to the same object that ``a_list`` +was previously pointing to, but the assignment still happens. + +Thus, in our tuple example what is happening is equivalent to:: + + >>> result = a_tuple[0].__iadd__(['item']) + >>> a_tuple[0] = result + Traceback (most recent call last): + ... + TypeError: 'tuple' object does not support item assignment + +The ``__iadd__`` succeeds, and thus the list is extended, but even though +``result`` points to the same object that ``a_tuple[0]`` already points to, +that final assignment still results in an error, because tuples are immutable. + + +I want to do a complicated sort: can you do a Schwartzian Transform in Python? +------------------------------------------------------------------------------ + +The technique, attributed to Randal Schwartz of the Perl community, sorts the +elements of a list by a metric which maps each element to its "sort value". In +Python, use the ``key`` argument for the :meth:`list.sort` method:: + + Isorted = L[:] + Isorted.sort(key=lambda s: int(s[10:15])) + + +How can I sort one list by values from another list? +---------------------------------------------------- + +Merge them into an iterator of tuples, sort the resulting list, and then pick +out the element you want. :: + + >>> list1 = ["what", "I'm", "sorting", "by"] + >>> list2 = ["something", "else", "to", "sort"] + >>> pairs = zip(list1, list2) + >>> pairs = sorted(pairs) + >>> pairs + [("I'm", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', 'something')] + >>> result = [x[1] for x in pairs] + >>> result + ['else', 'sort', 'to', 'something'] + + +An alternative for the last step is:: + + >>> result = [] + >>> for p in pairs: result.append(p[1]) + +If you find this more legible, you might prefer to use this instead of the final +list comprehension. However, it is almost twice as slow for long lists. Why? +First, the ``append()`` operation has to reallocate memory, and while it uses +some tricks to avoid doing that each time, it still has to do it occasionally, +and that costs quite a bit. Second, the expression "result.append" requires an +extra attribute lookup, and third, there's a speed reduction from having to make +all those function calls. + + +Objects +======= + +What is a class? +---------------- + +A class is the particular object type created by executing a class statement. +Class objects are used as templates to create instance objects, which embody +both the data (attributes) and code (methods) specific to a datatype. + +A class can be based on one or more other classes, called its base class(es). It +then inherits the attributes and methods of its base classes. This allows an +object model to be successively refined by inheritance. You might have a +generic ``Mailbox`` class that provides basic accessor methods for a mailbox, +and subclasses such as ``MboxMailbox``, ``MaildirMailbox``, ``OutlookMailbox`` +that handle various specific mailbox formats. + + +What is a method? +----------------- + +A method is a function on some object ``x`` that you normally call as +``x.name(arguments...)``. Methods are defined as functions inside the class +definition:: + + class C: + def meth(self, arg): + return arg * 2 + self.attribute + + +What is self? +------------- + +Self is merely a conventional name for the first argument of a method. A method +defined as ``meth(self, a, b, c)`` should be called as ``x.meth(a, b, c)`` for +some instance ``x`` of the class in which the definition occurs; the called +method will think it is called as ``meth(x, a, b, c)``. + +See also :ref:`why-self`. + + +How do I check if an object is an instance of a given class or of a subclass of it? +----------------------------------------------------------------------------------- + +Use the built-in function ``isinstance(obj, cls)``. You can check if an object +is an instance of any of a number of classes by providing a tuple instead of a +single class, e.g. ``isinstance(obj, (class1, class2, ...))``, and can also +check whether an object is one of Python's built-in types, e.g. +``isinstance(obj, str)`` or ``isinstance(obj, (int, float, complex))``. + +Note that most programs do not use :func:`isinstance` on user-defined classes +very often. If you are developing the classes yourself, a more proper +object-oriented style is to define methods on the classes that encapsulate a +particular behaviour, instead of checking the object's class and doing a +different thing based on what class it is. For example, if you have a function +that does something:: + + def search(obj): + if isinstance(obj, Mailbox): + ... # code to search a mailbox + elif isinstance(obj, Document): + ... # code to search a document + elif ... + +A better approach is to define a ``search()`` method on all the classes and just +call it:: + + class Mailbox: + def search(self): + ... # code to search a mailbox + + class Document: + def search(self): + ... # code to search a document + + obj.search() + + +What is delegation? +------------------- + +Delegation is an object oriented technique (also called a design pattern). +Let's say you have an object ``x`` and want to change the behaviour of just one +of its methods. You can create a new class that provides a new implementation +of the method you're interested in changing and delegates all other methods to +the corresponding method of ``x``. + +Python programmers can easily implement delegation. For example, the following +class implements a class that behaves like a file but converts all written data +to uppercase:: + + class UpperOut: + + def __init__(self, outfile): + self._outfile = outfile + + def write(self, s): + self._outfile.write(s.upper()) + + def __getattr__(self, name): + return getattr(self._outfile, name) + +Here the ``UpperOut`` class redefines the ``write()`` method to convert the +argument string to uppercase before calling the underlying +``self._outfile.write()`` method. All other methods are delegated to the +underlying ``self._outfile`` object. The delegation is accomplished via the +``__getattr__`` method; consult :ref:`the language reference <attribute-access>` +for more information about controlling attribute access. + +Note that for more general cases delegation can get trickier. When attributes +must be set as well as retrieved, the class must define a :meth:`__setattr__` +method too, and it must do so carefully. The basic implementation of +:meth:`__setattr__` is roughly equivalent to the following:: + + class X: + ... + def __setattr__(self, name, value): + self.__dict__[name] = value + ... + +Most :meth:`__setattr__` implementations must modify ``self.__dict__`` to store +local state for self without causing an infinite recursion. + + +How do I call a method defined in a base class from a derived class that overrides it? +-------------------------------------------------------------------------------------- + +Use the built-in :func:`super` function:: + + class Derived(Base): + def meth(self): + super(Derived, self).meth() + +For version prior to 3.0, you may be using classic classes: For a class +definition such as ``class Derived(Base): ...`` you can call method ``meth()`` +defined in ``Base`` (or one of ``Base``'s base classes) as ``Base.meth(self, +arguments...)``. Here, ``Base.meth`` is an unbound method, so you need to +provide the ``self`` argument. + + +How can I organize my code to make it easier to change the base class? +---------------------------------------------------------------------- + +You could define an alias for the base class, assign the real base class to it +before your class definition, and use the alias throughout your class. Then all +you have to change is the value assigned to the alias. Incidentally, this trick +is also handy if you want to decide dynamically (e.g. depending on availability +of resources) which base class to use. Example:: + + BaseAlias = <real base class> + + class Derived(BaseAlias): + def meth(self): + BaseAlias.meth(self) + ... + + +How do I create static class data and static class methods? +----------------------------------------------------------- + +Both static data and static methods (in the sense of C++ or Java) are supported +in Python. + +For static data, simply define a class attribute. To assign a new value to the +attribute, you have to explicitly use the class name in the assignment:: + + class C: + count = 0 # number of times C.__init__ called + + def __init__(self): + C.count = C.count + 1 + + def getcount(self): + return C.count # or return self.count + +``c.count`` also refers to ``C.count`` for any ``c`` such that ``isinstance(c, +C)`` holds, unless overridden by ``c`` itself or by some class on the base-class +search path from ``c.__class__`` back to ``C``. + +Caution: within a method of C, an assignment like ``self.count = 42`` creates a +new and unrelated instance named "count" in ``self``'s own dict. Rebinding of a +class-static data name must always specify the class whether inside a method or +not:: + + C.count = 314 + +Static methods are possible:: + + class C: + @staticmethod + def static(arg1, arg2, arg3): + # No 'self' parameter! + ... + +However, a far more straightforward way to get the effect of a static method is +via a simple module-level function:: + + def getcount(): + return C.count + +If your code is structured so as to define one class (or tightly related class +hierarchy) per module, this supplies the desired encapsulation. + + +How can I overload constructors (or methods) in Python? +------------------------------------------------------- + +This answer actually applies to all methods, but the question usually comes up +first in the context of constructors. + +In C++ you'd write + +.. code-block:: c + + class C { + C() { cout << "No arguments\n"; } + C(int i) { cout << "Argument is " << i << "\n"; } + } + +In Python you have to write a single constructor that catches all cases using +default arguments. For example:: + + class C: + def __init__(self, i=None): + if i is None: + print("No arguments") + else: + print("Argument is", i) + +This is not entirely equivalent, but close enough in practice. + +You could also try a variable-length argument list, e.g. :: + + def __init__(self, *args): + ... + +The same approach works for all method definitions. + + +I try to use __spam and I get an error about _SomeClassName__spam. +------------------------------------------------------------------ + +Variable names with double leading underscores are "mangled" to provide a simple +but effective way to define class private variables. Any identifier of the form +``__spam`` (at least two leading underscores, at most one trailing underscore) +is textually replaced with ``_classname__spam``, where ``classname`` is the +current class name with any leading underscores stripped. + +This doesn't guarantee privacy: an outside user can still deliberately access +the "_classname__spam" attribute, and private values are visible in the object's +``__dict__``. Many Python programmers never bother to use private variable +names at all. + + +My class defines __del__ but it is not called when I delete the object. +----------------------------------------------------------------------- + +There are several possible reasons for this. + +The del statement does not necessarily call :meth:`__del__` -- it simply +decrements the object's reference count, and if this reaches zero +:meth:`__del__` is called. + +If your data structures contain circular links (e.g. a tree where each child has +a parent reference and each parent has a list of children) the reference counts +will never go back to zero. Once in a while Python runs an algorithm to detect +such cycles, but the garbage collector might run some time after the last +reference to your data structure vanishes, so your :meth:`__del__` method may be +called at an inconvenient and random time. This is inconvenient if you're trying +to reproduce a problem. Worse, the order in which object's :meth:`__del__` +methods are executed is arbitrary. You can run :func:`gc.collect` to force a +collection, but there *are* pathological cases where objects will never be +collected. + +Despite the cycle collector, it's still a good idea to define an explicit +``close()`` method on objects to be called whenever you're done with them. The +``close()`` method can then remove attributes that refer to subobjects. Don't +call :meth:`__del__` directly -- :meth:`__del__` should call ``close()`` and +``close()`` should make sure that it can be called more than once for the same +object. + +Another way to avoid cyclical references is to use the :mod:`weakref` module, +which allows you to point to objects without incrementing their reference count. +Tree data structures, for instance, should use weak references for their parent +and sibling references (if they need them!). + +.. XXX relevant for Python 3? + + If the object has ever been a local variable in a function that caught an + expression in an except clause, chances are that a reference to the object + still exists in that function's stack frame as contained in the stack trace. + Normally, calling :func:`sys.exc_clear` will take care of this by clearing + the last recorded exception. + +Finally, if your :meth:`__del__` method raises an exception, a warning message +is printed to :data:`sys.stderr`. + + +How do I get a list of all instances of a given class? +------------------------------------------------------ + +Python does not keep track of all instances of a class (or of a built-in type). +You can program the class's constructor to keep track of all instances by +keeping a list of weak references to each instance. + + +Why does the result of ``id()`` appear to be not unique? +-------------------------------------------------------- + +The :func:`id` builtin returns an integer that is guaranteed to be unique during +the lifetime of the object. Since in CPython, this is the object's memory +address, it happens frequently that after an object is deleted from memory, the +next freshly created object is allocated at the same position in memory. This +is illustrated by this example: + +>>> id(1000) # doctest: +SKIP +13901272 +>>> id(2000) # doctest: +SKIP +13901272 + +The two ids belong to different integer objects that are created before, and +deleted immediately after execution of the ``id()`` call. To be sure that +objects whose id you want to examine are still alive, create another reference +to the object: + +>>> a = 1000; b = 2000 +>>> id(a) # doctest: +SKIP +13901272 +>>> id(b) # doctest: +SKIP +13891296 + + +Modules +======= + +How do I create a .pyc file? +---------------------------- + +When a module is imported for the first time (or when the source file has +changed since the current compiled file was created) a ``.pyc`` file containing +the compiled code should be created in a ``__pycache__`` subdirectory of the +directory containing the ``.py`` file. The ``.pyc`` file will have a +filename that starts with the same name as the ``.py`` file, and ends with +``.pyc``, with a middle component that depends on the particular ``python`` +binary that created it. (See :pep:`3147` for details.) + +One reason that a ``.pyc`` file may not be created is a permissions problem +with the directory containing the source file, meaning that the ``__pycache__`` +subdirectory cannot be created. This can happen, for example, if you develop as +one user but run as another, such as if you are testing with a web server. + +Unless the :envvar:`PYTHONDONTWRITEBYTECODE` environment variable is set, +creation of a .pyc file is automatic if you're importing a module and Python +has the ability (permissions, free space, etc...) to create a ``__pycache__`` +subdirectory and write the compiled module to that subdirectory. + +Running Python on a top level script is not considered an import and no +``.pyc`` will be created. For example, if you have a top-level module +``foo.py`` that imports another module ``xyz.py``, when you run ``foo`` (by +typing ``python foo.py`` as a shell command), a ``.pyc`` will be created for +``xyz`` because ``xyz`` is imported, but no ``.pyc`` file will be created for +``foo`` since ``foo.py`` isn't being imported. + +If you need to create a ``.pyc`` file for ``foo`` -- that is, to create a +``.pyc`` file for a module that is not imported -- you can, using the +:mod:`py_compile` and :mod:`compileall` modules. + +The :mod:`py_compile` module can manually compile any module. One way is to use +the ``compile()`` function in that module interactively:: + + >>> import py_compile + >>> py_compile.compile('foo.py') # doctest: +SKIP + +This will write the ``.pyc`` to a ``__pycache__`` subdirectory in the same +location as ``foo.py`` (or you can override that with the optional parameter +``cfile``). + +You can also automatically compile all files in a directory or directories using +the :mod:`compileall` module. You can do it from the shell prompt by running +``compileall.py`` and providing the path of a directory containing Python files +to compile:: + + python -m compileall . + + +How do I find the current module name? +-------------------------------------- + +A module can find out its own module name by looking at the predefined global +variable ``__name__``. If this has the value ``'__main__'``, the program is +running as a script. Many modules that are usually used by importing them also +provide a command-line interface or a self-test, and only execute this code +after checking ``__name__``:: + + def main(): + print('Running test...') + ... + + if __name__ == '__main__': + main() + + +How can I have modules that mutually import each other? +------------------------------------------------------- + +Suppose you have the following modules: + +foo.py:: + + from bar import bar_var + foo_var = 1 + +bar.py:: + + from foo import foo_var + bar_var = 2 + +The problem is that the interpreter will perform the following steps: + +* main imports foo +* Empty globals for foo are created +* foo is compiled and starts executing +* foo imports bar +* Empty globals for bar are created +* bar is compiled and starts executing +* bar imports foo (which is a no-op since there already is a module named foo) +* bar.foo_var = foo.foo_var + +The last step fails, because Python isn't done with interpreting ``foo`` yet and +the global symbol dictionary for ``foo`` is still empty. + +The same thing happens when you use ``import foo``, and then try to access +``foo.foo_var`` in global code. + +There are (at least) three possible workarounds for this problem. + +Guido van Rossum recommends avoiding all uses of ``from <module> import ...``, +and placing all code inside functions. Initializations of global variables and +class variables should use constants or built-in functions only. This means +everything from an imported module is referenced as ``<module>.<name>``. + +Jim Roskind suggests performing steps in the following order in each module: + +* exports (globals, functions, and classes that don't need imported base + classes) +* ``import`` statements +* active code (including globals that are initialized from imported values). + +van Rossum doesn't like this approach much because the imports appear in a +strange place, but it does work. + +Matthias Urlichs recommends restructuring your code so that the recursive import +is not necessary in the first place. + +These solutions are not mutually exclusive. + + +__import__('x.y.z') returns <module 'x'>; how do I get z? +--------------------------------------------------------- + +Consider using the convenience function :func:`~importlib.import_module` from +:mod:`importlib` instead:: + + z = importlib.import_module('x.y.z') + + +When I edit an imported module and reimport it, the changes don't show up. Why does this happen? +------------------------------------------------------------------------------------------------- + +For reasons of efficiency as well as consistency, Python only reads the module +file on the first time a module is imported. If it didn't, in a program +consisting of many modules where each one imports the same basic module, the +basic module would be parsed and re-parsed many times. To force re-reading of a +changed module, do this:: + + import importlib + import modname + importlib.reload(modname) + +Warning: this technique is not 100% fool-proof. In particular, modules +containing statements like :: + + from modname import some_objects + +will continue to work with the old version of the imported objects. If the +module contains class definitions, existing class instances will *not* be +updated to use the new class definition. This can result in the following +paradoxical behaviour:: + + >>> import importlib + >>> import cls + >>> c = cls.C() # Create an instance of C + >>> importlib.reload(cls) + <module 'cls' from 'cls.py'> + >>> isinstance(c, cls.C) # isinstance is false?!? + False + +The nature of the problem is made clear if you print out the "identity" of the +class objects:: + + >>> hex(id(c.__class__)) + '0x7352a0' + >>> hex(id(cls.C)) + '0x4198d0' diff --git a/cpython_2/environment/repo/Doc/faq/python-video-icon.png b/cpython_2/environment/repo/Doc/faq/python-video-icon.png new file mode 100644 index 0000000000000000000000000000000000000000..957b633763f10f5f1510fedf76f9ae1a59d81b6f Binary files /dev/null and b/cpython_2/environment/repo/Doc/faq/python-video-icon.png differ diff --git a/cpython_2/environment/repo/Doc/faq/windows.rst b/cpython_2/environment/repo/Doc/faq/windows.rst new file mode 100644 index 0000000000000000000000000000000000000000..a181086e9ce6271b38f3316471de2417e010e3b9 --- /dev/null +++ b/cpython_2/environment/repo/Doc/faq/windows.rst @@ -0,0 +1,285 @@ +:tocdepth: 2 + +.. highlight:: none + +.. _windows-faq: + +===================== +Python on Windows FAQ +===================== + +.. only:: html + + .. contents:: + +.. XXX need review for Python 3. + XXX need review for Windows Vista/Seven? + +.. _faq-run-program-under-windows: + + +How do I run a Python program under Windows? +-------------------------------------------- + +This is not necessarily a straightforward question. If you are already familiar +with running programs from the Windows command line then everything will seem +obvious; otherwise, you might need a little more guidance. + +Unless you use some sort of integrated development environment, you will end up +*typing* Windows commands into what is variously referred to as a "DOS window" +or "Command prompt window". Usually you can create such a window from your +search bar by searching for ``cmd``. You should be able to recognize +when you have started such a window because you will see a Windows "command +prompt", which usually looks like this: + +.. code-block:: doscon + + C:\> + +The letter may be different, and there might be other things after it, so you +might just as easily see something like: + +.. code-block:: doscon + + D:\YourName\Projects\Python> + +depending on how your computer has been set up and what else you have recently +done with it. Once you have started such a window, you are well on the way to +running Python programs. + +You need to realize that your Python scripts have to be processed by another +program called the Python *interpreter*. The interpreter reads your script, +compiles it into bytecodes, and then executes the bytecodes to run your +program. So, how do you arrange for the interpreter to handle your Python? + +First, you need to make sure that your command window recognises the word +"py" as an instruction to start the interpreter. If you have opened a +command window, you should try entering the command ``py`` and hitting +return: + +.. code-block:: doscon + + C:\Users\YourName> py + +You should then see something like: + +.. code-block:: pycon + + Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32 + Type "help", "copyright", "credits" or "license" for more information. + >>> + +You have started the interpreter in "interactive mode". That means you can enter +Python statements or expressions interactively and have them executed or +evaluated while you wait. This is one of Python's strongest features. Check it +by entering a few expressions of your choice and seeing the results: + +.. code-block:: pycon + + >>> print("Hello") + Hello + >>> "Hello" * 3 + 'HelloHelloHello' + +Many people use the interactive mode as a convenient yet highly programmable +calculator. When you want to end your interactive Python session, +call the :func:`exit` function or hold the :kbd:`Ctrl` key down +while you enter a :kbd:`Z`, then hit the ":kbd:`Enter`" key to get +back to your Windows command prompt. + +You may also find that you have a Start-menu entry such as :menuselection:`Start +--> Programs --> Python 3.x --> Python (command line)` that results in you +seeing the ``>>>`` prompt in a new window. If so, the window will disappear +after you call the :func:`exit` function or enter the :kbd:`Ctrl-Z` +character; Windows is running a single "python" +command in the window, and closes it when you terminate the interpreter. + +Now that we know the ``py`` command is recognized, you can give your +Python script to it. You'll have to give either an absolute or a +relative path to the Python script. Let's say your Python script is +located in your desktop and is named ``hello.py``, and your command +prompt is nicely opened in your home directory so you're seeing something +similar to:: + + C:\Users\YourName> + +So now you'll ask the ``py`` command to give your script to Python by +typing ``py`` followed by your script path:: + + + C:\Users\YourName> py Desktop\hello.py + hello + +How do I make Python scripts executable? +---------------------------------------- + +On Windows, the standard Python installer already associates the .py +extension with a file type (Python.File) and gives that file type an open +command that runs the interpreter (``D:\Program Files\Python\python.exe "%1" +%*``). This is enough to make scripts executable from the command prompt as +'foo.py'. If you'd rather be able to execute the script by simple typing 'foo' +with no extension you need to add .py to the PATHEXT environment variable. + +Why does Python sometimes take so long to start? +------------------------------------------------ + +Usually Python starts very quickly on Windows, but occasionally there are bug +reports that Python suddenly begins to take a long time to start up. This is +made even more puzzling because Python will work fine on other Windows systems +which appear to be configured identically. + +The problem may be caused by a misconfiguration of virus checking software on +the problem machine. Some virus scanners have been known to introduce startup +overhead of two orders of magnitude when the scanner is configured to monitor +all reads from the filesystem. Try checking the configuration of virus scanning +software on your systems to ensure that they are indeed configured identically. +McAfee, when configured to scan all file system read activity, is a particular +offender. + + +How do I make an executable from a Python script? +------------------------------------------------- + +See `cx_Freeze <https://anthony-tuininga.github.io/cx_Freeze/>`_ for a distutils extension +that allows you to create console and GUI executables from Python code. +`py2exe <http://www.py2exe.org/>`_, the most popular extension for building +Python 2.x-based executables, does not yet support Python 3 but a version that +does is in development. + + +Is a ``*.pyd`` file the same as a DLL? +-------------------------------------- + +Yes, .pyd files are dll's, but there are a few differences. If you have a DLL +named ``foo.pyd``, then it must have a function ``PyInit_foo()``. You can then +write Python "import foo", and Python will search for foo.pyd (as well as +foo.py, foo.pyc) and if it finds it, will attempt to call ``PyInit_foo()`` to +initialize it. You do not link your .exe with foo.lib, as that would cause +Windows to require the DLL to be present. + +Note that the search path for foo.pyd is PYTHONPATH, not the same as the path +that Windows uses to search for foo.dll. Also, foo.pyd need not be present to +run your program, whereas if you linked your program with a dll, the dll is +required. Of course, foo.pyd is required if you want to say ``import foo``. In +a DLL, linkage is declared in the source code with ``__declspec(dllexport)``. +In a .pyd, linkage is defined in a list of available functions. + + +How can I embed Python into a Windows application? +-------------------------------------------------- + +Embedding the Python interpreter in a Windows app can be summarized as follows: + +1. Do _not_ build Python into your .exe file directly. On Windows, Python must + be a DLL to handle importing modules that are themselves DLL's. (This is the + first key undocumented fact.) Instead, link to :file:`python{NN}.dll`; it is + typically installed in ``C:\Windows\System``. *NN* is the Python version, a + number such as "33" for Python 3.3. + + You can link to Python in two different ways. Load-time linking means + linking against :file:`python{NN}.lib`, while run-time linking means linking + against :file:`python{NN}.dll`. (General note: :file:`python{NN}.lib` is the + so-called "import lib" corresponding to :file:`python{NN}.dll`. It merely + defines symbols for the linker.) + + Run-time linking greatly simplifies link options; everything happens at run + time. Your code must load :file:`python{NN}.dll` using the Windows + ``LoadLibraryEx()`` routine. The code must also use access routines and data + in :file:`python{NN}.dll` (that is, Python's C API's) using pointers obtained + by the Windows ``GetProcAddress()`` routine. Macros can make using these + pointers transparent to any C code that calls routines in Python's C API. + + Borland note: convert :file:`python{NN}.lib` to OMF format using Coff2Omf.exe + first. + + .. XXX what about static linking? + +2. If you use SWIG, it is easy to create a Python "extension module" that will + make the app's data and methods available to Python. SWIG will handle just + about all the grungy details for you. The result is C code that you link + *into* your .exe file (!) You do _not_ have to create a DLL file, and this + also simplifies linking. + +3. SWIG will create an init function (a C function) whose name depends on the + name of the extension module. For example, if the name of the module is leo, + the init function will be called initleo(). If you use SWIG shadow classes, + as you should, the init function will be called initleoc(). This initializes + a mostly hidden helper class used by the shadow class. + + The reason you can link the C code in step 2 into your .exe file is that + calling the initialization function is equivalent to importing the module + into Python! (This is the second key undocumented fact.) + +4. In short, you can use the following code to initialize the Python interpreter + with your extension module. + + .. code-block:: c + + #include "python.h" + ... + Py_Initialize(); // Initialize Python. + initmyAppc(); // Initialize (import) the helper class. + PyRun_SimpleString("import myApp"); // Import the shadow class. + +5. There are two problems with Python's C API which will become apparent if you + use a compiler other than MSVC, the compiler used to build pythonNN.dll. + + Problem 1: The so-called "Very High Level" functions that take FILE * + arguments will not work in a multi-compiler environment because each + compiler's notion of a struct FILE will be different. From an implementation + standpoint these are very _low_ level functions. + + Problem 2: SWIG generates the following code when generating wrappers to void + functions: + + .. code-block:: c + + Py_INCREF(Py_None); + _resultobj = Py_None; + return _resultobj; + + Alas, Py_None is a macro that expands to a reference to a complex data + structure called _Py_NoneStruct inside pythonNN.dll. Again, this code will + fail in a mult-compiler environment. Replace such code by: + + .. code-block:: c + + return Py_BuildValue(""); + + It may be possible to use SWIG's ``%typemap`` command to make the change + automatically, though I have not been able to get this to work (I'm a + complete SWIG newbie). + +6. Using a Python shell script to put up a Python interpreter window from inside + your Windows app is not a good idea; the resulting window will be independent + of your app's windowing system. Rather, you (or the wxPythonWindow class) + should create a "native" interpreter window. It is easy to connect that + window to the Python interpreter. You can redirect Python's i/o to _any_ + object that supports read and write, so all you need is a Python object + (defined in your extension module) that contains read() and write() methods. + +How do I keep editors from inserting tabs into my Python source? +---------------------------------------------------------------- + +The FAQ does not recommend using tabs, and the Python style guide, :pep:`8`, +recommends 4 spaces for distributed Python code; this is also the Emacs +python-mode default. + +Under any editor, mixing tabs and spaces is a bad idea. MSVC is no different in +this respect, and is easily configured to use spaces: Take :menuselection:`Tools +--> Options --> Tabs`, and for file type "Default" set "Tab size" and "Indent +size" to 4, and select the "Insert spaces" radio button. + +Python raises :exc:`IndentationError` or :exc:`TabError` if mixed tabs +and spaces are causing problems in leading whitespace. +You may also run the :mod:`tabnanny` module to check a directory tree +in batch mode. + + +How do I check for a keypress without blocking? +----------------------------------------------- + +Use the msvcrt module. This is a standard Windows-specific extension module. +It defines a function ``kbhit()`` which checks whether a keyboard hit is +present, and ``getch()`` which gets one character without echoing it. + diff --git a/cpython_2/environment/repo/Doc/glossary.rst b/cpython_2/environment/repo/Doc/glossary.rst new file mode 100644 index 0000000000000000000000000000000000000000..6189cb045049c2a20ee59fcf4aa27bfa60b52f17 --- /dev/null +++ b/cpython_2/environment/repo/Doc/glossary.rst @@ -0,0 +1,1155 @@ +.. _glossary: + +******** +Glossary +******** + +.. if you add new entries, keep the alphabetical sorting! + +.. glossary:: + + ``>>>`` + The default Python prompt of the interactive shell. Often seen for code + examples which can be executed interactively in the interpreter. + + ``...`` + Can refer to: + + * The default Python prompt of the interactive shell when entering the + code for an indented code block, when within a pair of matching left and + right delimiters (parentheses, square brackets, curly braces or triple + quotes), or after specifying a decorator. + + * The :const:`Ellipsis` built-in constant. + + 2to3 + A tool that tries to convert Python 2.x code to Python 3.x code by + handling most of the incompatibilities which can be detected by parsing the + source and traversing the parse tree. + + 2to3 is available in the standard library as :mod:`lib2to3`; a standalone + entry point is provided as :file:`Tools/scripts/2to3`. See + :ref:`2to3-reference`. + + abstract base class + Abstract base classes complement :term:`duck-typing` by + providing a way to define interfaces when other techniques like + :func:`hasattr` would be clumsy or subtly wrong (for example with + :ref:`magic methods <special-lookup>`). ABCs introduce virtual + subclasses, which are classes that don't inherit from a class but are + still recognized by :func:`isinstance` and :func:`issubclass`; see the + :mod:`abc` module documentation. Python comes with many built-in ABCs for + data structures (in the :mod:`collections.abc` module), numbers (in the + :mod:`numbers` module), streams (in the :mod:`io` module), import finders + and loaders (in the :mod:`importlib.abc` module). You can create your own + ABCs with the :mod:`abc` module. + + annotation + A label associated with a variable, a class + attribute or a function parameter or return value, + used by convention as a :term:`type hint`. + + Annotations of local variables cannot be accessed at runtime, but + annotations of global variables, class attributes, and functions + are stored in the :attr:`__annotations__` + special attribute of modules, classes, and functions, + respectively. + + See :term:`variable annotation`, :term:`function annotation`, :pep:`484` + and :pep:`526`, which describe this functionality. + + argument + A value passed to a :term:`function` (or :term:`method`) when calling the + function. There are two kinds of argument: + + * :dfn:`keyword argument`: an argument preceded by an identifier (e.g. + ``name=``) in a function call or passed as a value in a dictionary + preceded by ``**``. For example, ``3`` and ``5`` are both keyword + arguments in the following calls to :func:`complex`:: + + complex(real=3, imag=5) + complex(**{'real': 3, 'imag': 5}) + + * :dfn:`positional argument`: an argument that is not a keyword argument. + Positional arguments can appear at the beginning of an argument list + and/or be passed as elements of an :term:`iterable` preceded by ``*``. + For example, ``3`` and ``5`` are both positional arguments in the + following calls:: + + complex(3, 5) + complex(*(3, 5)) + + Arguments are assigned to the named local variables in a function body. + See the :ref:`calls` section for the rules governing this assignment. + Syntactically, any expression can be used to represent an argument; the + evaluated value is assigned to the local variable. + + See also the :term:`parameter` glossary entry, the FAQ question on + :ref:`the difference between arguments and parameters + <faq-argument-vs-parameter>`, and :pep:`362`. + + asynchronous context manager + An object which controls the environment seen in an + :keyword:`async with` statement by defining :meth:`__aenter__` and + :meth:`__aexit__` methods. Introduced by :pep:`492`. + + asynchronous generator + A function which returns an :term:`asynchronous generator iterator`. It + looks like a coroutine function defined with :keyword:`async def` except + that it contains :keyword:`yield` expressions for producing a series of + values usable in an :keyword:`async for` loop. + + Usually refers to an asynchronous generator function, but may refer to an + *asynchronous generator iterator* in some contexts. In cases where the + intended meaning isn't clear, using the full terms avoids ambiguity. + + An asynchronous generator function may contain :keyword:`await` + expressions as well as :keyword:`async for`, and :keyword:`async with` + statements. + + asynchronous generator iterator + An object created by a :term:`asynchronous generator` function. + + This is an :term:`asynchronous iterator` which when called using the + :meth:`__anext__` method returns an awaitable object which will execute + the body of the asynchronous generator function until the next + :keyword:`yield` expression. + + Each :keyword:`yield` temporarily suspends processing, remembering the + location execution state (including local variables and pending + try-statements). When the *asynchronous generator iterator* effectively + resumes with another awaitable returned by :meth:`__anext__`, it + picks up where it left off. See :pep:`492` and :pep:`525`. + + asynchronous iterable + An object, that can be used in an :keyword:`async for` statement. + Must return an :term:`asynchronous iterator` from its + :meth:`__aiter__` method. Introduced by :pep:`492`. + + asynchronous iterator + An object that implements the :meth:`__aiter__` and :meth:`__anext__` + methods. ``__anext__`` must return an :term:`awaitable` object. + :keyword:`async for` resolves the awaitables returned by an asynchronous + iterator's :meth:`__anext__` method until it raises a + :exc:`StopAsyncIteration` exception. Introduced by :pep:`492`. + + attribute + A value associated with an object which is referenced by name using + dotted expressions. For example, if an object *o* has an attribute + *a* it would be referenced as *o.a*. + + awaitable + An object that can be used in an :keyword:`await` expression. Can be + a :term:`coroutine` or an object with an :meth:`__await__` method. + See also :pep:`492`. + + BDFL + Benevolent Dictator For Life, a.k.a. `Guido van Rossum + <https://gvanrossum.github.io/>`_, Python's creator. + + binary file + A :term:`file object` able to read and write + :term:`bytes-like objects <bytes-like object>`. + Examples of binary files are files opened in binary mode (``'rb'``, + ``'wb'`` or ``'rb+'``), :data:`sys.stdin.buffer`, + :data:`sys.stdout.buffer`, and instances of :class:`io.BytesIO` and + :class:`gzip.GzipFile`. + + See also :term:`text file` for a file object able to read and write + :class:`str` objects. + + bytes-like object + An object that supports the :ref:`bufferobjects` and can + export a C-:term:`contiguous` buffer. This includes all :class:`bytes`, + :class:`bytearray`, and :class:`array.array` objects, as well as many + common :class:`memoryview` objects. Bytes-like objects can + be used for various operations that work with binary data; these include + compression, saving to a binary file, and sending over a socket. + + Some operations need the binary data to be mutable. The documentation + often refers to these as "read-write bytes-like objects". Example + mutable buffer objects include :class:`bytearray` and a + :class:`memoryview` of a :class:`bytearray`. + Other operations require the binary data to be stored in + immutable objects ("read-only bytes-like objects"); examples + of these include :class:`bytes` and a :class:`memoryview` + of a :class:`bytes` object. + + bytecode + Python source code is compiled into bytecode, the internal representation + of a Python program in the CPython interpreter. The bytecode is also + cached in ``.pyc`` files so that executing the same file is + faster the second time (recompilation from source to bytecode can be + avoided). This "intermediate language" is said to run on a + :term:`virtual machine` that executes the machine code corresponding to + each bytecode. Do note that bytecodes are not expected to work between + different Python virtual machines, nor to be stable between Python + releases. + + A list of bytecode instructions can be found in the documentation for + :ref:`the dis module <bytecodes>`. + + class + A template for creating user-defined objects. Class definitions + normally contain method definitions which operate on instances of the + class. + + class variable + A variable defined in a class and intended to be modified only at + class level (i.e., not in an instance of the class). + + coercion + The implicit conversion of an instance of one type to another during an + operation which involves two arguments of the same type. For example, + ``int(3.15)`` converts the floating point number to the integer ``3``, but + in ``3+4.5``, each argument is of a different type (one int, one float), + and both must be converted to the same type before they can be added or it + will raise a :exc:`TypeError`. Without coercion, all arguments of even + compatible types would have to be normalized to the same value by the + programmer, e.g., ``float(3)+4.5`` rather than just ``3+4.5``. + + complex number + An extension of the familiar real number system in which all numbers are + expressed as a sum of a real part and an imaginary part. Imaginary + numbers are real multiples of the imaginary unit (the square root of + ``-1``), often written ``i`` in mathematics or ``j`` in + engineering. Python has built-in support for complex numbers, which are + written with this latter notation; the imaginary part is written with a + ``j`` suffix, e.g., ``3+1j``. To get access to complex equivalents of the + :mod:`math` module, use :mod:`cmath`. Use of complex numbers is a fairly + advanced mathematical feature. If you're not aware of a need for them, + it's almost certain you can safely ignore them. + + context manager + An object which controls the environment seen in a :keyword:`with` + statement by defining :meth:`__enter__` and :meth:`__exit__` methods. + See :pep:`343`. + + context variable + A variable which can have different values depending on its context. + This is similar to Thread-Local Storage in which each execution + thread may have a different value for a variable. However, with context + variables, there may be several contexts in one execution thread and the + main usage for context variables is to keep track of variables in + concurrent asynchronous tasks. + See :mod:`contextvars`. + + contiguous + .. index:: C-contiguous, Fortran contiguous + + A buffer is considered contiguous exactly if it is either + *C-contiguous* or *Fortran contiguous*. Zero-dimensional buffers are + C and Fortran contiguous. In one-dimensional arrays, the items + must be laid out in memory next to each other, in order of + increasing indexes starting from zero. In multidimensional + C-contiguous arrays, the last index varies the fastest when + visiting items in order of memory address. However, in + Fortran contiguous arrays, the first index varies the fastest. + + coroutine + Coroutines are a more generalized form of subroutines. Subroutines are + entered at one point and exited at another point. Coroutines can be + entered, exited, and resumed at many different points. They can be + implemented with the :keyword:`async def` statement. See also + :pep:`492`. + + coroutine function + A function which returns a :term:`coroutine` object. A coroutine + function may be defined with the :keyword:`async def` statement, + and may contain :keyword:`await`, :keyword:`async for`, and + :keyword:`async with` keywords. These were introduced + by :pep:`492`. + + CPython + The canonical implementation of the Python programming language, as + distributed on `python.org <https://www.python.org>`_. The term "CPython" + is used when necessary to distinguish this implementation from others + such as Jython or IronPython. + + decorator + A function returning another function, usually applied as a function + transformation using the ``@wrapper`` syntax. Common examples for + decorators are :func:`classmethod` and :func:`staticmethod`. + + The decorator syntax is merely syntactic sugar, the following two + function definitions are semantically equivalent:: + + def f(...): + ... + f = staticmethod(f) + + @staticmethod + def f(...): + ... + + The same concept exists for classes, but is less commonly used there. See + the documentation for :ref:`function definitions <function>` and + :ref:`class definitions <class>` for more about decorators. + + descriptor + Any object which defines the methods :meth:`__get__`, :meth:`__set__`, or + :meth:`__delete__`. When a class attribute is a descriptor, its special + binding behavior is triggered upon attribute lookup. Normally, using + *a.b* to get, set or delete an attribute looks up the object named *b* in + the class dictionary for *a*, but if *b* is a descriptor, the respective + descriptor method gets called. Understanding descriptors is a key to a + deep understanding of Python because they are the basis for many features + including functions, methods, properties, class methods, static methods, + and reference to super classes. + + For more information about descriptors' methods, see :ref:`descriptors`. + + dictionary + An associative array, where arbitrary keys are mapped to values. The + keys can be any object with :meth:`__hash__` and :meth:`__eq__` methods. + Called a hash in Perl. + + dictionary view + The objects returned from :meth:`dict.keys`, :meth:`dict.values`, and + :meth:`dict.items` are called dictionary views. They provide a dynamic + view on the dictionary’s entries, which means that when the dictionary + changes, the view reflects these changes. To force the + dictionary view to become a full list use ``list(dictview)``. See + :ref:`dict-views`. + + docstring + A string literal which appears as the first expression in a class, + function or module. While ignored when the suite is executed, it is + recognized by the compiler and put into the :attr:`__doc__` attribute + of the enclosing class, function or module. Since it is available via + introspection, it is the canonical place for documentation of the + object. + + duck-typing + A programming style which does not look at an object's type to determine + if it has the right interface; instead, the method or attribute is simply + called or used ("If it looks like a duck and quacks like a duck, it + must be a duck.") By emphasizing interfaces rather than specific types, + well-designed code improves its flexibility by allowing polymorphic + substitution. Duck-typing avoids tests using :func:`type` or + :func:`isinstance`. (Note, however, that duck-typing can be complemented + with :term:`abstract base classes <abstract base class>`.) Instead, it + typically employs :func:`hasattr` tests or :term:`EAFP` programming. + + EAFP + Easier to ask for forgiveness than permission. This common Python coding + style assumes the existence of valid keys or attributes and catches + exceptions if the assumption proves false. This clean and fast style is + characterized by the presence of many :keyword:`try` and :keyword:`except` + statements. The technique contrasts with the :term:`LBYL` style + common to many other languages such as C. + + expression + A piece of syntax which can be evaluated to some value. In other words, + an expression is an accumulation of expression elements like literals, + names, attribute access, operators or function calls which all return a + value. In contrast to many other languages, not all language constructs + are expressions. There are also :term:`statement`\s which cannot be used + as expressions, such as :keyword:`while`. Assignments are also statements, + not expressions. + + extension module + A module written in C or C++, using Python's C API to interact with the + core and with user code. + + f-string + String literals prefixed with ``'f'`` or ``'F'`` are commonly called + "f-strings" which is short for + :ref:`formatted string literals <f-strings>`. See also :pep:`498`. + + file object + An object exposing a file-oriented API (with methods such as + :meth:`read()` or :meth:`write()`) to an underlying resource. Depending + on the way it was created, a file object can mediate access to a real + on-disk file or to another type of storage or communication device + (for example standard input/output, in-memory buffers, sockets, pipes, + etc.). File objects are also called :dfn:`file-like objects` or + :dfn:`streams`. + + There are actually three categories of file objects: raw + :term:`binary files <binary file>`, buffered + :term:`binary files <binary file>` and :term:`text files <text file>`. + Their interfaces are defined in the :mod:`io` module. The canonical + way to create a file object is by using the :func:`open` function. + + file-like object + A synonym for :term:`file object`. + + finder + An object that tries to find the :term:`loader` for a module that is + being imported. + + Since Python 3.3, there are two types of finder: :term:`meta path finders + <meta path finder>` for use with :data:`sys.meta_path`, and :term:`path + entry finders <path entry finder>` for use with :data:`sys.path_hooks`. + + See :pep:`302`, :pep:`420` and :pep:`451` for much more detail. + + floor division + Mathematical division that rounds down to nearest integer. The floor + division operator is ``//``. For example, the expression ``11 // 4`` + evaluates to ``2`` in contrast to the ``2.75`` returned by float true + division. Note that ``(-11) // 4`` is ``-3`` because that is ``-2.75`` + rounded *downward*. See :pep:`238`. + + function + A series of statements which returns some value to a caller. It can also + be passed zero or more :term:`arguments <argument>` which may be used in + the execution of the body. See also :term:`parameter`, :term:`method`, + and the :ref:`function` section. + + function annotation + An :term:`annotation` of a function parameter or return value. + + Function annotations are usually used for + :term:`type hints <type hint>`: for example, this function is expected to take two + :class:`int` arguments and is also expected to have an :class:`int` + return value:: + + def sum_two_numbers(a: int, b: int) -> int: + return a + b + + Function annotation syntax is explained in section :ref:`function`. + + See :term:`variable annotation` and :pep:`484`, + which describe this functionality. + + __future__ + A pseudo-module which programmers can use to enable new language features + which are not compatible with the current interpreter. + + By importing the :mod:`__future__` module and evaluating its variables, + you can see when a new feature was first added to the language and when it + becomes the default:: + + >>> import __future__ + >>> __future__.division + _Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192) + + garbage collection + The process of freeing memory when it is not used anymore. Python + performs garbage collection via reference counting and a cyclic garbage + collector that is able to detect and break reference cycles. The + garbage collector can be controlled using the :mod:`gc` module. + + .. index:: single: generator + + generator + A function which returns a :term:`generator iterator`. It looks like a + normal function except that it contains :keyword:`yield` expressions + for producing a series of values usable in a for-loop or that can be + retrieved one at a time with the :func:`next` function. + + Usually refers to a generator function, but may refer to a + *generator iterator* in some contexts. In cases where the intended + meaning isn't clear, using the full terms avoids ambiguity. + + generator iterator + An object created by a :term:`generator` function. + + Each :keyword:`yield` temporarily suspends processing, remembering the + location execution state (including local variables and pending + try-statements). When the *generator iterator* resumes, it picks up where + it left off (in contrast to functions which start fresh on every + invocation). + + .. index:: single: generator expression + + generator expression + An expression that returns an iterator. It looks like a normal expression + followed by a :keyword:`!for` clause defining a loop variable, range, + and an optional :keyword:`!if` clause. The combined expression + generates values for an enclosing function:: + + >>> sum(i*i for i in range(10)) # sum of squares 0, 1, 4, ... 81 + 285 + + generic function + A function composed of multiple functions implementing the same operation + for different types. Which implementation should be used during a call is + determined by the dispatch algorithm. + + See also the :term:`single dispatch` glossary entry, the + :func:`functools.singledispatch` decorator, and :pep:`443`. + + + GIL + See :term:`global interpreter lock`. + + global interpreter lock + The mechanism used by the :term:`CPython` interpreter to assure that + only one thread executes Python :term:`bytecode` at a time. + This simplifies the CPython implementation by making the object model + (including critical built-in types such as :class:`dict`) implicitly + safe against concurrent access. Locking the entire interpreter + makes it easier for the interpreter to be multi-threaded, at the + expense of much of the parallelism afforded by multi-processor + machines. + + However, some extension modules, either standard or third-party, + are designed so as to release the GIL when doing computationally-intensive + tasks such as compression or hashing. Also, the GIL is always released + when doing I/O. + + Past efforts to create a "free-threaded" interpreter (one which locks + shared data at a much finer granularity) have not been successful + because performance suffered in the common single-processor case. It + is believed that overcoming this performance issue would make the + implementation much more complicated and therefore costlier to maintain. + + + hash-based pyc + A bytecode cache file that uses the hash rather than the last-modified + time of the corresponding source file to determine its validity. See + :ref:`pyc-invalidation`. + + hashable + An object is *hashable* if it has a hash value which never changes during + its lifetime (it needs a :meth:`__hash__` method), and can be compared to + other objects (it needs an :meth:`__eq__` method). Hashable objects which + compare equal must have the same hash value. + + Hashability makes an object usable as a dictionary key and a set member, + because these data structures use the hash value internally. + + Most of Python's immutable built-in objects are hashable; mutable + containers (such as lists or dictionaries) are not; immutable + containers (such as tuples and frozensets) are only hashable if + their elements are hashable. Objects which are + instances of user-defined classes are hashable by default. They all + compare unequal (except with themselves), and their hash value is derived + from their :func:`id`. + + IDLE + An Integrated Development Environment for Python. IDLE is a basic editor + and interpreter environment which ships with the standard distribution of + Python. + + immutable + An object with a fixed value. Immutable objects include numbers, strings and + tuples. Such an object cannot be altered. A new object has to + be created if a different value has to be stored. They play an important + role in places where a constant hash value is needed, for example as a key + in a dictionary. + + import path + A list of locations (or :term:`path entries <path entry>`) that are + searched by the :term:`path based finder` for modules to import. During + import, this list of locations usually comes from :data:`sys.path`, but + for subpackages it may also come from the parent package's ``__path__`` + attribute. + + importing + The process by which Python code in one module is made available to + Python code in another module. + + importer + An object that both finds and loads a module; both a + :term:`finder` and :term:`loader` object. + + interactive + Python has an interactive interpreter which means you can enter + statements and expressions at the interpreter prompt, immediately + execute them and see their results. Just launch ``python`` with no + arguments (possibly by selecting it from your computer's main + menu). It is a very powerful way to test out new ideas or inspect + modules and packages (remember ``help(x)``). + + interpreted + Python is an interpreted language, as opposed to a compiled one, + though the distinction can be blurry because of the presence of the + bytecode compiler. This means that source files can be run directly + without explicitly creating an executable which is then run. + Interpreted languages typically have a shorter development/debug cycle + than compiled ones, though their programs generally also run more + slowly. See also :term:`interactive`. + + interpreter shutdown + When asked to shut down, the Python interpreter enters a special phase + where it gradually releases all allocated resources, such as modules + and various critical internal structures. It also makes several calls + to the :term:`garbage collector <garbage collection>`. This can trigger + the execution of code in user-defined destructors or weakref callbacks. + Code executed during the shutdown phase can encounter various + exceptions as the resources it relies on may not function anymore + (common examples are library modules or the warnings machinery). + + The main reason for interpreter shutdown is that the ``__main__`` module + or the script being run has finished executing. + + iterable + An object capable of returning its members one at a time. Examples of + iterables include all sequence types (such as :class:`list`, :class:`str`, + and :class:`tuple`) and some non-sequence types like :class:`dict`, + :term:`file objects <file object>`, and objects of any classes you define + with an :meth:`__iter__` method or with a :meth:`__getitem__` method + that implements :term:`Sequence` semantics. + + Iterables can be + used in a :keyword:`for` loop and in many other places where a sequence is + needed (:func:`zip`, :func:`map`, ...). When an iterable object is passed + as an argument to the built-in function :func:`iter`, it returns an + iterator for the object. This iterator is good for one pass over the set + of values. When using iterables, it is usually not necessary to call + :func:`iter` or deal with iterator objects yourself. The ``for`` + statement does that automatically for you, creating a temporary unnamed + variable to hold the iterator for the duration of the loop. See also + :term:`iterator`, :term:`sequence`, and :term:`generator`. + + iterator + An object representing a stream of data. Repeated calls to the iterator's + :meth:`~iterator.__next__` method (or passing it to the built-in function + :func:`next`) return successive items in the stream. When no more data + are available a :exc:`StopIteration` exception is raised instead. At this + point, the iterator object is exhausted and any further calls to its + :meth:`__next__` method just raise :exc:`StopIteration` again. Iterators + are required to have an :meth:`__iter__` method that returns the iterator + object itself so every iterator is also iterable and may be used in most + places where other iterables are accepted. One notable exception is code + which attempts multiple iteration passes. A container object (such as a + :class:`list`) produces a fresh new iterator each time you pass it to the + :func:`iter` function or use it in a :keyword:`for` loop. Attempting this + with an iterator will just return the same exhausted iterator object used + in the previous iteration pass, making it appear like an empty container. + + More information can be found in :ref:`typeiter`. + + key function + A key function or collation function is a callable that returns a value + used for sorting or ordering. For example, :func:`locale.strxfrm` is + used to produce a sort key that is aware of locale specific sort + conventions. + + A number of tools in Python accept key functions to control how elements + are ordered or grouped. They include :func:`min`, :func:`max`, + :func:`sorted`, :meth:`list.sort`, :func:`heapq.merge`, + :func:`heapq.nsmallest`, :func:`heapq.nlargest`, and + :func:`itertools.groupby`. + + There are several ways to create a key function. For example. the + :meth:`str.lower` method can serve as a key function for case insensitive + sorts. Alternatively, a key function can be built from a + :keyword:`lambda` expression such as ``lambda r: (r[0], r[2])``. Also, + the :mod:`operator` module provides three key function constructors: + :func:`~operator.attrgetter`, :func:`~operator.itemgetter`, and + :func:`~operator.methodcaller`. See the :ref:`Sorting HOW TO + <sortinghowto>` for examples of how to create and use key functions. + + keyword argument + See :term:`argument`. + + lambda + An anonymous inline function consisting of a single :term:`expression` + which is evaluated when the function is called. The syntax to create + a lambda function is ``lambda [parameters]: expression`` + + LBYL + Look before you leap. This coding style explicitly tests for + pre-conditions before making calls or lookups. This style contrasts with + the :term:`EAFP` approach and is characterized by the presence of many + :keyword:`if` statements. + + In a multi-threaded environment, the LBYL approach can risk introducing a + race condition between "the looking" and "the leaping". For example, the + code, ``if key in mapping: return mapping[key]`` can fail if another + thread removes *key* from *mapping* after the test, but before the lookup. + This issue can be solved with locks or by using the EAFP approach. + + list + A built-in Python :term:`sequence`. Despite its name it is more akin + to an array in other languages than to a linked list since access to + elements is O(1). + + list comprehension + A compact way to process all or part of the elements in a sequence and + return a list with the results. ``result = ['{:#04x}'.format(x) for x in + range(256) if x % 2 == 0]`` generates a list of strings containing + even hex numbers (0x..) in the range from 0 to 255. The :keyword:`if` + clause is optional. If omitted, all elements in ``range(256)`` are + processed. + + loader + An object that loads a module. It must define a method named + :meth:`load_module`. A loader is typically returned by a + :term:`finder`. See :pep:`302` for details and + :class:`importlib.abc.Loader` for an :term:`abstract base class`. + + magic method + .. index:: pair: magic; method + + An informal synonym for :term:`special method`. + + mapping + A container object that supports arbitrary key lookups and implements the + methods specified in the :class:`~collections.abc.Mapping` or + :class:`~collections.abc.MutableMapping` + :ref:`abstract base classes <collections-abstract-base-classes>`. Examples + include :class:`dict`, :class:`collections.defaultdict`, + :class:`collections.OrderedDict` and :class:`collections.Counter`. + + meta path finder + A :term:`finder` returned by a search of :data:`sys.meta_path`. Meta path + finders are related to, but different from :term:`path entry finders + <path entry finder>`. + + See :class:`importlib.abc.MetaPathFinder` for the methods that meta path + finders implement. + + metaclass + The class of a class. Class definitions create a class name, a class + dictionary, and a list of base classes. The metaclass is responsible for + taking those three arguments and creating the class. Most object oriented + programming languages provide a default implementation. What makes Python + special is that it is possible to create custom metaclasses. Most users + never need this tool, but when the need arises, metaclasses can provide + powerful, elegant solutions. They have been used for logging attribute + access, adding thread-safety, tracking object creation, implementing + singletons, and many other tasks. + + More information can be found in :ref:`metaclasses`. + + method + A function which is defined inside a class body. If called as an attribute + of an instance of that class, the method will get the instance object as + its first :term:`argument` (which is usually called ``self``). + See :term:`function` and :term:`nested scope`. + + method resolution order + Method Resolution Order is the order in which base classes are searched + for a member during lookup. See `The Python 2.3 Method Resolution Order + <https://www.python.org/download/releases/2.3/mro/>`_ for details of the + algorithm used by the Python interpreter since the 2.3 release. + + module + An object that serves as an organizational unit of Python code. Modules + have a namespace containing arbitrary Python objects. Modules are loaded + into Python by the process of :term:`importing`. + + See also :term:`package`. + + module spec + A namespace containing the import-related information used to load a + module. An instance of :class:`importlib.machinery.ModuleSpec`. + + MRO + See :term:`method resolution order`. + + mutable + Mutable objects can change their value but keep their :func:`id`. See + also :term:`immutable`. + + named tuple + The term "named tuple" applies to any type or class that inherits from + tuple and whose indexable elements are also accessible using named + attributes. The type or class may have other features as well. + + Several built-in types are named tuples, including the values returned + by :func:`time.localtime` and :func:`os.stat`. Another example is + :data:`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 + + Some named tuples are built-in types (such as the above examples). + Alternatively, a named tuple can be created from a regular class + definition that inherits from :class:`tuple` and that defines named + fields. Such a class can be written by hand or it can be created with + the factory function :func:`collections.namedtuple`. The latter + technique also adds some extra methods that may not be found in + hand-written or built-in named tuples. + + namespace + The place where a variable is stored. Namespaces are implemented as + dictionaries. There are the local, global and built-in namespaces as well + as nested namespaces in objects (in methods). Namespaces support + modularity by preventing naming conflicts. For instance, the functions + :func:`builtins.open <.open>` and :func:`os.open` are distinguished by + their namespaces. Namespaces also aid readability and maintainability by + making it clear which module implements a function. For instance, writing + :func:`random.seed` or :func:`itertools.islice` makes it clear that those + functions are implemented by the :mod:`random` and :mod:`itertools` + modules, respectively. + + namespace package + A :pep:`420` :term:`package` which serves only as a container for + subpackages. Namespace packages may have no physical representation, + and specifically are not like a :term:`regular package` because they + have no ``__init__.py`` file. + + See also :term:`module`. + + nested scope + The ability to refer to a variable in an enclosing definition. For + instance, a function defined inside another function can refer to + variables in the outer function. Note that nested scopes by default work + only for reference and not for assignment. Local variables both read and + write in the innermost scope. Likewise, global variables read and write + to the global namespace. The :keyword:`nonlocal` allows writing to outer + scopes. + + new-style class + Old name for the flavor of classes now used for all class objects. In + earlier Python versions, only new-style classes could use Python's newer, + versatile features like :attr:`~object.__slots__`, descriptors, + properties, :meth:`__getattribute__`, class methods, and static methods. + + object + Any data with state (attributes or value) and defined behavior + (methods). Also the ultimate base class of any :term:`new-style + class`. + + package + A Python :term:`module` which can contain submodules or recursively, + subpackages. Technically, a package is a Python module with an + ``__path__`` attribute. + + See also :term:`regular package` and :term:`namespace package`. + + parameter + A named entity in a :term:`function` (or method) definition that + specifies an :term:`argument` (or in some cases, arguments) that the + function can accept. There are five kinds of parameter: + + * :dfn:`positional-or-keyword`: specifies an argument that can be passed + either :term:`positionally <argument>` or as a :term:`keyword argument + <argument>`. This is the default kind of parameter, for example *foo* + and *bar* in the following:: + + def func(foo, bar=None): ... + + .. _positional-only_parameter: + + * :dfn:`positional-only`: specifies an argument that can be supplied only + by position. Positional-only parameters can be defined by including a + ``/`` character in the parameter list of the function definition after + them, for example *posonly1* and *posonly2* in the following:: + + def func(posonly1, posonly2, /, positional_or_keyword): ... + + .. _keyword-only_parameter: + + * :dfn:`keyword-only`: specifies an argument that can be supplied only + by keyword. Keyword-only parameters can be defined by including a + single var-positional parameter or bare ``*`` in the parameter list + of the function definition before them, for example *kw_only1* and + *kw_only2* in the following:: + + def func(arg, *, kw_only1, kw_only2): ... + + * :dfn:`var-positional`: specifies that an arbitrary sequence of + positional arguments can be provided (in addition to any positional + arguments already accepted by other parameters). Such a parameter can + be defined by prepending the parameter name with ``*``, for example + *args* in the following:: + + def func(*args, **kwargs): ... + + * :dfn:`var-keyword`: specifies that arbitrarily many keyword arguments + can be provided (in addition to any keyword arguments already accepted + by other parameters). Such a parameter can be defined by prepending + the parameter name with ``**``, for example *kwargs* in the example + above. + + Parameters can specify both optional and required arguments, as well as + default values for some optional arguments. + + See also the :term:`argument` glossary entry, the FAQ question on + :ref:`the difference between arguments and parameters + <faq-argument-vs-parameter>`, the :class:`inspect.Parameter` class, the + :ref:`function` section, and :pep:`362`. + + path entry + A single location on the :term:`import path` which the :term:`path + based finder` consults to find modules for importing. + + path entry finder + A :term:`finder` returned by a callable on :data:`sys.path_hooks` + (i.e. a :term:`path entry hook`) which knows how to locate modules given + a :term:`path entry`. + + See :class:`importlib.abc.PathEntryFinder` for the methods that path entry + finders implement. + + path entry hook + A callable on the :data:`sys.path_hook` list which returns a :term:`path + entry finder` if it knows how to find modules on a specific :term:`path + entry`. + + path based finder + One of the default :term:`meta path finders <meta path finder>` which + searches an :term:`import path` for modules. + + path-like object + An object representing a file system path. A path-like object is either + a :class:`str` or :class:`bytes` object representing a path, or an object + implementing the :class:`os.PathLike` protocol. An object that supports + the :class:`os.PathLike` protocol can be converted to a :class:`str` or + :class:`bytes` file system path by calling the :func:`os.fspath` function; + :func:`os.fsdecode` and :func:`os.fsencode` can be used to guarantee a + :class:`str` or :class:`bytes` result instead, respectively. Introduced + by :pep:`519`. + + PEP + Python Enhancement Proposal. A PEP is a design document + providing information to the Python community, or describing a new + feature for Python or its processes or environment. PEPs should + provide a concise technical specification and a rationale for proposed + features. + + PEPs are intended to be the primary mechanisms for proposing major new + features, for collecting community input on an issue, and for documenting + the design decisions that have gone into Python. The PEP author is + responsible for building consensus within the community and documenting + dissenting opinions. + + See :pep:`1`. + + portion + A set of files in a single directory (possibly stored in a zip file) + that contribute to a namespace package, as defined in :pep:`420`. + + positional argument + See :term:`argument`. + + provisional API + A provisional API is one which has been deliberately excluded from + the standard library's backwards compatibility guarantees. While major + changes to such interfaces are not expected, as long as they are marked + provisional, backwards incompatible changes (up to and including removal + of the interface) may occur if deemed necessary by core developers. Such + changes will not be made gratuitously -- they will occur only if serious + fundamental flaws are uncovered that were missed prior to the inclusion + of the API. + + Even for provisional APIs, backwards incompatible changes are seen as + a "solution of last resort" - every attempt will still be made to find + a backwards compatible resolution to any identified problems. + + This process allows the standard library to continue to evolve over + time, without locking in problematic design errors for extended periods + of time. See :pep:`411` for more details. + + provisional package + See :term:`provisional API`. + + Python 3000 + Nickname for the Python 3.x release line (coined long ago when the + release of version 3 was something in the distant future.) This is also + abbreviated "Py3k". + + Pythonic + An idea or piece of code which closely follows the most common idioms + of the Python language, rather than implementing code using concepts + common to other languages. For example, a common idiom in Python is + to loop over all elements of an iterable using a :keyword:`for` + statement. Many other languages don't have this type of construct, so + people unfamiliar with Python sometimes use a numerical counter instead:: + + for i in range(len(food)): + print(food[i]) + + As opposed to the cleaner, Pythonic method:: + + for piece in food: + print(piece) + + qualified name + A dotted name showing the "path" from a module's global scope to a + class, function or method defined in that module, as defined in + :pep:`3155`. For top-level functions and classes, the qualified name + is the same as the object's name:: + + >>> class C: + ... class D: + ... def meth(self): + ... pass + ... + >>> C.__qualname__ + 'C' + >>> C.D.__qualname__ + 'C.D' + >>> C.D.meth.__qualname__ + 'C.D.meth' + + When used to refer to modules, the *fully qualified name* means the + entire dotted path to the module, including any parent packages, + e.g. ``email.mime.text``:: + + >>> import email.mime.text + >>> email.mime.text.__name__ + 'email.mime.text' + + reference count + The number of references to an object. When the reference count of an + object drops to zero, it is deallocated. Reference counting is + generally not visible to Python code, but it is a key element of the + :term:`CPython` implementation. The :mod:`sys` module defines a + :func:`~sys.getrefcount` function that programmers can call to return the + reference count for a particular object. + + regular package + A traditional :term:`package`, such as a directory containing an + ``__init__.py`` file. + + See also :term:`namespace package`. + + __slots__ + A declaration inside a class that saves memory by pre-declaring space for + instance attributes and eliminating instance dictionaries. Though + popular, the technique is somewhat tricky to get right and is best + reserved for rare cases where there are large numbers of instances in a + memory-critical application. + + sequence + An :term:`iterable` which supports efficient element access using integer + indices via the :meth:`__getitem__` special method and defines a + :meth:`__len__` method that returns the length of the sequence. + Some built-in sequence types are :class:`list`, :class:`str`, + :class:`tuple`, and :class:`bytes`. Note that :class:`dict` also + supports :meth:`__getitem__` and :meth:`__len__`, but is considered a + mapping rather than a sequence because the lookups use arbitrary + :term:`immutable` keys rather than integers. + + The :class:`collections.abc.Sequence` abstract base class + defines a much richer interface that goes beyond just + :meth:`__getitem__` and :meth:`__len__`, adding :meth:`count`, + :meth:`index`, :meth:`__contains__`, and + :meth:`__reversed__`. Types that implement this expanded + interface can be registered explicitly using + :func:`~abc.register`. + + single dispatch + A form of :term:`generic function` dispatch where the implementation is + chosen based on the type of a single argument. + + slice + An object usually containing a portion of a :term:`sequence`. A slice is + created using the subscript notation, ``[]`` with colons between numbers + when several are given, such as in ``variable_name[1:3:5]``. The bracket + (subscript) notation uses :class:`slice` objects internally. + + special method + .. index:: pair: special; method + + A method that is called implicitly by Python to execute a certain + operation on a type, such as addition. Such methods have names starting + and ending with double underscores. Special methods are documented in + :ref:`specialnames`. + + statement + A statement is part of a suite (a "block" of code). A statement is either + an :term:`expression` or one of several constructs with a keyword, such + as :keyword:`if`, :keyword:`while` or :keyword:`for`. + + text encoding + A codec which encodes Unicode strings to bytes. + + text file + A :term:`file object` able to read and write :class:`str` objects. + Often, a text file actually accesses a byte-oriented datastream + and handles the :term:`text encoding` automatically. + Examples of text files are files opened in text mode (``'r'`` or ``'w'``), + :data:`sys.stdin`, :data:`sys.stdout`, and instances of + :class:`io.StringIO`. + + See also :term:`binary file` for a file object able to read and write + :term:`bytes-like objects <bytes-like object>`. + + triple-quoted string + A string which is bound by three instances of either a quotation mark + (") or an apostrophe ('). While they don't provide any functionality + not available with single-quoted strings, they are useful for a number + of reasons. They allow you to include unescaped single and double + quotes within a string and they can span multiple lines without the + use of the continuation character, making them especially useful when + writing docstrings. + + type + The type of a Python object determines what kind of object it is; every + object has a type. An object's type is accessible as its + :attr:`~instance.__class__` attribute or can be retrieved with + ``type(obj)``. + + type alias + A synonym for a type, created by assigning the type to an identifier. + + Type aliases are useful for simplifying :term:`type hints <type hint>`. + For example:: + + from typing import List, Tuple + + def remove_gray_shades( + colors: List[Tuple[int, int, int]]) -> List[Tuple[int, int, int]]: + pass + + could be made more readable like this:: + + from typing import List, Tuple + + Color = Tuple[int, int, int] + + def remove_gray_shades(colors: List[Color]) -> List[Color]: + pass + + See :mod:`typing` and :pep:`484`, which describe this functionality. + + type hint + An :term:`annotation` that specifies the expected type for a variable, a class + attribute, or a function parameter or return value. + + Type hints are optional and are not enforced by Python but + they are useful to static type analysis tools, and aid IDEs with code + completion and refactoring. + + Type hints of global variables, class attributes, and functions, + but not local variables, can be accessed using + :func:`typing.get_type_hints`. + + See :mod:`typing` and :pep:`484`, which describe this functionality. + + universal newlines + A manner of interpreting text streams in which all of the following are + recognized as ending a line: the Unix end-of-line convention ``'\n'``, + the Windows convention ``'\r\n'``, and the old Macintosh convention + ``'\r'``. See :pep:`278` and :pep:`3116`, as well as + :func:`bytes.splitlines` for an additional use. + + variable annotation + An :term:`annotation` of a variable or a class attribute. + + When annotating a variable or a class attribute, assignment is optional:: + + class C: + field: 'annotation' + + Variable annotations are usually used for + :term:`type hints <type hint>`: for example this variable is expected to take + :class:`int` values:: + + count: int = 0 + + Variable annotation syntax is explained in section :ref:`annassign`. + + See :term:`function annotation`, :pep:`484` + and :pep:`526`, which describe this functionality. + + virtual environment + A cooperatively isolated runtime environment that allows Python users + and applications to install and upgrade Python distribution packages + without interfering with the behaviour of other Python applications + running on the same system. + + See also :mod:`venv`. + + virtual machine + A computer defined entirely in software. Python's virtual machine + executes the :term:`bytecode` emitted by the bytecode compiler. + + Zen of Python + Listing of Python design principles and philosophies that are helpful in + understanding and using the language. The listing can be found by typing + "``import this``" at the interactive prompt. diff --git a/cpython_2/environment/repo/Doc/howto/argparse.rst b/cpython_2/environment/repo/Doc/howto/argparse.rst new file mode 100644 index 0000000000000000000000000000000000000000..e78a022b372faad181e2b5703f716d2488fd7772 --- /dev/null +++ b/cpython_2/environment/repo/Doc/howto/argparse.rst @@ -0,0 +1,765 @@ +***************** +Argparse Tutorial +***************** + +:author: Tshepang Lekhonkhobe + +.. _argparse-tutorial: + +This tutorial is intended to be a gentle introduction to :mod:`argparse`, the +recommended command-line parsing module in the Python standard library. + +.. note:: + + There are two other modules that fulfill the same task, namely + :mod:`getopt` (an equivalent for :c:func:`getopt` from the C + language) and the deprecated :mod:`optparse`. + Note also that :mod:`argparse` is based on :mod:`optparse`, + and therefore very similar in terms of usage. + + +Concepts +======== + +Let's show the sort of functionality that we are going to explore in this +introductory tutorial by making use of the :command:`ls` command: + +.. code-block:: shell-session + + $ ls + cpython devguide prog.py pypy rm-unused-function.patch + $ ls pypy + ctypes_configure demo dotviewer include lib_pypy lib-python ... + $ ls -l + total 20 + drwxr-xr-x 19 wena wena 4096 Feb 18 18:51 cpython + drwxr-xr-x 4 wena wena 4096 Feb 8 12:04 devguide + -rwxr-xr-x 1 wena wena 535 Feb 19 00:05 prog.py + drwxr-xr-x 14 wena wena 4096 Feb 7 00:59 pypy + -rw-r--r-- 1 wena wena 741 Feb 18 01:01 rm-unused-function.patch + $ ls --help + Usage: ls [OPTION]... [FILE]... + List information about the FILEs (the current directory by default). + Sort entries alphabetically if none of -cftuvSUX nor --sort is specified. + ... + +A few concepts we can learn from the four commands: + +* The :command:`ls` command is useful when run without any options at all. It defaults + to displaying the contents of the current directory. + +* If we want beyond what it provides by default, we tell it a bit more. In + this case, we want it to display a different directory, ``pypy``. + What we did is specify what is known as a positional argument. It's named so + because the program should know what to do with the value, solely based on + where it appears on the command line. This concept is more relevant + to a command like :command:`cp`, whose most basic usage is ``cp SRC DEST``. + The first position is *what you want copied,* and the second + position is *where you want it copied to*. + +* Now, say we want to change behaviour of the program. In our example, + we display more info for each file instead of just showing the file names. + The ``-l`` in that case is known as an optional argument. + +* That's a snippet of the help text. It's very useful in that you can + come across a program you have never used before, and can figure out + how it works simply by reading its help text. + + +The basics +========== + +Let us start with a very simple example which does (almost) nothing:: + + import argparse + parser = argparse.ArgumentParser() + parser.parse_args() + +Following is a result of running the code: + +.. code-block:: shell-session + + $ python3 prog.py + $ python3 prog.py --help + usage: prog.py [-h] + + optional arguments: + -h, --help show this help message and exit + $ python3 prog.py --verbose + usage: prog.py [-h] + prog.py: error: unrecognized arguments: --verbose + $ python3 prog.py foo + usage: prog.py [-h] + prog.py: error: unrecognized arguments: foo + +Here is what is happening: + +* Running the script without any options results in nothing displayed to + stdout. Not so useful. + +* The second one starts to display the usefulness of the :mod:`argparse` + module. We have done almost nothing, but already we get a nice help message. + +* The ``--help`` option, which can also be shortened to ``-h``, is the only + option we get for free (i.e. no need to specify it). Specifying anything + else results in an error. But even then, we do get a useful usage message, + also for free. + + +Introducing Positional arguments +================================ + +An example:: + + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("echo") + args = parser.parse_args() + print(args.echo) + +And running the code: + +.. code-block:: shell-session + + $ python3 prog.py + usage: prog.py [-h] echo + prog.py: error: the following arguments are required: echo + $ python3 prog.py --help + usage: prog.py [-h] echo + + positional arguments: + echo + + optional arguments: + -h, --help show this help message and exit + $ python3 prog.py foo + foo + +Here is what's happening: + +* We've added the :meth:`add_argument` method, which is what we use to specify + which command-line options the program is willing to accept. In this case, + I've named it ``echo`` so that it's in line with its function. + +* Calling our program now requires us to specify an option. + +* The :meth:`parse_args` method actually returns some data from the + options specified, in this case, ``echo``. + +* The variable is some form of 'magic' that :mod:`argparse` performs for free + (i.e. no need to specify which variable that value is stored in). + You will also notice that its name matches the string argument given + to the method, ``echo``. + +Note however that, although the help display looks nice and all, it currently +is not as helpful as it can be. For example we see that we got ``echo`` as a +positional argument, but we don't know what it does, other than by guessing or +by reading the source code. So, let's make it a bit more useful:: + + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("echo", help="echo the string you use here") + args = parser.parse_args() + print(args.echo) + +And we get: + +.. code-block:: shell-session + + $ python3 prog.py -h + usage: prog.py [-h] echo + + positional arguments: + echo echo the string you use here + + optional arguments: + -h, --help show this help message and exit + +Now, how about doing something even more useful:: + + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("square", help="display a square of a given number") + args = parser.parse_args() + print(args.square**2) + +Following is a result of running the code: + +.. code-block:: shell-session + + $ python3 prog.py 4 + Traceback (most recent call last): + File "prog.py", line 5, in <module> + print(args.square**2) + TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int' + +That didn't go so well. That's because :mod:`argparse` treats the options we +give it as strings, unless we tell it otherwise. So, let's tell +:mod:`argparse` to treat that input as an integer:: + + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("square", help="display a square of a given number", + type=int) + args = parser.parse_args() + print(args.square**2) + +Following is a result of running the code: + +.. code-block:: shell-session + + $ python3 prog.py 4 + 16 + $ python3 prog.py four + usage: prog.py [-h] square + prog.py: error: argument square: invalid int value: 'four' + +That went well. The program now even helpfully quits on bad illegal input +before proceeding. + + +Introducing Optional arguments +============================== + +So far we have been playing with positional arguments. Let us +have a look on how to add optional ones:: + + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("--verbosity", help="increase output verbosity") + args = parser.parse_args() + if args.verbosity: + print("verbosity turned on") + +And the output: + +.. code-block:: shell-session + + $ python3 prog.py --verbosity 1 + verbosity turned on + $ python3 prog.py + $ python3 prog.py --help + usage: prog.py [-h] [--verbosity VERBOSITY] + + optional arguments: + -h, --help show this help message and exit + --verbosity VERBOSITY + increase output verbosity + $ python3 prog.py --verbosity + usage: prog.py [-h] [--verbosity VERBOSITY] + prog.py: error: argument --verbosity: expected one argument + +Here is what is happening: + +* The program is written so as to display something when ``--verbosity`` is + specified and display nothing when not. + +* To show that the option is actually optional, there is no error when running + the program without it. Note that by default, if an optional argument isn't + used, the relevant variable, in this case :attr:`args.verbosity`, is + given ``None`` as a value, which is the reason it fails the truth + test of the :keyword:`if` statement. + +* The help message is a bit different. + +* When using the ``--verbosity`` option, one must also specify some value, + any value. + +The above example accepts arbitrary integer values for ``--verbosity``, but for +our simple program, only two values are actually useful, ``True`` or ``False``. +Let's modify the code accordingly:: + + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("--verbose", help="increase output verbosity", + action="store_true") + args = parser.parse_args() + if args.verbose: + print("verbosity turned on") + +And the output: + +.. code-block:: shell-session + + $ python3 prog.py --verbose + verbosity turned on + $ python3 prog.py --verbose 1 + usage: prog.py [-h] [--verbose] + prog.py: error: unrecognized arguments: 1 + $ python3 prog.py --help + usage: prog.py [-h] [--verbose] + + optional arguments: + -h, --help show this help message and exit + --verbose increase output verbosity + +Here is what is happening: + +* The option is now more of a flag than something that requires a value. + We even changed the name of the option to match that idea. + Note that we now specify a new keyword, ``action``, and give it the value + ``"store_true"``. This means that, if the option is specified, + assign the value ``True`` to :data:`args.verbose`. + Not specifying it implies ``False``. + +* It complains when you specify a value, in true spirit of what flags + actually are. + +* Notice the different help text. + + +Short options +------------- + +If you are familiar with command line usage, +you will notice that I haven't yet touched on the topic of short +versions of the options. It's quite simple:: + + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("-v", "--verbose", help="increase output verbosity", + action="store_true") + args = parser.parse_args() + if args.verbose: + print("verbosity turned on") + +And here goes: + +.. code-block:: shell-session + + $ python3 prog.py -v + verbosity turned on + $ python3 prog.py --help + usage: prog.py [-h] [-v] + + optional arguments: + -h, --help show this help message and exit + -v, --verbose increase output verbosity + +Note that the new ability is also reflected in the help text. + + +Combining Positional and Optional arguments +=========================================== + +Our program keeps growing in complexity:: + + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("square", type=int, + help="display a square of a given number") + parser.add_argument("-v", "--verbose", action="store_true", + help="increase output verbosity") + args = parser.parse_args() + answer = args.square**2 + if args.verbose: + print("the square of {} equals {}".format(args.square, answer)) + else: + print(answer) + +And now the output: + +.. code-block:: shell-session + + $ python3 prog.py + usage: prog.py [-h] [-v] square + prog.py: error: the following arguments are required: square + $ python3 prog.py 4 + 16 + $ python3 prog.py 4 --verbose + the square of 4 equals 16 + $ python3 prog.py --verbose 4 + the square of 4 equals 16 + +* We've brought back a positional argument, hence the complaint. + +* Note that the order does not matter. + +How about we give this program of ours back the ability to have +multiple verbosity values, and actually get to use them:: + + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("square", type=int, + help="display a square of a given number") + parser.add_argument("-v", "--verbosity", type=int, + help="increase output verbosity") + args = parser.parse_args() + answer = args.square**2 + if args.verbosity == 2: + print("the square of {} equals {}".format(args.square, answer)) + elif args.verbosity == 1: + print("{}^2 == {}".format(args.square, answer)) + else: + print(answer) + +And the output: + +.. code-block:: shell-session + + $ python3 prog.py 4 + 16 + $ python3 prog.py 4 -v + usage: prog.py [-h] [-v VERBOSITY] square + prog.py: error: argument -v/--verbosity: expected one argument + $ python3 prog.py 4 -v 1 + 4^2 == 16 + $ python3 prog.py 4 -v 2 + the square of 4 equals 16 + $ python3 prog.py 4 -v 3 + 16 + +These all look good except the last one, which exposes a bug in our program. +Let's fix it by restricting the values the ``--verbosity`` option can accept:: + + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("square", type=int, + help="display a square of a given number") + parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2], + help="increase output verbosity") + args = parser.parse_args() + answer = args.square**2 + if args.verbosity == 2: + print("the square of {} equals {}".format(args.square, answer)) + elif args.verbosity == 1: + print("{}^2 == {}".format(args.square, answer)) + else: + print(answer) + +And the output: + +.. code-block:: shell-session + + $ python3 prog.py 4 -v 3 + usage: prog.py [-h] [-v {0,1,2}] square + prog.py: error: argument -v/--verbosity: invalid choice: 3 (choose from 0, 1, 2) + $ python3 prog.py 4 -h + usage: prog.py [-h] [-v {0,1,2}] square + + positional arguments: + square display a square of a given number + + optional arguments: + -h, --help show this help message and exit + -v {0,1,2}, --verbosity {0,1,2} + increase output verbosity + +Note that the change also reflects both in the error message as well as the +help string. + +Now, let's use a different approach of playing with verbosity, which is pretty +common. It also matches the way the CPython executable handles its own +verbosity argument (check the output of ``python --help``):: + + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("square", type=int, + help="display the square of a given number") + parser.add_argument("-v", "--verbosity", action="count", + help="increase output verbosity") + args = parser.parse_args() + answer = args.square**2 + if args.verbosity == 2: + print("the square of {} equals {}".format(args.square, answer)) + elif args.verbosity == 1: + print("{}^2 == {}".format(args.square, answer)) + else: + print(answer) + +We have introduced another action, "count", +to count the number of occurrences of a specific optional arguments: + +.. code-block:: shell-session + + $ python3 prog.py 4 + 16 + $ python3 prog.py 4 -v + 4^2 == 16 + $ python3 prog.py 4 -vv + the square of 4 equals 16 + $ python3 prog.py 4 --verbosity --verbosity + the square of 4 equals 16 + $ python3 prog.py 4 -v 1 + usage: prog.py [-h] [-v] square + prog.py: error: unrecognized arguments: 1 + $ python3 prog.py 4 -h + usage: prog.py [-h] [-v] square + + positional arguments: + square display a square of a given number + + optional arguments: + -h, --help show this help message and exit + -v, --verbosity increase output verbosity + $ python3 prog.py 4 -vvv + 16 + +* Yes, it's now more of a flag (similar to ``action="store_true"``) in the + previous version of our script. That should explain the complaint. + +* It also behaves similar to "store_true" action. + +* Now here's a demonstration of what the "count" action gives. You've probably + seen this sort of usage before. + +* And if you don't specify the ``-v`` flag, that flag is considered to have + ``None`` value. + +* As should be expected, specifying the long form of the flag, we should get + the same output. + +* Sadly, our help output isn't very informative on the new ability our script + has acquired, but that can always be fixed by improving the documentation for + our script (e.g. via the ``help`` keyword argument). + +* That last output exposes a bug in our program. + + +Let's fix:: + + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("square", type=int, + help="display a square of a given number") + parser.add_argument("-v", "--verbosity", action="count", + help="increase output verbosity") + args = parser.parse_args() + answer = args.square**2 + + # bugfix: replace == with >= + if args.verbosity >= 2: + print("the square of {} equals {}".format(args.square, answer)) + elif args.verbosity >= 1: + print("{}^2 == {}".format(args.square, answer)) + else: + print(answer) + +And this is what it gives: + +.. code-block:: shell-session + + $ python3 prog.py 4 -vvv + the square of 4 equals 16 + $ python3 prog.py 4 -vvvv + the square of 4 equals 16 + $ python3 prog.py 4 + Traceback (most recent call last): + File "prog.py", line 11, in <module> + if args.verbosity >= 2: + TypeError: '>=' not supported between instances of 'NoneType' and 'int' + + +* First output went well, and fixes the bug we had before. + That is, we want any value >= 2 to be as verbose as possible. + +* Third output not so good. + +Let's fix that bug:: + + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("square", type=int, + help="display a square of a given number") + parser.add_argument("-v", "--verbosity", action="count", default=0, + help="increase output verbosity") + args = parser.parse_args() + answer = args.square**2 + if args.verbosity >= 2: + print("the square of {} equals {}".format(args.square, answer)) + elif args.verbosity >= 1: + print("{}^2 == {}".format(args.square, answer)) + else: + print(answer) + +We've just introduced yet another keyword, ``default``. +We've set it to ``0`` in order to make it comparable to the other int values. +Remember that by default, +if an optional argument isn't specified, +it gets the ``None`` value, and that cannot be compared to an int value +(hence the :exc:`TypeError` exception). + +And: + +.. code-block:: shell-session + + $ python3 prog.py 4 + 16 + +You can go quite far just with what we've learned so far, +and we have only scratched the surface. +The :mod:`argparse` module is very powerful, +and we'll explore a bit more of it before we end this tutorial. + + +Getting a little more advanced +============================== + +What if we wanted to expand our tiny program to perform other powers, +not just squares:: + + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("x", type=int, help="the base") + parser.add_argument("y", type=int, help="the exponent") + parser.add_argument("-v", "--verbosity", action="count", default=0) + args = parser.parse_args() + answer = args.x**args.y + if args.verbosity >= 2: + print("{} to the power {} equals {}".format(args.x, args.y, answer)) + elif args.verbosity >= 1: + print("{}^{} == {}".format(args.x, args.y, answer)) + else: + print(answer) + +Output: + +.. code-block:: shell-session + + $ python3 prog.py + usage: prog.py [-h] [-v] x y + prog.py: error: the following arguments are required: x, y + $ python3 prog.py -h + usage: prog.py [-h] [-v] x y + + positional arguments: + x the base + y the exponent + + optional arguments: + -h, --help show this help message and exit + -v, --verbosity + $ python3 prog.py 4 2 -v + 4^2 == 16 + + +Notice that so far we've been using verbosity level to *change* the text +that gets displayed. The following example instead uses verbosity level +to display *more* text instead:: + + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("x", type=int, help="the base") + parser.add_argument("y", type=int, help="the exponent") + parser.add_argument("-v", "--verbosity", action="count", default=0) + args = parser.parse_args() + answer = args.x**args.y + if args.verbosity >= 2: + print("Running '{}'".format(__file__)) + if args.verbosity >= 1: + print("{}^{} == ".format(args.x, args.y), end="") + print(answer) + +Output: + +.. code-block:: shell-session + + $ python3 prog.py 4 2 + 16 + $ python3 prog.py 4 2 -v + 4^2 == 16 + $ python3 prog.py 4 2 -vv + Running 'prog.py' + 4^2 == 16 + + +Conflicting options +------------------- + +So far, we have been working with two methods of an +:class:`argparse.ArgumentParser` instance. Let's introduce a third one, +:meth:`add_mutually_exclusive_group`. It allows for us to specify options that +conflict with each other. Let's also change the rest of the program so that +the new functionality makes more sense: +we'll introduce the ``--quiet`` option, +which will be the opposite of the ``--verbose`` one:: + + import argparse + + parser = argparse.ArgumentParser() + group = parser.add_mutually_exclusive_group() + group.add_argument("-v", "--verbose", action="store_true") + group.add_argument("-q", "--quiet", action="store_true") + parser.add_argument("x", type=int, help="the base") + parser.add_argument("y", type=int, help="the exponent") + args = parser.parse_args() + answer = args.x**args.y + + if args.quiet: + print(answer) + elif args.verbose: + print("{} to the power {} equals {}".format(args.x, args.y, answer)) + else: + print("{}^{} == {}".format(args.x, args.y, answer)) + +Our program is now simpler, and we've lost some functionality for the sake of +demonstration. Anyways, here's the output: + +.. code-block:: shell-session + + $ python3 prog.py 4 2 + 4^2 == 16 + $ python3 prog.py 4 2 -q + 16 + $ python3 prog.py 4 2 -v + 4 to the power 2 equals 16 + $ python3 prog.py 4 2 -vq + usage: prog.py [-h] [-v | -q] x y + prog.py: error: argument -q/--quiet: not allowed with argument -v/--verbose + $ python3 prog.py 4 2 -v --quiet + usage: prog.py [-h] [-v | -q] x y + prog.py: error: argument -q/--quiet: not allowed with argument -v/--verbose + +That should be easy to follow. I've added that last output so you can see the +sort of flexibility you get, i.e. mixing long form options with short form +ones. + +Before we conclude, you probably want to tell your users the main purpose of +your program, just in case they don't know:: + + import argparse + + parser = argparse.ArgumentParser(description="calculate X to the power of Y") + group = parser.add_mutually_exclusive_group() + group.add_argument("-v", "--verbose", action="store_true") + group.add_argument("-q", "--quiet", action="store_true") + parser.add_argument("x", type=int, help="the base") + parser.add_argument("y", type=int, help="the exponent") + args = parser.parse_args() + answer = args.x**args.y + + if args.quiet: + print(answer) + elif args.verbose: + print("{} to the power {} equals {}".format(args.x, args.y, answer)) + else: + print("{}^{} == {}".format(args.x, args.y, answer)) + +Note that slight difference in the usage text. Note the ``[-v | -q]``, +which tells us that we can either use ``-v`` or ``-q``, +but not both at the same time: + +.. code-block:: shell-session + + $ python3 prog.py --help + usage: prog.py [-h] [-v | -q] x y + + calculate X to the power of Y + + positional arguments: + x the base + y the exponent + + optional arguments: + -h, --help show this help message and exit + -v, --verbose + -q, --quiet + + +Conclusion +========== + +The :mod:`argparse` module offers a lot more than shown here. +Its docs are quite detailed and thorough, and full of examples. +Having gone through this tutorial, you should easily digest them +without feeling overwhelmed. diff --git a/cpython_2/environment/repo/Doc/howto/clinic.rst b/cpython_2/environment/repo/Doc/howto/clinic.rst new file mode 100644 index 0000000000000000000000000000000000000000..50041829b8c388cde910018c90ed64c958673352 --- /dev/null +++ b/cpython_2/environment/repo/Doc/howto/clinic.rst @@ -0,0 +1,1740 @@ +.. highlight:: c + +********************** +Argument Clinic How-To +********************** + +:author: Larry Hastings + + +.. topic:: Abstract + + Argument Clinic is a preprocessor for CPython C files. + Its purpose is to automate all the boilerplate involved + with writing argument parsing code for "builtins". + This document shows you how to convert your first C + function to work with Argument Clinic, and then introduces + some advanced topics on Argument Clinic usage. + + Currently Argument Clinic is considered internal-only + for CPython. Its use is not supported for files outside + CPython, and no guarantees are made regarding backwards + compatibility for future versions. In other words: if you + maintain an external C extension for CPython, you're welcome + to experiment with Argument Clinic in your own code. But the + version of Argument Clinic that ships with the next version + of CPython *could* be totally incompatible and break all your code. + +The Goals Of Argument Clinic +============================ + +Argument Clinic's primary goal +is to take over responsibility for all argument parsing code +inside CPython. This means that, when you convert a function +to work with Argument Clinic, that function should no longer +do any of its own argument parsing—the code generated by +Argument Clinic should be a "black box" to you, where CPython +calls in at the top, and your code gets called at the bottom, +with ``PyObject *args`` (and maybe ``PyObject *kwargs``) +magically converted into the C variables and types you need. + +In order for Argument Clinic to accomplish its primary goal, +it must be easy to use. Currently, working with CPython's +argument parsing library is a chore, requiring maintaining +redundant information in a surprising number of places. +When you use Argument Clinic, you don't have to repeat yourself. + +Obviously, no one would want to use Argument Clinic unless +it's solving their problem—and without creating new problems of +its own. +So it's paramount that Argument Clinic generate correct code. +It'd be nice if the code was faster, too, but at the very least +it should not introduce a major speed regression. (Eventually Argument +Clinic *should* make a major speedup possible—we could +rewrite its code generator to produce tailor-made argument +parsing code, rather than calling the general-purpose CPython +argument parsing library. That would make for the fastest +argument parsing possible!) + +Additionally, Argument Clinic must be flexible enough to +work with any approach to argument parsing. Python has +some functions with some very strange parsing behaviors; +Argument Clinic's goal is to support all of them. + +Finally, the original motivation for Argument Clinic was +to provide introspection "signatures" for CPython builtins. +It used to be, the introspection query functions would throw +an exception if you passed in a builtin. With Argument +Clinic, that's a thing of the past! + +One idea you should keep in mind, as you work with +Argument Clinic: the more information you give it, the +better job it'll be able to do. +Argument Clinic is admittedly relatively simple right +now. But as it evolves it will get more sophisticated, +and it should be able to do many interesting and smart +things with all the information you give it. + + +Basic Concepts And Usage +======================== + +Argument Clinic ships with CPython; you'll find it in ``Tools/clinic/clinic.py``. +If you run that script, specifying a C file as an argument: + +.. code-block:: shell-session + + $ python3 Tools/clinic/clinic.py foo.c + +Argument Clinic will scan over the file looking for lines that +look exactly like this: + +.. code-block:: none + + /*[clinic input] + +When it finds one, it reads everything up to a line that looks +exactly like this: + +.. code-block:: none + + [clinic start generated code]*/ + +Everything in between these two lines is input for Argument Clinic. +All of these lines, including the beginning and ending comment +lines, are collectively called an Argument Clinic "block". + +When Argument Clinic parses one of these blocks, it +generates output. This output is rewritten into the C file +immediately after the block, followed by a comment containing a checksum. +The Argument Clinic block now looks like this: + +.. code-block:: none + + /*[clinic input] + ... clinic input goes here ... + [clinic start generated code]*/ + ... clinic output goes here ... + /*[clinic end generated code: checksum=...]*/ + +If you run Argument Clinic on the same file a second time, Argument Clinic +will discard the old output and write out the new output with a fresh checksum +line. However, if the input hasn't changed, the output won't change either. + +You should never modify the output portion of an Argument Clinic block. Instead, +change the input until it produces the output you want. (That's the purpose of the +checksum—to detect if someone changed the output, as these edits would be lost +the next time Argument Clinic writes out fresh output.) + +For the sake of clarity, here's the terminology we'll use with Argument Clinic: + +* The first line of the comment (``/*[clinic input]``) is the *start line*. +* The last line of the initial comment (``[clinic start generated code]*/``) is the *end line*. +* The last line (``/*[clinic end generated code: checksum=...]*/``) is the *checksum line*. +* In between the start line and the end line is the *input*. +* In between the end line and the checksum line is the *output*. +* All the text collectively, from the start line to the checksum line inclusively, + is the *block*. (A block that hasn't been successfully processed by Argument + Clinic yet doesn't have output or a checksum line, but it's still considered + a block.) + + +Converting Your First Function +============================== + +The best way to get a sense of how Argument Clinic works is to +convert a function to work with it. Here, then, are the bare +minimum steps you'd need to follow to convert a function to +work with Argument Clinic. Note that for code you plan to +check in to CPython, you really should take the conversion farther, +using some of the advanced concepts you'll see later on in +the document (like "return converters" and "self converters"). +But we'll keep it simple for this walkthrough so you can learn. + +Let's dive in! + +0. Make sure you're working with a freshly updated checkout + of the CPython trunk. + +1. Find a Python builtin that calls either :c:func:`PyArg_ParseTuple` + or :c:func:`PyArg_ParseTupleAndKeywords`, and hasn't been converted + to work with Argument Clinic yet. + For my example I'm using ``_pickle.Pickler.dump()``. + +2. If the call to the ``PyArg_Parse`` function uses any of the + following format units: + + .. code-block:: none + + O& + O! + es + es# + et + et# + + or if it has multiple calls to :c:func:`PyArg_ParseTuple`, + you should choose a different function. Argument Clinic *does* + support all of these scenarios. But these are advanced + topics—let's do something simpler for your first function. + + Also, if the function has multiple calls to :c:func:`PyArg_ParseTuple` + or :c:func:`PyArg_ParseTupleAndKeywords` where it supports different + types for the same argument, or if the function uses something besides + PyArg_Parse functions to parse its arguments, it probably + isn't suitable for conversion to Argument Clinic. Argument Clinic + doesn't support generic functions or polymorphic parameters. + +3. Add the following boilerplate above the function, creating our block:: + + /*[clinic input] + [clinic start generated code]*/ + +4. Cut the docstring and paste it in between the ``[clinic]`` lines, + removing all the junk that makes it a properly quoted C string. + When you're done you should have just the text, based at the left + margin, with no line wider than 80 characters. + (Argument Clinic will preserve indents inside the docstring.) + + If the old docstring had a first line that looked like a function + signature, throw that line away. (The docstring doesn't need it + anymore—when you use ``help()`` on your builtin in the future, + the first line will be built automatically based on the function's + signature.) + + Sample:: + + /*[clinic input] + Write a pickled representation of obj to the open file. + [clinic start generated code]*/ + +5. If your docstring doesn't have a "summary" line, Argument Clinic will + complain. So let's make sure it has one. The "summary" line should + be a paragraph consisting of a single 80-column line + at the beginning of the docstring. + + (Our example docstring consists solely of a summary line, so the sample + code doesn't have to change for this step.) + +6. Above the docstring, enter the name of the function, followed + by a blank line. This should be the Python name of the function, + and should be the full dotted path + to the function—it should start with the name of the module, + include any sub-modules, and if the function is a method on + a class it should include the class name too. + + Sample:: + + /*[clinic input] + _pickle.Pickler.dump + + Write a pickled representation of obj to the open file. + [clinic start generated code]*/ + +7. If this is the first time that module or class has been used with Argument + Clinic in this C file, + you must declare the module and/or class. Proper Argument Clinic hygiene + prefers declaring these in a separate block somewhere near the + top of the C file, in the same way that include files and statics go at + the top. (In our sample code we'll just show the two blocks next to + each other.) + + The name of the class and module should be the same as the one + seen by Python. Check the name defined in the :c:type:`PyModuleDef` + or :c:type:`PyTypeObject` as appropriate. + + When you declare a class, you must also specify two aspects of its type + in C: the type declaration you'd use for a pointer to an instance of + this class, and a pointer to the :c:type:`PyTypeObject` for this class. + + Sample:: + + /*[clinic input] + module _pickle + class _pickle.Pickler "PicklerObject *" "&Pickler_Type" + [clinic start generated code]*/ + + /*[clinic input] + _pickle.Pickler.dump + + Write a pickled representation of obj to the open file. + [clinic start generated code]*/ + + + + +8. Declare each of the parameters to the function. Each parameter + should get its own line. All the parameter lines should be + indented from the function name and the docstring. + + The general form of these parameter lines is as follows: + + .. code-block:: none + + name_of_parameter: converter + + If the parameter has a default value, add that after the + converter: + + .. code-block:: none + + name_of_parameter: converter = default_value + + Argument Clinic's support for "default values" is quite sophisticated; + please see :ref:`the section below on default values <default_values>` + for more information. + + Add a blank line below the parameters. + + What's a "converter"? It establishes both the type + of the variable used in C, and the method to convert the Python + value into a C value at runtime. + For now you're going to use what's called a "legacy converter"—a + convenience syntax intended to make porting old code into Argument + Clinic easier. + + For each parameter, copy the "format unit" for that + parameter from the ``PyArg_Parse()`` format argument and + specify *that* as its converter, as a quoted + string. ("format unit" is the formal name for the one-to-three + character substring of the ``format`` parameter that tells + the argument parsing function what the type of the variable + is and how to convert it. For more on format units please + see :ref:`arg-parsing`.) + + For multicharacter format units like ``z#``, use the + entire two-or-three character string. + + Sample:: + + /*[clinic input] + module _pickle + class _pickle.Pickler "PicklerObject *" "&Pickler_Type" + [clinic start generated code]*/ + + /*[clinic input] + _pickle.Pickler.dump + + obj: 'O' + + Write a pickled representation of obj to the open file. + [clinic start generated code]*/ + +9. If your function has ``|`` in the format string, meaning some + parameters have default values, you can ignore it. Argument + Clinic infers which parameters are optional based on whether + or not they have default values. + + If your function has ``$`` in the format string, meaning it + takes keyword-only arguments, specify ``*`` on a line by + itself before the first keyword-only argument, indented the + same as the parameter lines. + + (``_pickle.Pickler.dump`` has neither, so our sample is unchanged.) + + +10. If the existing C function calls :c:func:`PyArg_ParseTuple` + (as opposed to :c:func:`PyArg_ParseTupleAndKeywords`), then all its + arguments are positional-only. + + To mark all parameters as positional-only in Argument Clinic, + add a ``/`` on a line by itself after the last parameter, + indented the same as the parameter lines. + + Currently this is all-or-nothing; either all parameters are + positional-only, or none of them are. (In the future Argument + Clinic may relax this restriction.) + + Sample:: + + /*[clinic input] + module _pickle + class _pickle.Pickler "PicklerObject *" "&Pickler_Type" + [clinic start generated code]*/ + + /*[clinic input] + _pickle.Pickler.dump + + obj: 'O' + / + + Write a pickled representation of obj to the open file. + [clinic start generated code]*/ + +11. It's helpful to write a per-parameter docstring for each parameter. + But per-parameter docstrings are optional; you can skip this step + if you prefer. + + Here's how to add a per-parameter docstring. The first line + of the per-parameter docstring must be indented further than the + parameter definition. The left margin of this first line establishes + the left margin for the whole per-parameter docstring; all the text + you write will be outdented by this amount. You can write as much + text as you like, across multiple lines if you wish. + + Sample:: + + /*[clinic input] + module _pickle + class _pickle.Pickler "PicklerObject *" "&Pickler_Type" + [clinic start generated code]*/ + + /*[clinic input] + _pickle.Pickler.dump + + obj: 'O' + The object to be pickled. + / + + Write a pickled representation of obj to the open file. + [clinic start generated code]*/ + +12. Save and close the file, then run ``Tools/clinic/clinic.py`` on + it. With luck everything worked---your block now has output, and + a ``.c.h`` file has been generated! Reopen the file in your + text editor to see:: + + /*[clinic input] + _pickle.Pickler.dump + + obj: 'O' + The object to be pickled. + / + + Write a pickled representation of obj to the open file. + [clinic start generated code]*/ + + static PyObject * + _pickle_Pickler_dump(PicklerObject *self, PyObject *obj) + /*[clinic end generated code: output=87ecad1261e02ac7 input=552eb1c0f52260d9]*/ + + Obviously, if Argument Clinic didn't produce any output, it's because + it found an error in your input. Keep fixing your errors and retrying + until Argument Clinic processes your file without complaint. + + For readability, most of the glue code has been generated to a ``.c.h`` + file. You'll need to include that in your original ``.c`` file, + typically right after the clinic module block:: + + #include "clinic/_pickle.c.h" + +13. Double-check that the argument-parsing code Argument Clinic generated + looks basically the same as the existing code. + + First, ensure both places use the same argument-parsing function. + The existing code must call either + :c:func:`PyArg_ParseTuple` or :c:func:`PyArg_ParseTupleAndKeywords`; + ensure that the code generated by Argument Clinic calls the + *exact* same function. + + Second, the format string passed in to :c:func:`PyArg_ParseTuple` or + :c:func:`PyArg_ParseTupleAndKeywords` should be *exactly* the same + as the hand-written one in the existing function, up to the colon + or semi-colon. + + (Argument Clinic always generates its format strings + with a ``:`` followed by the name of the function. If the + existing code's format string ends with ``;``, to provide + usage help, this change is harmless—don't worry about it.) + + Third, for parameters whose format units require two arguments + (like a length variable, or an encoding string, or a pointer + to a conversion function), ensure that the second argument is + *exactly* the same between the two invocations. + + Fourth, inside the output portion of the block you'll find a preprocessor + macro defining the appropriate static :c:type:`PyMethodDef` structure for + this builtin:: + + #define __PICKLE_PICKLER_DUMP_METHODDEF \ + {"dump", (PyCFunction)__pickle_Pickler_dump, METH_O, __pickle_Pickler_dump__doc__}, + + This static structure should be *exactly* the same as the existing static + :c:type:`PyMethodDef` structure for this builtin. + + If any of these items differ in *any way*, + adjust your Argument Clinic function specification and rerun + ``Tools/clinic/clinic.py`` until they *are* the same. + + +14. Notice that the last line of its output is the declaration + of your "impl" function. This is where the builtin's implementation goes. + Delete the existing prototype of the function you're modifying, but leave + the opening curly brace. Now delete its argument parsing code and the + declarations of all the variables it dumps the arguments into. + Notice how the Python arguments are now arguments to this impl function; + if the implementation used different names for these variables, fix it. + + Let's reiterate, just because it's kind of weird. Your code should now + look like this:: + + static return_type + your_function_impl(...) + /*[clinic end generated code: checksum=...]*/ + { + ... + + Argument Clinic generated the checksum line and the function prototype just + above it. You should write the opening (and closing) curly braces for the + function, and the implementation inside. + + Sample:: + + /*[clinic input] + module _pickle + class _pickle.Pickler "PicklerObject *" "&Pickler_Type" + [clinic start generated code]*/ + /*[clinic end generated code: checksum=da39a3ee5e6b4b0d3255bfef95601890afd80709]*/ + + /*[clinic input] + _pickle.Pickler.dump + + obj: 'O' + The object to be pickled. + / + + Write a pickled representation of obj to the open file. + [clinic start generated code]*/ + + PyDoc_STRVAR(__pickle_Pickler_dump__doc__, + "Write a pickled representation of obj to the open file.\n" + "\n" + ... + static PyObject * + _pickle_Pickler_dump_impl(PicklerObject *self, PyObject *obj) + /*[clinic end generated code: checksum=3bd30745bf206a48f8b576a1da3d90f55a0a4187]*/ + { + /* Check whether the Pickler was initialized correctly (issue3664). + Developers often forget to call __init__() in their subclasses, which + would trigger a segfault without this check. */ + if (self->write == NULL) { + PyErr_Format(PicklingError, + "Pickler.__init__() was not called by %s.__init__()", + Py_TYPE(self)->tp_name); + return NULL; + } + + if (_Pickler_ClearBuffer(self) < 0) + return NULL; + + ... + +15. Remember the macro with the :c:type:`PyMethodDef` structure for this + function? Find the existing :c:type:`PyMethodDef` structure for this + function and replace it with a reference to the macro. (If the builtin + is at module scope, this will probably be very near the end of the file; + if the builtin is a class method, this will probably be below but relatively + near to the implementation.) + + Note that the body of the macro contains a trailing comma. So when you + replace the existing static :c:type:`PyMethodDef` structure with the macro, + *don't* add a comma to the end. + + Sample:: + + static struct PyMethodDef Pickler_methods[] = { + __PICKLE_PICKLER_DUMP_METHODDEF + __PICKLE_PICKLER_CLEAR_MEMO_METHODDEF + {NULL, NULL} /* sentinel */ + }; + + +16. Compile, then run the relevant portions of the regression-test suite. + This change should not introduce any new compile-time warnings or errors, + and there should be no externally-visible change to Python's behavior. + + Well, except for one difference: ``inspect.signature()`` run on your function + should now provide a valid signature! + + Congratulations, you've ported your first function to work with Argument Clinic! + +Advanced Topics +=============== + +Now that you've had some experience working with Argument Clinic, it's time +for some advanced topics. + + +Symbolic default values +----------------------- + +The default value you provide for a parameter can't be any arbitrary +expression. Currently the following are explicitly supported: + +* Numeric constants (integer and float) +* String constants +* ``True``, ``False``, and ``None`` +* Simple symbolic constants like ``sys.maxsize``, which must + start with the name of the module + +In case you're curious, this is implemented in ``from_builtin()`` +in ``Lib/inspect.py``. + +(In the future, this may need to get even more elaborate, +to allow full expressions like ``CONSTANT - 1``.) + + +Renaming the C functions and variables generated by Argument Clinic +------------------------------------------------------------------- + +Argument Clinic automatically names the functions it generates for you. +Occasionally this may cause a problem, if the generated name collides with +the name of an existing C function. There's an easy solution: override the names +used for the C functions. Just add the keyword ``"as"`` +to your function declaration line, followed by the function name you wish to use. +Argument Clinic will use that function name for the base (generated) function, +then add ``"_impl"`` to the end and use that for the name of the impl function. + +For example, if we wanted to rename the C function names generated for +``pickle.Pickler.dump``, it'd look like this:: + + /*[clinic input] + pickle.Pickler.dump as pickler_dumper + + ... + +The base function would now be named ``pickler_dumper()``, +and the impl function would now be named ``pickler_dumper_impl()``. + + +Similarly, you may have a problem where you want to give a parameter +a specific Python name, but that name may be inconvenient in C. Argument +Clinic allows you to give a parameter different names in Python and in C, +using the same ``"as"`` syntax:: + + /*[clinic input] + pickle.Pickler.dump + + obj: object + file as file_obj: object + protocol: object = NULL + * + fix_imports: bool = True + +Here, the name used in Python (in the signature and the ``keywords`` +array) would be ``file``, but the C variable would be named ``file_obj``. + +You can use this to rename the ``self`` parameter too! + + +Converting functions using PyArg_UnpackTuple +-------------------------------------------- + +To convert a function parsing its arguments with :c:func:`PyArg_UnpackTuple`, +simply write out all the arguments, specifying each as an ``object``. You +may specify the ``type`` argument to cast the type as appropriate. All +arguments should be marked positional-only (add a ``/`` on a line by itself +after the last argument). + +Currently the generated code will use :c:func:`PyArg_ParseTuple`, but this +will change soon. + +Optional Groups +--------------- + +Some legacy functions have a tricky approach to parsing their arguments: +they count the number of positional arguments, then use a ``switch`` statement +to call one of several different :c:func:`PyArg_ParseTuple` calls depending on +how many positional arguments there are. (These functions cannot accept +keyword-only arguments.) This approach was used to simulate optional +arguments back before :c:func:`PyArg_ParseTupleAndKeywords` was created. + +While functions using this approach can often be converted to +use :c:func:`PyArg_ParseTupleAndKeywords`, optional arguments, and default values, +it's not always possible. Some of these legacy functions have +behaviors :c:func:`PyArg_ParseTupleAndKeywords` doesn't directly support. +The most obvious example is the builtin function ``range()``, which has +an optional argument on the *left* side of its required argument! +Another example is ``curses.window.addch()``, which has a group of two +arguments that must always be specified together. (The arguments are +called ``x`` and ``y``; if you call the function passing in ``x``, +you must also pass in ``y``—and if you don't pass in ``x`` you may not +pass in ``y`` either.) + +In any case, the goal of Argument Clinic is to support argument parsing +for all existing CPython builtins without changing their semantics. +Therefore Argument Clinic supports +this alternate approach to parsing, using what are called *optional groups*. +Optional groups are groups of arguments that must all be passed in together. +They can be to the left or the right of the required arguments. They +can *only* be used with positional-only parameters. + +.. note:: Optional groups are *only* intended for use when converting + functions that make multiple calls to :c:func:`PyArg_ParseTuple`! + Functions that use *any* other approach for parsing arguments + should *almost never* be converted to Argument Clinic using + optional groups. Functions using optional groups currently + cannot have accurate signatures in Python, because Python just + doesn't understand the concept. Please avoid using optional + groups wherever possible. + +To specify an optional group, add a ``[`` on a line by itself before +the parameters you wish to group together, and a ``]`` on a line by itself +after these parameters. As an example, here's how ``curses.window.addch`` +uses optional groups to make the first two parameters and the last +parameter optional:: + + /*[clinic input] + + curses.window.addch + + [ + x: int + X-coordinate. + y: int + Y-coordinate. + ] + + ch: object + Character to add. + + [ + attr: long + Attributes for the character. + ] + / + + ... + + +Notes: + +* For every optional group, one additional parameter will be passed into the + impl function representing the group. The parameter will be an int named + ``group_{direction}_{number}``, + where ``{direction}`` is either ``right`` or ``left`` depending on whether the group + is before or after the required parameters, and ``{number}`` is a monotonically + increasing number (starting at 1) indicating how far away the group is from + the required parameters. When the impl is called, this parameter will be set + to zero if this group was unused, and set to non-zero if this group was used. + (By used or unused, I mean whether or not the parameters received arguments + in this invocation.) + +* If there are no required arguments, the optional groups will behave + as if they're to the right of the required arguments. + +* In the case of ambiguity, the argument parsing code + favors parameters on the left (before the required parameters). + +* Optional groups can only contain positional-only parameters. + +* Optional groups are *only* intended for legacy code. Please do not + use optional groups for new code. + + +Using real Argument Clinic converters, instead of "legacy converters" +--------------------------------------------------------------------- + +To save time, and to minimize how much you need to learn +to achieve your first port to Argument Clinic, the walkthrough above tells +you to use "legacy converters". "Legacy converters" are a convenience, +designed explicitly to make porting existing code to Argument Clinic +easier. And to be clear, their use is acceptable when porting code for +Python 3.4. + +However, in the long term we probably want all our blocks to +use Argument Clinic's real syntax for converters. Why? A couple +reasons: + +* The proper converters are far easier to read and clearer in their intent. +* There are some format units that are unsupported as "legacy converters", + because they require arguments, and the legacy converter syntax doesn't + support specifying arguments. +* In the future we may have a new argument parsing library that isn't + restricted to what :c:func:`PyArg_ParseTuple` supports; this flexibility + won't be available to parameters using legacy converters. + +Therefore, if you don't mind a little extra effort, please use the normal +converters instead of legacy converters. + +In a nutshell, the syntax for Argument Clinic (non-legacy) converters +looks like a Python function call. However, if there are no explicit +arguments to the function (all functions take their default values), +you may omit the parentheses. Thus ``bool`` and ``bool()`` are exactly +the same converters. + +All arguments to Argument Clinic converters are keyword-only. +All Argument Clinic converters accept the following arguments: + + ``c_default`` + The default value for this parameter when defined in C. + Specifically, this will be the initializer for the variable declared + in the "parse function". See :ref:`the section on default values <default_values>` + for how to use this. + Specified as a string. + + ``annotation`` + The annotation value for this parameter. Not currently supported, + because :pep:`8` mandates that the Python library may not use + annotations. + +In addition, some converters accept additional arguments. Here is a list +of these arguments, along with their meanings: + + ``accept`` + A set of Python types (and possibly pseudo-types); + this restricts the allowable Python argument to values of these types. + (This is not a general-purpose facility; as a rule it only supports + specific lists of types as shown in the legacy converter table.) + + To accept ``None``, add ``NoneType`` to this set. + + ``bitwise`` + Only supported for unsigned integers. The native integer value of this + Python argument will be written to the parameter without any range checking, + even for negative values. + + ``converter`` + Only supported by the ``object`` converter. Specifies the name of a + :ref:`C "converter function" <o_ampersand>` + to use to convert this object to a native type. + + ``encoding`` + Only supported for strings. Specifies the encoding to use when converting + this string from a Python str (Unicode) value into a C ``char *`` value. + + + ``subclass_of`` + Only supported for the ``object`` converter. Requires that the Python + value be a subclass of a Python type, as expressed in C. + + ``type`` + Only supported for the ``object`` and ``self`` converters. Specifies + the C type that will be used to declare the variable. Default value is + ``"PyObject *"``. + + ``zeroes`` + Only supported for strings. If true, embedded NUL bytes (``'\\0'``) are + permitted inside the value. The length of the string will be passed in + to the impl function, just after the string parameter, as a parameter named + ``<parameter_name>_length``. + +Please note, not every possible combination of arguments will work. +Usually these arguments are implemented by specific ``PyArg_ParseTuple`` +*format units*, with specific behavior. For example, currently you cannot +call ``unsigned_short`` without also specifying ``bitwise=True``. +Although it's perfectly reasonable to think this would work, these semantics don't +map to any existing format unit. So Argument Clinic doesn't support it. (Or, at +least, not yet.) + +Below is a table showing the mapping of legacy converters into real +Argument Clinic converters. On the left is the legacy converter, +on the right is the text you'd replace it with. + +========= ================================================================================= +``'B'`` ``unsigned_char(bitwise=True)`` +``'b'`` ``unsigned_char`` +``'c'`` ``char`` +``'C'`` ``int(accept={str})`` +``'d'`` ``double`` +``'D'`` ``Py_complex`` +``'es'`` ``str(encoding='name_of_encoding')`` +``'es#'`` ``str(encoding='name_of_encoding', zeroes=True)`` +``'et'`` ``str(encoding='name_of_encoding', accept={bytes, bytearray, str})`` +``'et#'`` ``str(encoding='name_of_encoding', accept={bytes, bytearray, str}, zeroes=True)`` +``'f'`` ``float`` +``'h'`` ``short`` +``'H'`` ``unsigned_short(bitwise=True)`` +``'i'`` ``int`` +``'I'`` ``unsigned_int(bitwise=True)`` +``'k'`` ``unsigned_long(bitwise=True)`` +``'K'`` ``unsigned_long_long(bitwise=True)`` +``'l'`` ``long`` +``'L'`` ``long long`` +``'n'`` ``Py_ssize_t`` +``'O'`` ``object`` +``'O!'`` ``object(subclass_of='&PySomething_Type')`` +``'O&'`` ``object(converter='name_of_c_function')`` +``'p'`` ``bool`` +``'S'`` ``PyBytesObject`` +``'s'`` ``str`` +``'s#'`` ``str(zeroes=True)`` +``'s*'`` ``Py_buffer(accept={buffer, str})`` +``'U'`` ``unicode`` +``'u'`` ``Py_UNICODE`` +``'u#'`` ``Py_UNICODE(zeroes=True)`` +``'w*'`` ``Py_buffer(accept={rwbuffer})`` +``'Y'`` ``PyByteArrayObject`` +``'y'`` ``str(accept={bytes})`` +``'y#'`` ``str(accept={robuffer}, zeroes=True)`` +``'y*'`` ``Py_buffer`` +``'Z'`` ``Py_UNICODE(accept={str, NoneType})`` +``'Z#'`` ``Py_UNICODE(accept={str, NoneType}, zeroes=True)`` +``'z'`` ``str(accept={str, NoneType})`` +``'z#'`` ``str(accept={str, NoneType}, zeroes=True)`` +``'z*'`` ``Py_buffer(accept={buffer, str, NoneType})`` +========= ================================================================================= + +As an example, here's our sample ``pickle.Pickler.dump`` using the proper +converter:: + + /*[clinic input] + pickle.Pickler.dump + + obj: object + The object to be pickled. + / + + Write a pickled representation of obj to the open file. + [clinic start generated code]*/ + +One advantage of real converters is that they're more flexible than legacy +converters. For example, the ``unsigned_int`` converter (and all the +``unsigned_`` converters) can be specified without ``bitwise=True``. Their +default behavior performs range checking on the value, and they won't accept +negative numbers. You just can't do that with a legacy converter! + +Argument Clinic will show you all the converters it has +available. For each converter it'll show you all the parameters +it accepts, along with the default value for each parameter. +Just run ``Tools/clinic/clinic.py --converters`` to see the full list. + +Py_buffer +--------- + +When using the ``Py_buffer`` converter +(or the ``'s*'``, ``'w*'``, ``'*y'``, or ``'z*'`` legacy converters), +you *must* not call :c:func:`PyBuffer_Release` on the provided buffer. +Argument Clinic generates code that does it for you (in the parsing function). + + + +Advanced converters +------------------- + +Remember those format units you skipped for your first +time because they were advanced? Here's how to handle those too. + +The trick is, all those format units take arguments—either +conversion functions, or types, or strings specifying an encoding. +(But "legacy converters" don't support arguments. That's why we +skipped them for your first function.) The argument you specified +to the format unit is now an argument to the converter; this +argument is either ``converter`` (for ``O&``), ``subclass_of`` (for ``O!``), +or ``encoding`` (for all the format units that start with ``e``). + +When using ``subclass_of``, you may also want to use the other +custom argument for ``object()``: ``type``, which lets you set the type +actually used for the parameter. For example, if you want to ensure +that the object is a subclass of ``PyUnicode_Type``, you probably want +to use the converter ``object(type='PyUnicodeObject *', subclass_of='&PyUnicode_Type')``. + +One possible problem with using Argument Clinic: it takes away some possible +flexibility for the format units starting with ``e``. When writing a +``PyArg_Parse`` call by hand, you could theoretically decide at runtime what +encoding string to pass in to :c:func:`PyArg_ParseTuple`. But now this string must +be hard-coded at Argument-Clinic-preprocessing-time. This limitation is deliberate; +it made supporting this format unit much easier, and may allow for future optimizations. +This restriction doesn't seem unreasonable; CPython itself always passes in static +hard-coded encoding strings for parameters whose format units start with ``e``. + + +.. _default_values: + +Parameter default values +------------------------ + +Default values for parameters can be any of a number of values. +At their simplest, they can be string, int, or float literals: + +.. code-block:: none + + foo: str = "abc" + bar: int = 123 + bat: float = 45.6 + +They can also use any of Python's built-in constants: + +.. code-block:: none + + yep: bool = True + nope: bool = False + nada: object = None + +There's also special support for a default value of ``NULL``, and +for simple expressions, documented in the following sections. + + +The ``NULL`` default value +-------------------------- + +For string and object parameters, you can set them to ``None`` to indicate +that there's no default. However, that means the C variable will be +initialized to ``Py_None``. For convenience's sakes, there's a special +value called ``NULL`` for just this reason: from Python's perspective it +behaves like a default value of ``None``, but the C variable is initialized +with ``NULL``. + +Expressions specified as default values +--------------------------------------- + +The default value for a parameter can be more than just a literal value. +It can be an entire expression, using math operators and looking up attributes +on objects. However, this support isn't exactly simple, because of some +non-obvious semantics. + +Consider the following example: + +.. code-block:: none + + foo: Py_ssize_t = sys.maxsize - 1 + +``sys.maxsize`` can have different values on different platforms. Therefore +Argument Clinic can't simply evaluate that expression locally and hard-code it +in C. So it stores the default in such a way that it will get evaluated at +runtime, when the user asks for the function's signature. + +What namespace is available when the expression is evaluated? It's evaluated +in the context of the module the builtin came from. So, if your module has an +attribute called "``max_widgets``", you may simply use it: + +.. code-block:: none + + foo: Py_ssize_t = max_widgets + +If the symbol isn't found in the current module, it fails over to looking in +``sys.modules``. That's how it can find ``sys.maxsize`` for example. (Since you +don't know in advance what modules the user will load into their interpreter, +it's best to restrict yourself to modules that are preloaded by Python itself.) + +Evaluating default values only at runtime means Argument Clinic can't compute +the correct equivalent C default value. So you need to tell it explicitly. +When you use an expression, you must also specify the equivalent expression +in C, using the ``c_default`` parameter to the converter: + +.. code-block:: none + + foo: Py_ssize_t(c_default="PY_SSIZE_T_MAX - 1") = sys.maxsize - 1 + +Another complication: Argument Clinic can't know in advance whether or not the +expression you supply is valid. It parses it to make sure it looks legal, but +it can't *actually* know. You must be very careful when using expressions to +specify values that are guaranteed to be valid at runtime! + +Finally, because expressions must be representable as static C values, there +are many restrictions on legal expressions. Here's a list of Python features +you're not permitted to use: + +* Function calls. +* Inline if statements (``3 if foo else 5``). +* Automatic sequence unpacking (``*[1, 2, 3]``). +* List/set/dict comprehensions and generator expressions. +* Tuple/list/set/dict literals. + + + +Using a return converter +------------------------ + +By default the impl function Argument Clinic generates for you returns ``PyObject *``. +But your C function often computes some C type, then converts it into the ``PyObject *`` +at the last moment. Argument Clinic handles converting your inputs from Python types +into native C types—why not have it convert your return value from a native C type +into a Python type too? + +That's what a "return converter" does. It changes your impl function to return +some C type, then adds code to the generated (non-impl) function to handle converting +that value into the appropriate ``PyObject *``. + +The syntax for return converters is similar to that of parameter converters. +You specify the return converter like it was a return annotation on the +function itself. Return converters behave much the same as parameter converters; +they take arguments, the arguments are all keyword-only, and if you're not changing +any of the default arguments you can omit the parentheses. + +(If you use both ``"as"`` *and* a return converter for your function, +the ``"as"`` should come before the return converter.) + +There's one additional complication when using return converters: how do you +indicate an error has occurred? Normally, a function returns a valid (non-``NULL``) +pointer for success, and ``NULL`` for failure. But if you use an integer return converter, +all integers are valid. How can Argument Clinic detect an error? Its solution: each return +converter implicitly looks for a special value that indicates an error. If you return +that value, and an error has been set (``PyErr_Occurred()`` returns a true +value), then the generated code will propagate the error. Otherwise it will +encode the value you return like normal. + +Currently Argument Clinic supports only a few return converters: + +.. code-block:: none + + bool + int + unsigned int + long + unsigned int + size_t + Py_ssize_t + float + double + DecodeFSDefault + +None of these take parameters. For the first three, return -1 to indicate +error. For ``DecodeFSDefault``, the return type is ``const char *``; return a ``NULL`` +pointer to indicate an error. + +(There's also an experimental ``NoneType`` converter, which lets you +return ``Py_None`` on success or ``NULL`` on failure, without having +to increment the reference count on ``Py_None``. I'm not sure it adds +enough clarity to be worth using.) + +To see all the return converters Argument Clinic supports, along with +their parameters (if any), +just run ``Tools/clinic/clinic.py --converters`` for the full list. + + +Cloning existing functions +-------------------------- + +If you have a number of functions that look similar, you may be able to +use Clinic's "clone" feature. When you clone an existing function, +you reuse: + +* its parameters, including + + * their names, + + * their converters, with all parameters, + + * their default values, + + * their per-parameter docstrings, + + * their *kind* (whether they're positional only, + positional or keyword, or keyword only), and + +* its return converter. + +The only thing not copied from the original function is its docstring; +the syntax allows you to specify a new docstring. + +Here's the syntax for cloning a function:: + + /*[clinic input] + module.class.new_function [as c_basename] = module.class.existing_function + + Docstring for new_function goes here. + [clinic start generated code]*/ + +(The functions can be in different modules or classes. I wrote +``module.class`` in the sample just to illustrate that you must +use the full path to *both* functions.) + +Sorry, there's no syntax for partially-cloning a function, or cloning a function +then modifying it. Cloning is an all-or nothing proposition. + +Also, the function you are cloning from must have been previously defined +in the current file. + +Calling Python code +------------------- + +The rest of the advanced topics require you to write Python code +which lives inside your C file and modifies Argument Clinic's +runtime state. This is simple: you simply define a Python block. + +A Python block uses different delimiter lines than an Argument +Clinic function block. It looks like this:: + + /*[python input] + # python code goes here + [python start generated code]*/ + +All the code inside the Python block is executed at the +time it's parsed. All text written to stdout inside the block +is redirected into the "output" after the block. + +As an example, here's a Python block that adds a static integer +variable to the C code:: + + /*[python input] + print('static int __ignored_unused_variable__ = 0;') + [python start generated code]*/ + static int __ignored_unused_variable__ = 0; + /*[python checksum:...]*/ + + +Using a "self converter" +------------------------ + +Argument Clinic automatically adds a "self" parameter for you +using a default converter. It automatically sets the ``type`` +of this parameter to the "pointer to an instance" you specified +when you declared the type. However, you can override +Argument Clinic's converter and specify one yourself. +Just add your own ``self`` parameter as the first parameter in a +block, and ensure that its converter is an instance of +``self_converter`` or a subclass thereof. + +What's the point? This lets you override the type of ``self``, +or give it a different default name. + +How do you specify the custom type you want to cast ``self`` to? +If you only have one or two functions with the same type for ``self``, +you can directly use Argument Clinic's existing ``self`` converter, +passing in the type you want to use as the ``type`` parameter:: + + /*[clinic input] + + _pickle.Pickler.dump + + self: self(type="PicklerObject *") + obj: object + / + + Write a pickled representation of the given object to the open file. + [clinic start generated code]*/ + +On the other hand, if you have a lot of functions that will use the same +type for ``self``, it's best to create your own converter, subclassing +``self_converter`` but overwriting the ``type`` member:: + + /*[python input] + class PicklerObject_converter(self_converter): + type = "PicklerObject *" + [python start generated code]*/ + + /*[clinic input] + + _pickle.Pickler.dump + + self: PicklerObject + obj: object + / + + Write a pickled representation of the given object to the open file. + [clinic start generated code]*/ + + + +Writing a custom converter +-------------------------- + +As we hinted at in the previous section... you can write your own converters! +A converter is simply a Python class that inherits from ``CConverter``. +The main purpose of a custom converter is if you have a parameter using +the ``O&`` format unit—parsing this parameter means calling +a :c:func:`PyArg_ParseTuple` "converter function". + +Your converter class should be named ``*something*_converter``. +If the name follows this convention, then your converter class +will be automatically registered with Argument Clinic; its name +will be the name of your class with the ``_converter`` suffix +stripped off. (This is accomplished with a metaclass.) + +You shouldn't subclass ``CConverter.__init__``. Instead, you should +write a ``converter_init()`` function. ``converter_init()`` +always accepts a ``self`` parameter; after that, all additional +parameters *must* be keyword-only. Any arguments passed in to +the converter in Argument Clinic will be passed along to your +``converter_init()``. + +There are some additional members of ``CConverter`` you may wish +to specify in your subclass. Here's the current list: + +``type`` + The C type to use for this variable. + ``type`` should be a Python string specifying the type, e.g. ``int``. + If this is a pointer type, the type string should end with ``' *'``. + +``default`` + The Python default value for this parameter, as a Python value. + Or the magic value ``unspecified`` if there is no default. + +``py_default`` + ``default`` as it should appear in Python code, + as a string. + Or ``None`` if there is no default. + +``c_default`` + ``default`` as it should appear in C code, + as a string. + Or ``None`` if there is no default. + +``c_ignored_default`` + The default value used to initialize the C variable when + there is no default, but not specifying a default may + result in an "uninitialized variable" warning. This can + easily happen when using option groups—although + properly-written code will never actually use this value, + the variable does get passed in to the impl, and the + C compiler will complain about the "use" of the + uninitialized value. This value should always be a + non-empty string. + +``converter`` + The name of the C converter function, as a string. + +``impl_by_reference`` + A boolean value. If true, + Argument Clinic will add a ``&`` in front of the name of + the variable when passing it into the impl function. + +``parse_by_reference`` + A boolean value. If true, + Argument Clinic will add a ``&`` in front of the name of + the variable when passing it into :c:func:`PyArg_ParseTuple`. + + +Here's the simplest example of a custom converter, from ``Modules/zlibmodule.c``:: + + /*[python input] + + class ssize_t_converter(CConverter): + type = 'Py_ssize_t' + converter = 'ssize_t_converter' + + [python start generated code]*/ + /*[python end generated code: output=da39a3ee5e6b4b0d input=35521e4e733823c7]*/ + +This block adds a converter to Argument Clinic named ``ssize_t``. Parameters +declared as ``ssize_t`` will be declared as type ``Py_ssize_t``, and will +be parsed by the ``'O&'`` format unit, which will call the +``ssize_t_converter`` converter function. ``ssize_t`` variables +automatically support default values. + +More sophisticated custom converters can insert custom C code to +handle initialization and cleanup. +You can see more examples of custom converters in the CPython +source tree; grep the C files for the string ``CConverter``. + +Writing a custom return converter +--------------------------------- + +Writing a custom return converter is much like writing +a custom converter. Except it's somewhat simpler, because return +converters are themselves much simpler. + +Return converters must subclass ``CReturnConverter``. +There are no examples yet of custom return converters, +because they are not widely used yet. If you wish to +write your own return converter, please read ``Tools/clinic/clinic.py``, +specifically the implementation of ``CReturnConverter`` and +all its subclasses. + +METH_O and METH_NOARGS +---------------------------------------------- + +To convert a function using ``METH_O``, make sure the function's +single argument is using the ``object`` converter, and mark the +arguments as positional-only:: + + /*[clinic input] + meth_o_sample + + argument: object + / + [clinic start generated code]*/ + + +To convert a function using ``METH_NOARGS``, just don't specify +any arguments. + +You can still use a self converter, a return converter, and specify +a ``type`` argument to the object converter for ``METH_O``. + +tp_new and tp_init functions +---------------------------------------------- + +You can convert ``tp_new`` and ``tp_init`` functions. Just name +them ``__new__`` or ``__init__`` as appropriate. Notes: + +* The function name generated for ``__new__`` doesn't end in ``__new__`` + like it would by default. It's just the name of the class, converted + into a valid C identifier. + +* No ``PyMethodDef`` ``#define`` is generated for these functions. + +* ``__init__`` functions return ``int``, not ``PyObject *``. + +* Use the docstring as the class docstring. + +* Although ``__new__`` and ``__init__`` functions must always + accept both the ``args`` and ``kwargs`` objects, when converting + you may specify any signature for these functions that you like. + (If your function doesn't support keywords, the parsing function + generated will throw an exception if it receives any.) + +Changing and redirecting Clinic's output +---------------------------------------- + +It can be inconvenient to have Clinic's output interspersed with +your conventional hand-edited C code. Luckily, Clinic is configurable: +you can buffer up its output for printing later (or earlier!), or write +its output to a separate file. You can also add a prefix or suffix to +every line of Clinic's generated output. + +While changing Clinic's output in this manner can be a boon to readability, +it may result in Clinic code using types before they are defined, or +your code attempting to use Clinic-generated code before it is defined. +These problems can be easily solved by rearranging the declarations in your file, +or moving where Clinic's generated code goes. (This is why the default behavior +of Clinic is to output everything into the current block; while many people +consider this hampers readability, it will never require rearranging your +code to fix definition-before-use problems.) + +Let's start with defining some terminology: + +*field* + A field, in this context, is a subsection of Clinic's output. + For example, the ``#define`` for the ``PyMethodDef`` structure + is a field, called ``methoddef_define``. Clinic has seven + different fields it can output per function definition: + + .. code-block:: none + + docstring_prototype + docstring_definition + methoddef_define + impl_prototype + parser_prototype + parser_definition + impl_definition + + All the names are of the form ``"<a>_<b>"``, + where ``"<a>"`` is the semantic object represented (the parsing function, + the impl function, the docstring, or the methoddef structure) and ``"<b>"`` + represents what kind of statement the field is. Field names that end in + ``"_prototype"`` + represent forward declarations of that thing, without the actual body/data + of the thing; field names that end in ``"_definition"`` represent the actual + definition of the thing, with the body/data of the thing. (``"methoddef"`` + is special, it's the only one that ends with ``"_define"``, representing that + it's a preprocessor #define.) + +*destination* + A destination is a place Clinic can write output to. There are + five built-in destinations: + + ``block`` + The default destination: printed in the output section of + the current Clinic block. + + ``buffer`` + A text buffer where you can save text for later. Text sent + here is appended to the end of any existing text. It's an + error to have any text left in the buffer when Clinic finishes + processing a file. + + ``file`` + A separate "clinic file" that will be created automatically by Clinic. + The filename chosen for the file is ``{basename}.clinic{extension}``, + where ``basename`` and ``extension`` were assigned the output + from ``os.path.splitext()`` run on the current file. (Example: + the ``file`` destination for ``_pickle.c`` would be written to + ``_pickle.clinic.c``.) + + **Important: When using a** ``file`` **destination, you** + *must check in* **the generated file!** + + ``two-pass`` + A buffer like ``buffer``. However, a two-pass buffer can only + be dumped once, and it prints out all text sent to it during + all processing, even from Clinic blocks *after* the dumping point. + + ``suppress`` + The text is suppressed—thrown away. + + +Clinic defines five new directives that let you reconfigure its output. + +The first new directive is ``dump``: + +.. code-block:: none + + dump <destination> + +This dumps the current contents of the named destination into the output of +the current block, and empties it. This only works with ``buffer`` and +``two-pass`` destinations. + +The second new directive is ``output``. The most basic form of ``output`` +is like this: + +.. code-block:: none + + output <field> <destination> + +This tells Clinic to output *field* to *destination*. ``output`` also +supports a special meta-destination, called ``everything``, which tells +Clinic to output *all* fields to that *destination*. + +``output`` has a number of other functions: + +.. code-block:: none + + output push + output pop + output preset <preset> + + +``output push`` and ``output pop`` allow you to push and pop +configurations on an internal configuration stack, so that you +can temporarily modify the output configuration, then easily restore +the previous configuration. Simply push before your change to save +the current configuration, then pop when you wish to restore the +previous configuration. + +``output preset`` sets Clinic's output to one of several built-in +preset configurations, as follows: + + ``block`` + Clinic's original starting configuration. Writes everything + immediately after the input block. + + Suppress the ``parser_prototype`` + and ``docstring_prototype``, write everything else to ``block``. + + ``file`` + Designed to write everything to the "clinic file" that it can. + You then ``#include`` this file near the top of your file. + You may need to rearrange your file to make this work, though + usually this just means creating forward declarations for various + ``typedef`` and ``PyTypeObject`` definitions. + + Suppress the ``parser_prototype`` + and ``docstring_prototype``, write the ``impl_definition`` to + ``block``, and write everything else to ``file``. + + The default filename is ``"{dirname}/clinic/{basename}.h"``. + + ``buffer`` + Save up most of the output from Clinic, to be written into + your file near the end. For Python files implementing modules + or builtin types, it's recommended that you dump the buffer + just above the static structures for your module or + builtin type; these are normally very near the end. Using + ``buffer`` may require even more editing than ``file``, if + your file has static ``PyMethodDef`` arrays defined in the + middle of the file. + + Suppress the ``parser_prototype``, ``impl_prototype``, + and ``docstring_prototype``, write the ``impl_definition`` to + ``block``, and write everything else to ``file``. + + ``two-pass`` + Similar to the ``buffer`` preset, but writes forward declarations to + the ``two-pass`` buffer, and definitions to the ``buffer``. + This is similar to the ``buffer`` preset, but may require + less editing than ``buffer``. Dump the ``two-pass`` buffer + near the top of your file, and dump the ``buffer`` near + the end just like you would when using the ``buffer`` preset. + + Suppresses the ``impl_prototype``, write the ``impl_definition`` + to ``block``, write ``docstring_prototype``, ``methoddef_define``, + and ``parser_prototype`` to ``two-pass``, write everything else + to ``buffer``. + + ``partial-buffer`` + Similar to the ``buffer`` preset, but writes more things to ``block``, + only writing the really big chunks of generated code to ``buffer``. + This avoids the definition-before-use problem of ``buffer`` completely, + at the small cost of having slightly more stuff in the block's output. + Dump the ``buffer`` near the end, just like you would when using + the ``buffer`` preset. + + Suppresses the ``impl_prototype``, write the ``docstring_definition`` + and ``parser_definition`` to ``buffer``, write everything else to ``block``. + +The third new directive is ``destination``: + +.. code-block:: none + + destination <name> <command> [...] + +This performs an operation on the destination named ``name``. + +There are two defined subcommands: ``new`` and ``clear``. + +The ``new`` subcommand works like this: + +.. code-block:: none + + destination <name> new <type> + +This creates a new destination with name ``<name>`` and type ``<type>``. + +There are five destination types: + + ``suppress`` + Throws the text away. + + ``block`` + Writes the text to the current block. This is what Clinic + originally did. + + ``buffer`` + A simple text buffer, like the "buffer" builtin destination above. + + ``file`` + A text file. The file destination takes an extra argument, + a template to use for building the filename, like so: + + destination <name> new <type> <file_template> + + The template can use three strings internally that will be replaced + by bits of the filename: + + {path} + The full path to the file, including directory and full filename. + {dirname} + The name of the directory the file is in. + {basename} + Just the name of the file, not including the directory. + {basename_root} + Basename with the extension clipped off + (everything up to but not including the last '.'). + {basename_extension} + The last '.' and everything after it. If the basename + does not contain a period, this will be the empty string. + + If there are no periods in the filename, {basename} and {filename} + are the same, and {extension} is empty. "{basename}{extension}" + is always exactly the same as "{filename}"." + + ``two-pass`` + A two-pass buffer, like the "two-pass" builtin destination above. + + +The ``clear`` subcommand works like this: + +.. code-block:: none + + destination <name> clear + +It removes all the accumulated text up to this point in the destination. +(I don't know what you'd need this for, but I thought maybe it'd be +useful while someone's experimenting.) + +The fourth new directive is ``set``: + +.. code-block:: none + + set line_prefix "string" + set line_suffix "string" + +``set`` lets you set two internal variables in Clinic. +``line_prefix`` is a string that will be prepended to every line of Clinic's output; +``line_suffix`` is a string that will be appended to every line of Clinic's output. + +Both of these support two format strings: + + ``{block comment start}`` + Turns into the string ``/*``, the start-comment text sequence for C files. + + ``{block comment end}`` + Turns into the string ``*/``, the end-comment text sequence for C files. + +The final new directive is one you shouldn't need to use directly, +called ``preserve``: + +.. code-block:: none + + preserve + +This tells Clinic that the current contents of the output should be kept, unmodified. +This is used internally by Clinic when dumping output into ``file`` files; wrapping +it in a Clinic block lets Clinic use its existing checksum functionality to ensure +the file was not modified by hand before it gets overwritten. + + +The #ifdef trick +---------------------------------------------- + +If you're converting a function that isn't available on all platforms, +there's a trick you can use to make life a little easier. The existing +code probably looks like this:: + + #ifdef HAVE_FUNCTIONNAME + static module_functionname(...) + { + ... + } + #endif /* HAVE_FUNCTIONNAME */ + +And then in the ``PyMethodDef`` structure at the bottom the existing code +will have: + +.. code-block:: none + + #ifdef HAVE_FUNCTIONNAME + {'functionname', ... }, + #endif /* HAVE_FUNCTIONNAME */ + +In this scenario, you should enclose the body of your impl function inside the ``#ifdef``, +like so:: + + #ifdef HAVE_FUNCTIONNAME + /*[clinic input] + module.functionname + ... + [clinic start generated code]*/ + static module_functionname(...) + { + ... + } + #endif /* HAVE_FUNCTIONNAME */ + +Then, remove those three lines from the ``PyMethodDef`` structure, +replacing them with the macro Argument Clinic generated: + +.. code-block:: none + + MODULE_FUNCTIONNAME_METHODDEF + +(You can find the real name for this macro inside the generated code. +Or you can calculate it yourself: it's the name of your function as defined +on the first line of your block, but with periods changed to underscores, +uppercased, and ``"_METHODDEF"`` added to the end.) + +Perhaps you're wondering: what if ``HAVE_FUNCTIONNAME`` isn't defined? +The ``MODULE_FUNCTIONNAME_METHODDEF`` macro won't be defined either! + +Here's where Argument Clinic gets very clever. It actually detects that the +Argument Clinic block might be deactivated by the ``#ifdef``. When that +happens, it generates a little extra code that looks like this:: + + #ifndef MODULE_FUNCTIONNAME_METHODDEF + #define MODULE_FUNCTIONNAME_METHODDEF + #endif /* !defined(MODULE_FUNCTIONNAME_METHODDEF) */ + +That means the macro always works. If the function is defined, this turns +into the correct structure, including the trailing comma. If the function is +undefined, this turns into nothing. + +However, this causes one ticklish problem: where should Argument Clinic put this +extra code when using the "block" output preset? It can't go in the output block, +because that could be deactivated by the ``#ifdef``. (That's the whole point!) + +In this situation, Argument Clinic writes the extra code to the "buffer" destination. +This may mean that you get a complaint from Argument Clinic: + +.. code-block:: none + + Warning in file "Modules/posixmodule.c" on line 12357: + Destination buffer 'buffer' not empty at end of file, emptying. + +When this happens, just open your file, find the ``dump buffer`` block that +Argument Clinic added to your file (it'll be at the very bottom), then +move it above the ``PyMethodDef`` structure where that macro is used. + + + +Using Argument Clinic in Python files +------------------------------------- + +It's actually possible to use Argument Clinic to preprocess Python files. +There's no point to using Argument Clinic blocks, of course, as the output +wouldn't make any sense to the Python interpreter. But using Argument Clinic +to run Python blocks lets you use Python as a Python preprocessor! + +Since Python comments are different from C comments, Argument Clinic +blocks embedded in Python files look slightly different. They look like this: + +.. code-block:: python3 + + #/*[python input] + #print("def foo(): pass") + #[python start generated code]*/ + def foo(): pass + #/*[python checksum:...]*/ diff --git a/cpython_2/environment/repo/Doc/howto/cporting.rst b/cpython_2/environment/repo/Doc/howto/cporting.rst new file mode 100644 index 0000000000000000000000000000000000000000..ce7700fc5990628ffea8a8fc00745e1ed892f401 --- /dev/null +++ b/cpython_2/environment/repo/Doc/howto/cporting.rst @@ -0,0 +1,26 @@ +.. highlight:: c + +.. _cporting-howto: + +************************************* +Porting Extension Modules to Python 3 +************************************* + +We recommend the following resources for porting extension modules to Python 3: + +* The `Migrating C extensions`_ chapter from + *Supporting Python 3: An in-depth guide*, a book on moving from Python 2 + to Python 3 in general, guides the reader through porting an extension + module. +* The `Porting guide`_ from the *py3c* project provides opinionated + suggestions with supporting code. +* The `Cython`_ and `CFFI`_ libraries offer abstractions over + Python's C API. + Extensions generally need to be re-written to use one of them, + but the library then handles differences between various Python + versions and implementations. + +.. _Migrating C extensions: http://python3porting.com/cextensions.html +.. _Porting guide: https://py3c.readthedocs.io/en/latest/guide.html +.. _Cython: http://cython.org/ +.. _CFFI: https://cffi.readthedocs.io/en/latest/ diff --git a/cpython_2/environment/repo/Doc/howto/curses.rst b/cpython_2/environment/repo/Doc/howto/curses.rst new file mode 100644 index 0000000000000000000000000000000000000000..cc4b4785b12290dcb0c500d418c6ac1b1fb8aec0 --- /dev/null +++ b/cpython_2/environment/repo/Doc/howto/curses.rst @@ -0,0 +1,552 @@ +.. _curses-howto: + +********************************** + Curses Programming with Python +********************************** + +:Author: A.M. Kuchling, Eric S. Raymond +:Release: 2.04 + + +.. topic:: Abstract + + This document describes how to use the :mod:`curses` extension + module to control text-mode displays. + + +What is curses? +=============== + +The curses library supplies a terminal-independent screen-painting and +keyboard-handling facility for text-based terminals; such terminals +include VT100s, the Linux console, and the simulated terminal provided +by various programs. Display terminals support various control codes +to perform common operations such as moving the cursor, scrolling the +screen, and erasing areas. Different terminals use widely differing +codes, and often have their own minor quirks. + +In a world of graphical displays, one might ask "why bother"? It's +true that character-cell display terminals are an obsolete technology, +but there are niches in which being able to do fancy things with them +are still valuable. One niche is on small-footprint or embedded +Unixes that don't run an X server. Another is tools such as OS +installers and kernel configurators that may have to run before any +graphical support is available. + +The curses library provides fairly basic functionality, providing the +programmer with an abstraction of a display containing multiple +non-overlapping windows of text. The contents of a window can be +changed in various ways---adding text, erasing it, changing its +appearance---and the curses library will figure out what control codes +need to be sent to the terminal to produce the right output. curses +doesn't provide many user-interface concepts such as buttons, checkboxes, +or dialogs; if you need such features, consider a user interface library such as +`Urwid <https://pypi.org/project/urwid/>`_. + +The curses library was originally written for BSD Unix; the later System V +versions of Unix from AT&T added many enhancements and new functions. BSD curses +is no longer maintained, having been replaced by ncurses, which is an +open-source implementation of the AT&T interface. If you're using an +open-source Unix such as Linux or FreeBSD, your system almost certainly uses +ncurses. Since most current commercial Unix versions are based on System V +code, all the functions described here will probably be available. The older +versions of curses carried by some proprietary Unixes may not support +everything, though. + +The Windows version of Python doesn't include the :mod:`curses` +module. A ported version called `UniCurses +<https://pypi.org/project/UniCurses>`_ is available. You could +also try `the Console module <http://effbot.org/zone/console-index.htm>`_ +written by Fredrik Lundh, which doesn't +use the same API as curses but provides cursor-addressable text output +and full support for mouse and keyboard input. + + +The Python curses module +------------------------ + +The Python module is a fairly simple wrapper over the C functions provided by +curses; if you're already familiar with curses programming in C, it's really +easy to transfer that knowledge to Python. The biggest difference is that the +Python interface makes things simpler by merging different C functions such as +:c:func:`addstr`, :c:func:`mvaddstr`, and :c:func:`mvwaddstr` into a single +:meth:`~curses.window.addstr` method. You'll see this covered in more +detail later. + +This HOWTO is an introduction to writing text-mode programs with curses +and Python. It doesn't attempt to be a complete guide to the curses API; for +that, see the Python library guide's section on ncurses, and the C manual pages +for ncurses. It will, however, give you the basic ideas. + + +Starting and ending a curses application +======================================== + +Before doing anything, curses must be initialized. This is done by +calling the :func:`~curses.initscr` function, which will determine the +terminal type, send any required setup codes to the terminal, and +create various internal data structures. If successful, +:func:`initscr` returns a window object representing the entire +screen; this is usually called ``stdscr`` after the name of the +corresponding C variable. :: + + import curses + stdscr = curses.initscr() + +Usually curses applications turn off automatic echoing of keys to the +screen, in order to be able to read keys and only display them under +certain circumstances. This requires calling the +:func:`~curses.noecho` function. :: + + curses.noecho() + +Applications will also commonly need to react to keys instantly, +without requiring the Enter key to be pressed; this is called cbreak +mode, as opposed to the usual buffered input mode. :: + + curses.cbreak() + +Terminals usually return special keys, such as the cursor keys or navigation +keys such as Page Up and Home, as a multibyte escape sequence. While you could +write your application to expect such sequences and process them accordingly, +curses can do it for you, returning a special value such as +:const:`curses.KEY_LEFT`. To get curses to do the job, you'll have to enable +keypad mode. :: + + stdscr.keypad(True) + +Terminating a curses application is much easier than starting one. You'll need +to call:: + + curses.nocbreak() + stdscr.keypad(False) + curses.echo() + +to reverse the curses-friendly terminal settings. Then call the +:func:`~curses.endwin` function to restore the terminal to its original +operating mode. :: + + curses.endwin() + +A common problem when debugging a curses application is to get your terminal +messed up when the application dies without restoring the terminal to its +previous state. In Python this commonly happens when your code is buggy and +raises an uncaught exception. Keys are no longer echoed to the screen when +you type them, for example, which makes using the shell difficult. + +In Python you can avoid these complications and make debugging much easier by +importing the :func:`curses.wrapper` function and using it like this:: + + from curses import wrapper + + def main(stdscr): + # Clear screen + stdscr.clear() + + # This raises ZeroDivisionError when i == 10. + for i in range(0, 11): + v = i-10 + stdscr.addstr(i, 0, '10 divided by {} is {}'.format(v, 10/v)) + + stdscr.refresh() + stdscr.getkey() + + wrapper(main) + +The :func:`~curses.wrapper` function takes a callable object and does the +initializations described above, also initializing colors if color +support is present. :func:`wrapper` then runs your provided callable. +Once the callable returns, :func:`wrapper` will restore the original +state of the terminal. The callable is called inside a +:keyword:`try`...\ :keyword:`except` that catches exceptions, restores +the state of the terminal, and then re-raises the exception. Therefore +your terminal won't be left in a funny state on exception and you'll be +able to read the exception's message and traceback. + + +Windows and Pads +================ + +Windows are the basic abstraction in curses. A window object represents a +rectangular area of the screen, and supports methods to display text, +erase it, allow the user to input strings, and so forth. + +The ``stdscr`` object returned by the :func:`~curses.initscr` function is a +window object that covers the entire screen. Many programs may need +only this single window, but you might wish to divide the screen into +smaller windows, in order to redraw or clear them separately. The +:func:`~curses.newwin` function creates a new window of a given size, +returning the new window object. :: + + begin_x = 20; begin_y = 7 + height = 5; width = 40 + win = curses.newwin(height, width, begin_y, begin_x) + +Note that the coordinate system used in curses is unusual. +Coordinates are always passed in the order *y,x*, and the top-left +corner of a window is coordinate (0,0). This breaks the normal +convention for handling coordinates where the *x* coordinate comes +first. This is an unfortunate difference from most other computer +applications, but it's been part of curses since it was first written, +and it's too late to change things now. + +Your application can determine the size of the screen by using the +:data:`curses.LINES` and :data:`curses.COLS` variables to obtain the *y* and +*x* sizes. Legal coordinates will then extend from ``(0,0)`` to +``(curses.LINES - 1, curses.COLS - 1)``. + +When you call a method to display or erase text, the effect doesn't +immediately show up on the display. Instead you must call the +:meth:`~curses.window.refresh` method of window objects to update the +screen. + +This is because curses was originally written with slow 300-baud +terminal connections in mind; with these terminals, minimizing the +time required to redraw the screen was very important. Instead curses +accumulates changes to the screen and displays them in the most +efficient manner when you call :meth:`refresh`. For example, if your +program displays some text in a window and then clears the window, +there's no need to send the original text because they're never +visible. + +In practice, explicitly telling curses to redraw a window doesn't +really complicate programming with curses much. Most programs go into a flurry +of activity, and then pause waiting for a keypress or some other action on the +part of the user. All you have to do is to be sure that the screen has been +redrawn before pausing to wait for user input, by first calling +``stdscr.refresh()`` or the :meth:`refresh` method of some other relevant +window. + +A pad is a special case of a window; it can be larger than the actual display +screen, and only a portion of the pad displayed at a time. Creating a pad +requires the pad's height and width, while refreshing a pad requires giving the +coordinates of the on-screen area where a subsection of the pad will be +displayed. :: + + pad = curses.newpad(100, 100) + # These loops fill the pad with letters; addch() is + # explained in the next section + for y in range(0, 99): + for x in range(0, 99): + pad.addch(y,x, ord('a') + (x*x+y*y) % 26) + + # Displays a section of the pad in the middle of the screen. + # (0,0) : coordinate of upper-left corner of pad area to display. + # (5,5) : coordinate of upper-left corner of window area to be filled + # with pad content. + # (20, 75) : coordinate of lower-right corner of window area to be + # : filled with pad content. + pad.refresh( 0,0, 5,5, 20,75) + +The :meth:`refresh` call displays a section of the pad in the rectangle +extending from coordinate (5,5) to coordinate (20,75) on the screen; the upper +left corner of the displayed section is coordinate (0,0) on the pad. Beyond +that difference, pads are exactly like ordinary windows and support the same +methods. + +If you have multiple windows and pads on screen there is a more +efficient way to update the screen and prevent annoying screen flicker +as each part of the screen gets updated. :meth:`refresh` actually +does two things: + +1) Calls the :meth:`~curses.window.noutrefresh` method of each window + to update an underlying data structure representing the desired + state of the screen. +2) Calls the function :func:`~curses.doupdate` function to change the + physical screen to match the desired state recorded in the data structure. + +Instead you can call :meth:`noutrefresh` on a number of windows to +update the data structure, and then call :func:`doupdate` to update +the screen. + + +Displaying Text +=============== + +From a C programmer's point of view, curses may sometimes look like a +twisty maze of functions, all subtly different. For example, +:c:func:`addstr` displays a string at the current cursor location in +the ``stdscr`` window, while :c:func:`mvaddstr` moves to a given y,x +coordinate first before displaying the string. :c:func:`waddstr` is just +like :c:func:`addstr`, but allows specifying a window to use instead of +using ``stdscr`` by default. :c:func:`mvwaddstr` allows specifying both +a window and a coordinate. + +Fortunately the Python interface hides all these details. ``stdscr`` +is a window object like any other, and methods such as +:meth:`~curses.window.addstr` accept multiple argument forms. Usually there +are four different forms. + ++---------------------------------+-----------------------------------------------+ +| Form | Description | ++=================================+===============================================+ +| *str* or *ch* | Display the string *str* or character *ch* at | +| | the current position | ++---------------------------------+-----------------------------------------------+ +| *str* or *ch*, *attr* | Display the string *str* or character *ch*, | +| | using attribute *attr* at the current | +| | position | ++---------------------------------+-----------------------------------------------+ +| *y*, *x*, *str* or *ch* | Move to position *y,x* within the window, and | +| | display *str* or *ch* | ++---------------------------------+-----------------------------------------------+ +| *y*, *x*, *str* or *ch*, *attr* | Move to position *y,x* within the window, and | +| | display *str* or *ch*, using attribute *attr* | ++---------------------------------+-----------------------------------------------+ + +Attributes allow displaying text in highlighted forms such as boldface, +underline, reverse code, or in color. They'll be explained in more detail in +the next subsection. + + +The :meth:`~curses.window.addstr` method takes a Python string or +bytestring as the value to be displayed. The contents of bytestrings +are sent to the terminal as-is. Strings are encoded to bytes using +the value of the window's :attr:`encoding` attribute; this defaults to +the default system encoding as returned by +:func:`locale.getpreferredencoding`. + +The :meth:`~curses.window.addch` methods take a character, which can be +either a string of length 1, a bytestring of length 1, or an integer. + +Constants are provided for extension characters; these constants are +integers greater than 255. For example, :const:`ACS_PLMINUS` is a +/- +symbol, and :const:`ACS_ULCORNER` is the upper left corner of a box +(handy for drawing borders). You can also use the appropriate Unicode +character. + +Windows remember where the cursor was left after the last operation, so if you +leave out the *y,x* coordinates, the string or character will be displayed +wherever the last operation left off. You can also move the cursor with the +``move(y,x)`` method. Because some terminals always display a flashing cursor, +you may want to ensure that the cursor is positioned in some location where it +won't be distracting; it can be confusing to have the cursor blinking at some +apparently random location. + +If your application doesn't need a blinking cursor at all, you can +call ``curs_set(False)`` to make it invisible. For compatibility +with older curses versions, there's a ``leaveok(bool)`` function +that's a synonym for :func:`~curses.curs_set`. When *bool* is true, the +curses library will attempt to suppress the flashing cursor, and you +won't need to worry about leaving it in odd locations. + + +Attributes and Color +-------------------- + +Characters can be displayed in different ways. Status lines in a text-based +application are commonly shown in reverse video, or a text viewer may need to +highlight certain words. curses supports this by allowing you to specify an +attribute for each cell on the screen. + +An attribute is an integer, each bit representing a different +attribute. You can try to display text with multiple attribute bits +set, but curses doesn't guarantee that all the possible combinations +are available, or that they're all visually distinct. That depends on +the ability of the terminal being used, so it's safest to stick to the +most commonly available attributes, listed here. + ++----------------------+--------------------------------------+ +| Attribute | Description | ++======================+======================================+ +| :const:`A_BLINK` | Blinking text | ++----------------------+--------------------------------------+ +| :const:`A_BOLD` | Extra bright or bold text | ++----------------------+--------------------------------------+ +| :const:`A_DIM` | Half bright text | ++----------------------+--------------------------------------+ +| :const:`A_REVERSE` | Reverse-video text | ++----------------------+--------------------------------------+ +| :const:`A_STANDOUT` | The best highlighting mode available | ++----------------------+--------------------------------------+ +| :const:`A_UNDERLINE` | Underlined text | ++----------------------+--------------------------------------+ + +So, to display a reverse-video status line on the top line of the screen, you +could code:: + + stdscr.addstr(0, 0, "Current mode: Typing mode", + curses.A_REVERSE) + stdscr.refresh() + +The curses library also supports color on those terminals that provide it. The +most common such terminal is probably the Linux console, followed by color +xterms. + +To use color, you must call the :func:`~curses.start_color` function soon +after calling :func:`~curses.initscr`, to initialize the default color set +(the :func:`curses.wrapper` function does this automatically). Once that's +done, the :func:`~curses.has_colors` function returns TRUE if the terminal +in use can +actually display color. (Note: curses uses the American spelling 'color', +instead of the Canadian/British spelling 'colour'. If you're used to the +British spelling, you'll have to resign yourself to misspelling it for the sake +of these functions.) + +The curses library maintains a finite number of color pairs, containing a +foreground (or text) color and a background color. You can get the attribute +value corresponding to a color pair with the :func:`~curses.color_pair` +function; this can be bitwise-OR'ed with other attributes such as +:const:`A_REVERSE`, but again, such combinations are not guaranteed to work +on all terminals. + +An example, which displays a line of text using color pair 1:: + + stdscr.addstr("Pretty text", curses.color_pair(1)) + stdscr.refresh() + +As I said before, a color pair consists of a foreground and background color. +The ``init_pair(n, f, b)`` function changes the definition of color pair *n*, to +foreground color f and background color b. Color pair 0 is hard-wired to white +on black, and cannot be changed. + +Colors are numbered, and :func:`start_color` initializes 8 basic +colors when it activates color mode. They are: 0:black, 1:red, +2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and 7:white. The :mod:`curses` +module defines named constants for each of these colors: +:const:`curses.COLOR_BLACK`, :const:`curses.COLOR_RED`, and so forth. + +Let's put all this together. To change color 1 to red text on a white +background, you would call:: + + curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE) + +When you change a color pair, any text already displayed using that color pair +will change to the new colors. You can also display new text in this color +with:: + + stdscr.addstr(0,0, "RED ALERT!", curses.color_pair(1)) + +Very fancy terminals can change the definitions of the actual colors to a given +RGB value. This lets you change color 1, which is usually red, to purple or +blue or any other color you like. Unfortunately, the Linux console doesn't +support this, so I'm unable to try it out, and can't provide any examples. You +can check if your terminal can do this by calling +:func:`~curses.can_change_color`, which returns ``True`` if the capability is +there. If you're lucky enough to have such a talented terminal, consult your +system's man pages for more information. + + +User Input +========== + +The C curses library offers only very simple input mechanisms. Python's +:mod:`curses` module adds a basic text-input widget. (Other libraries +such as `Urwid <https://pypi.org/project/urwid/>`_ have more extensive +collections of widgets.) + +There are two methods for getting input from a window: + +* :meth:`~curses.window.getch` refreshes the screen and then waits for + the user to hit a key, displaying the key if :func:`~curses.echo` has been + called earlier. You can optionally specify a coordinate to which + the cursor should be moved before pausing. + +* :meth:`~curses.window.getkey` does the same thing but converts the + integer to a string. Individual characters are returned as + 1-character strings, and special keys such as function keys return + longer strings containing a key name such as ``KEY_UP`` or ``^G``. + +It's possible to not wait for the user using the +:meth:`~curses.window.nodelay` window method. After ``nodelay(True)``, +:meth:`getch` and :meth:`getkey` for the window become +non-blocking. To signal that no input is ready, :meth:`getch` returns +``curses.ERR`` (a value of -1) and :meth:`getkey` raises an exception. +There's also a :func:`~curses.halfdelay` function, which can be used to (in +effect) set a timer on each :meth:`getch`; if no input becomes +available within a specified delay (measured in tenths of a second), +curses raises an exception. + +The :meth:`getch` method returns an integer; if it's between 0 and 255, it +represents the ASCII code of the key pressed. Values greater than 255 are +special keys such as Page Up, Home, or the cursor keys. You can compare the +value returned to constants such as :const:`curses.KEY_PPAGE`, +:const:`curses.KEY_HOME`, or :const:`curses.KEY_LEFT`. The main loop of +your program may look something like this:: + + while True: + c = stdscr.getch() + if c == ord('p'): + PrintDocument() + elif c == ord('q'): + break # Exit the while loop + elif c == curses.KEY_HOME: + x = y = 0 + +The :mod:`curses.ascii` module supplies ASCII class membership functions that +take either integer or 1-character string arguments; these may be useful in +writing more readable tests for such loops. It also supplies +conversion functions that take either integer or 1-character-string arguments +and return the same type. For example, :func:`curses.ascii.ctrl` returns the +control character corresponding to its argument. + +There's also a method to retrieve an entire string, +:meth:`~curses.window.getstr`. It isn't used very often, because its +functionality is quite limited; the only editing keys available are +the backspace key and the Enter key, which terminates the string. It +can optionally be limited to a fixed number of characters. :: + + curses.echo() # Enable echoing of characters + + # Get a 15-character string, with the cursor on the top line + s = stdscr.getstr(0,0, 15) + +The :mod:`curses.textpad` module supplies a text box that supports an +Emacs-like set of keybindings. Various methods of the +:class:`~curses.textpad.Textbox` class support editing with input +validation and gathering the edit results either with or without +trailing spaces. Here's an example:: + + import curses + from curses.textpad import Textbox, rectangle + + def main(stdscr): + stdscr.addstr(0, 0, "Enter IM message: (hit Ctrl-G to send)") + + editwin = curses.newwin(5,30, 2,1) + rectangle(stdscr, 1,0, 1+5+1, 1+30+1) + stdscr.refresh() + + box = Textbox(editwin) + + # Let the user edit until Ctrl-G is struck. + box.edit() + + # Get resulting contents + message = box.gather() + +See the library documentation on :mod:`curses.textpad` for more details. + + +For More Information +==================== + +This HOWTO doesn't cover some advanced topics, such as reading the +contents of the screen or capturing mouse events from an xterm +instance, but the Python library page for the :mod:`curses` module is now +reasonably complete. You should browse it next. + +If you're in doubt about the detailed behavior of the curses +functions, consult the manual pages for your curses implementation, +whether it's ncurses or a proprietary Unix vendor's. The manual pages +will document any quirks, and provide complete lists of all the +functions, attributes, and :const:`ACS_\*` characters available to +you. + +Because the curses API is so large, some functions aren't supported in +the Python interface. Often this isn't because they're difficult to +implement, but because no one has needed them yet. Also, Python +doesn't yet support the menu library associated with ncurses. +Patches adding support for these would be welcome; see +`the Python Developer's Guide <https://devguide.python.org/>`_ to +learn more about submitting patches to Python. + +* `Writing Programs with NCURSES <http://invisible-island.net/ncurses/ncurses-intro.html>`_: + a lengthy tutorial for C programmers. +* `The ncurses man page <https://linux.die.net/man/3/ncurses>`_ +* `The ncurses FAQ <http://invisible-island.net/ncurses/ncurses.faq.html>`_ +* `"Use curses... don't swear" <https://www.youtube.com/watch?v=eN1eZtjLEnU>`_: + video of a PyCon 2013 talk on controlling terminals using curses or Urwid. +* `"Console Applications with Urwid" <http://www.pyvideo.org/video/1568/console-applications-with-urwid>`_: + video of a PyCon CA 2012 talk demonstrating some applications written using + Urwid. diff --git a/cpython_2/environment/repo/Doc/howto/descriptor.rst b/cpython_2/environment/repo/Doc/howto/descriptor.rst new file mode 100644 index 0000000000000000000000000000000000000000..6928917dbe4200317267923ce7d5494ae1aae7f3 --- /dev/null +++ b/cpython_2/environment/repo/Doc/howto/descriptor.rst @@ -0,0 +1,443 @@ +====================== +Descriptor HowTo Guide +====================== + +:Author: Raymond Hettinger +:Contact: <python at rcn dot com> + +.. Contents:: + +Abstract +-------- + +Defines descriptors, summarizes the protocol, and shows how descriptors are +called. Examines a custom descriptor and several built-in Python descriptors +including functions, properties, static methods, and class methods. Shows how +each works by giving a pure Python equivalent and a sample application. + +Learning about descriptors not only provides access to a larger toolset, it +creates a deeper understanding of how Python works and an appreciation for the +elegance of its design. + + +Definition and Introduction +--------------------------- + +In general, a descriptor is an object attribute with "binding behavior", one +whose attribute access has been overridden by methods in the descriptor +protocol. Those methods are :meth:`__get__`, :meth:`__set__`, and +:meth:`__delete__`. If any of those methods are defined for an object, it is +said to be a descriptor. + +The default behavior for attribute access is to get, set, or delete the +attribute from an object's dictionary. For instance, ``a.x`` has a lookup chain +starting with ``a.__dict__['x']``, then ``type(a).__dict__['x']``, and +continuing through the base classes of ``type(a)`` excluding metaclasses. If the +looked-up value is an object defining one of the descriptor methods, then Python +may override the default behavior and invoke the descriptor method instead. +Where this occurs in the precedence chain depends on which descriptor methods +were defined. + +Descriptors are a powerful, general purpose protocol. They are the mechanism +behind properties, methods, static methods, class methods, and :func:`super()`. +They are used throughout Python itself to implement the new style classes +introduced in version 2.2. Descriptors simplify the underlying C-code and offer +a flexible set of new tools for everyday Python programs. + + +Descriptor Protocol +------------------- + +``descr.__get__(self, obj, type=None) -> value`` + +``descr.__set__(self, obj, value) -> None`` + +``descr.__delete__(self, obj) -> None`` + +That is all there is to it. Define any of these methods and an object is +considered a descriptor and can override default behavior upon being looked up +as an attribute. + +If an object defines :meth:`__set__` or :meth:`__delete__`, it is considered +a data descriptor. Descriptors that only define :meth:`__get__` are called +non-data descriptors (they are typically used for methods but other uses are +possible). + +Data and non-data descriptors differ in how overrides are calculated with +respect to entries in an instance's dictionary. If an instance's dictionary +has an entry with the same name as a data descriptor, the data descriptor +takes precedence. If an instance's dictionary has an entry with the same +name as a non-data descriptor, the dictionary entry takes precedence. + +To make a read-only data descriptor, define both :meth:`__get__` and +:meth:`__set__` with the :meth:`__set__` raising an :exc:`AttributeError` when +called. Defining the :meth:`__set__` method with an exception raising +placeholder is enough to make it a data descriptor. + + +Invoking Descriptors +-------------------- + +A descriptor can be called directly by its method name. For example, +``d.__get__(obj)``. + +Alternatively, it is more common for a descriptor to be invoked automatically +upon attribute access. For example, ``obj.d`` looks up ``d`` in the dictionary +of ``obj``. If ``d`` defines the method :meth:`__get__`, then ``d.__get__(obj)`` +is invoked according to the precedence rules listed below. + +The details of invocation depend on whether ``obj`` is an object or a class. + +For objects, the machinery is in :meth:`object.__getattribute__` which +transforms ``b.x`` into ``type(b).__dict__['x'].__get__(b, type(b))``. The +implementation works through a precedence chain that gives data descriptors +priority over instance variables, instance variables priority over non-data +descriptors, and assigns lowest priority to :meth:`__getattr__` if provided. +The full C implementation can be found in :c:func:`PyObject_GenericGetAttr()` in +:source:`Objects/object.c`. + +For classes, the machinery is in :meth:`type.__getattribute__` which transforms +``B.x`` into ``B.__dict__['x'].__get__(None, B)``. In pure Python, it looks +like:: + + def __getattribute__(self, key): + "Emulate type_getattro() in Objects/typeobject.c" + v = object.__getattribute__(self, key) + if hasattr(v, '__get__'): + return v.__get__(None, self) + return v + +The important points to remember are: + +* descriptors are invoked by the :meth:`__getattribute__` method +* overriding :meth:`__getattribute__` prevents automatic descriptor calls +* :meth:`object.__getattribute__` and :meth:`type.__getattribute__` make + different calls to :meth:`__get__`. +* data descriptors always override instance dictionaries. +* non-data descriptors may be overridden by instance dictionaries. + +The object returned by ``super()`` also has a custom :meth:`__getattribute__` +method for invoking descriptors. The attribute lookup ``super(B, obj).m`` searches +``obj.__class__.__mro__`` for the base class ``A`` immediately following ``B`` +and then returns ``A.__dict__['m'].__get__(obj, B)``. If not a descriptor, +``m`` is returned unchanged. If not in the dictionary, ``m`` reverts to a +search using :meth:`object.__getattribute__`. + +The implementation details are in :c:func:`super_getattro()` in +:source:`Objects/typeobject.c`. and a pure Python equivalent can be found in +`Guido's Tutorial`_. + +.. _`Guido's Tutorial`: https://www.python.org/download/releases/2.2.3/descrintro/#cooperation + +The details above show that the mechanism for descriptors is embedded in the +:meth:`__getattribute__()` methods for :class:`object`, :class:`type`, and +:func:`super`. Classes inherit this machinery when they derive from +:class:`object` or if they have a meta-class providing similar functionality. +Likewise, classes can turn-off descriptor invocation by overriding +:meth:`__getattribute__()`. + + +Descriptor Example +------------------ + +The following code creates a class whose objects are data descriptors which +print a message for each get or set. Overriding :meth:`__getattribute__` is +alternate approach that could do this for every attribute. However, this +descriptor is useful for monitoring just a few chosen attributes:: + + class RevealAccess: + """A data descriptor that sets and returns values + normally and prints a message logging their access. + """ + + def __init__(self, initval=None, name='var'): + self.val = initval + self.name = name + + def __get__(self, obj, objtype): + print('Retrieving', self.name) + return self.val + + def __set__(self, obj, val): + print('Updating', self.name) + self.val = val + + >>> class MyClass: + ... x = RevealAccess(10, 'var "x"') + ... y = 5 + ... + >>> m = MyClass() + >>> m.x + Retrieving var "x" + 10 + >>> m.x = 20 + Updating var "x" + >>> m.x + Retrieving var "x" + 20 + >>> m.y + 5 + +The protocol is simple and offers exciting possibilities. Several use cases are +so common that they have been packaged into individual function calls. +Properties, bound methods, static methods, and class methods are all +based on the descriptor protocol. + + +Properties +---------- + +Calling :func:`property` is a succinct way of building a data descriptor that +triggers function calls upon access to an attribute. Its signature is:: + + property(fget=None, fset=None, fdel=None, doc=None) -> property attribute + +The documentation shows a typical use to define a managed attribute ``x``:: + + class C: + def getx(self): return self.__x + def setx(self, value): self.__x = value + def delx(self): del self.__x + x = property(getx, setx, delx, "I'm the 'x' property.") + +To see how :func:`property` is implemented in terms of the descriptor protocol, +here is a pure Python equivalent:: + + class Property: + "Emulate PyProperty_Type() in Objects/descrobject.c" + + def __init__(self, fget=None, fset=None, fdel=None, doc=None): + self.fget = fget + self.fset = fset + self.fdel = fdel + if doc is None and fget is not None: + doc = fget.__doc__ + self.__doc__ = doc + + def __get__(self, obj, objtype=None): + if obj is None: + return self + if self.fget is None: + raise AttributeError("unreadable attribute") + return self.fget(obj) + + def __set__(self, obj, value): + if self.fset is None: + raise AttributeError("can't set attribute") + self.fset(obj, value) + + def __delete__(self, obj): + if self.fdel is None: + raise AttributeError("can't delete attribute") + self.fdel(obj) + + def getter(self, fget): + return type(self)(fget, self.fset, self.fdel, self.__doc__) + + def setter(self, fset): + return type(self)(self.fget, fset, self.fdel, self.__doc__) + + def deleter(self, fdel): + return type(self)(self.fget, self.fset, fdel, self.__doc__) + +The :func:`property` builtin helps whenever a user interface has granted +attribute access and then subsequent changes require the intervention of a +method. + +For instance, a spreadsheet class may grant access to a cell value through +``Cell('b10').value``. Subsequent improvements to the program require the cell +to be recalculated on every access; however, the programmer does not want to +affect existing client code accessing the attribute directly. The solution is +to wrap access to the value attribute in a property data descriptor:: + + class Cell: + . . . + def getvalue(self): + "Recalculate the cell before returning value" + self.recalc() + return self._value + value = property(getvalue) + + +Functions and Methods +--------------------- + +Python's object oriented features are built upon a function based environment. +Using non-data descriptors, the two are merged seamlessly. + +Class dictionaries store methods as functions. In a class definition, methods +are written using :keyword:`def` or :keyword:`lambda`, the usual tools for +creating functions. Methods only differ from regular functions in that the +first argument is reserved for the object instance. By Python convention, the +instance reference is called *self* but may be called *this* or any other +variable name. + +To support method calls, functions include the :meth:`__get__` method for +binding methods during attribute access. This means that all functions are +non-data descriptors which return bound methods when they are invoked from an +object. In pure Python, it works like this:: + + class Function: + . . . + def __get__(self, obj, objtype=None): + "Simulate func_descr_get() in Objects/funcobject.c" + if obj is None: + return self + return types.MethodType(self, obj) + +Running the interpreter shows how the function descriptor works in practice:: + + >>> class D: + ... def f(self, x): + ... return x + ... + >>> d = D() + + # Access through the class dictionary does not invoke __get__. + # It just returns the underlying function object. + >>> D.__dict__['f'] + <function D.f at 0x00C45070> + + # Dotted access from a class calls __get__() which just returns + # the underlying function unchanged. + >>> D.f + <function D.f at 0x00C45070> + + # The function has a __qualname__ attribute to support introspection + >>> D.f.__qualname__ + 'D.f' + + # Dotted access from an instance calls __get__() which returns the + # function wrapped in a bound method object + >>> d.f + <bound method D.f of <__main__.D object at 0x00B18C90>> + + # Internally, the bound method stores the underlying function, + # the bound instance, and the class of the bound instance. + >>> d.f.__func__ + <function D.f at 0x1012e5ae8> + >>> d.f.__self__ + <__main__.D object at 0x1012e1f98> + >>> d.f.__class__ + <class 'method'> + + +Static Methods and Class Methods +-------------------------------- + +Non-data descriptors provide a simple mechanism for variations on the usual +patterns of binding functions into methods. + +To recap, functions have a :meth:`__get__` method so that they can be converted +to a method when accessed as attributes. The non-data descriptor transforms an +``obj.f(*args)`` call into ``f(obj, *args)``. Calling ``klass.f(*args)`` +becomes ``f(*args)``. + +This chart summarizes the binding and its two most useful variants: + + +-----------------+----------------------+------------------+ + | Transformation | Called from an | Called from a | + | | Object | Class | + +=================+======================+==================+ + | function | f(obj, \*args) | f(\*args) | + +-----------------+----------------------+------------------+ + | staticmethod | f(\*args) | f(\*args) | + +-----------------+----------------------+------------------+ + | classmethod | f(type(obj), \*args) | f(klass, \*args) | + +-----------------+----------------------+------------------+ + +Static methods return the underlying function without changes. Calling either +``c.f`` or ``C.f`` is the equivalent of a direct lookup into +``object.__getattribute__(c, "f")`` or ``object.__getattribute__(C, "f")``. As a +result, the function becomes identically accessible from either an object or a +class. + +Good candidates for static methods are methods that do not reference the +``self`` variable. + +For instance, a statistics package may include a container class for +experimental data. The class provides normal methods for computing the average, +mean, median, and other descriptive statistics that depend on the data. However, +there may be useful functions which are conceptually related but do not depend +on the data. For instance, ``erf(x)`` is handy conversion routine that comes up +in statistical work but does not directly depend on a particular dataset. +It can be called either from an object or the class: ``s.erf(1.5) --> .9332`` or +``Sample.erf(1.5) --> .9332``. + +Since staticmethods return the underlying function with no changes, the example +calls are unexciting:: + + >>> class E: + ... def f(x): + ... print(x) + ... f = staticmethod(f) + ... + >>> E.f(3) + 3 + >>> E().f(3) + 3 + +Using the non-data descriptor protocol, a pure Python version of +:func:`staticmethod` would look like this:: + + class StaticMethod: + "Emulate PyStaticMethod_Type() in Objects/funcobject.c" + + def __init__(self, f): + self.f = f + + def __get__(self, obj, objtype=None): + return self.f + +Unlike static methods, class methods prepend the class reference to the +argument list before calling the function. This format is the same +for whether the caller is an object or a class:: + + >>> class E: + ... def f(klass, x): + ... return klass.__name__, x + ... f = classmethod(f) + ... + >>> print(E.f(3)) + ('E', 3) + >>> print(E().f(3)) + ('E', 3) + + +This behavior is useful whenever the function only needs to have a class +reference and does not care about any underlying data. One use for classmethods +is to create alternate class constructors. In Python 2.3, the classmethod +:func:`dict.fromkeys` creates a new dictionary from a list of keys. The pure +Python equivalent is:: + + class Dict: + . . . + def fromkeys(klass, iterable, value=None): + "Emulate dict_fromkeys() in Objects/dictobject.c" + d = klass() + for key in iterable: + d[key] = value + return d + fromkeys = classmethod(fromkeys) + +Now a new dictionary of unique keys can be constructed like this:: + + >>> Dict.fromkeys('abracadabra') + {'a': None, 'r': None, 'b': None, 'c': None, 'd': None} + +Using the non-data descriptor protocol, a pure Python version of +:func:`classmethod` would look like this:: + + class ClassMethod: + "Emulate PyClassMethod_Type() in Objects/funcobject.c" + + def __init__(self, f): + self.f = f + + def __get__(self, obj, klass=None): + if klass is None: + klass = type(obj) + def newfunc(*args): + return self.f(klass, *args) + return newfunc + diff --git a/cpython_2/environment/repo/Doc/howto/functional.rst b/cpython_2/environment/repo/Doc/howto/functional.rst new file mode 100644 index 0000000000000000000000000000000000000000..74e861480d2ff8873caa78f08c42bddb9be61727 --- /dev/null +++ b/cpython_2/environment/repo/Doc/howto/functional.rst @@ -0,0 +1,1262 @@ +******************************** + Functional Programming HOWTO +******************************** + +:Author: A. M. Kuchling +:Release: 0.32 + +In this document, we'll take a tour of Python's features suitable for +implementing programs in a functional style. After an introduction to the +concepts of functional programming, we'll look at language features such as +:term:`iterator`\s and :term:`generator`\s and relevant library modules such as +:mod:`itertools` and :mod:`functools`. + + +Introduction +============ + +This section explains the basic concept of functional programming; if +you're just interested in learning about Python language features, +skip to the next section on :ref:`functional-howto-iterators`. + +Programming languages support decomposing problems in several different ways: + +* Most programming languages are **procedural**: programs are lists of + instructions that tell the computer what to do with the program's input. C, + Pascal, and even Unix shells are procedural languages. + +* In **declarative** languages, you write a specification that describes the + problem to be solved, and the language implementation figures out how to + perform the computation efficiently. SQL is the declarative language you're + most likely to be familiar with; a SQL query describes the data set you want + to retrieve, and the SQL engine decides whether to scan tables or use indexes, + which subclauses should be performed first, etc. + +* **Object-oriented** programs manipulate collections of objects. Objects have + internal state and support methods that query or modify this internal state in + some way. Smalltalk and Java are object-oriented languages. C++ and Python + are languages that support object-oriented programming, but don't force the + use of object-oriented features. + +* **Functional** programming decomposes a problem into a set of functions. + Ideally, functions only take inputs and produce outputs, and don't have any + internal state that affects the output produced for a given input. Well-known + functional languages include the ML family (Standard ML, OCaml, and other + variants) and Haskell. + +The designers of some computer languages choose to emphasize one +particular approach to programming. This often makes it difficult to +write programs that use a different approach. Other languages are +multi-paradigm languages that support several different approaches. +Lisp, C++, and Python are multi-paradigm; you can write programs or +libraries that are largely procedural, object-oriented, or functional +in all of these languages. In a large program, different sections +might be written using different approaches; the GUI might be +object-oriented while the processing logic is procedural or +functional, for example. + +In a functional program, input flows through a set of functions. Each function +operates on its input and produces some output. Functional style discourages +functions with side effects that modify internal state or make other changes +that aren't visible in the function's return value. Functions that have no side +effects at all are called **purely functional**. Avoiding side effects means +not using data structures that get updated as a program runs; every function's +output must only depend on its input. + +Some languages are very strict about purity and don't even have assignment +statements such as ``a=3`` or ``c = a + b``, but it's difficult to avoid all +side effects. Printing to the screen or writing to a disk file are side +effects, for example. For example, in Python a call to the :func:`print` or +:func:`time.sleep` function both return no useful value; they're only called for +their side effects of sending some text to the screen or pausing execution for a +second. + +Python programs written in functional style usually won't go to the extreme of +avoiding all I/O or all assignments; instead, they'll provide a +functional-appearing interface but will use non-functional features internally. +For example, the implementation of a function will still use assignments to +local variables, but won't modify global variables or have other side effects. + +Functional programming can be considered the opposite of object-oriented +programming. Objects are little capsules containing some internal state along +with a collection of method calls that let you modify this state, and programs +consist of making the right set of state changes. Functional programming wants +to avoid state changes as much as possible and works with data flowing between +functions. In Python you might combine the two approaches by writing functions +that take and return instances representing objects in your application (e-mail +messages, transactions, etc.). + +Functional design may seem like an odd constraint to work under. Why should you +avoid objects and side effects? There are theoretical and practical advantages +to the functional style: + +* Formal provability. +* Modularity. +* Composability. +* Ease of debugging and testing. + + +Formal provability +------------------ + +A theoretical benefit is that it's easier to construct a mathematical proof that +a functional program is correct. + +For a long time researchers have been interested in finding ways to +mathematically prove programs correct. This is different from testing a program +on numerous inputs and concluding that its output is usually correct, or reading +a program's source code and concluding that the code looks right; the goal is +instead a rigorous proof that a program produces the right result for all +possible inputs. + +The technique used to prove programs correct is to write down **invariants**, +properties of the input data and of the program's variables that are always +true. For each line of code, you then show that if invariants X and Y are true +**before** the line is executed, the slightly different invariants X' and Y' are +true **after** the line is executed. This continues until you reach the end of +the program, at which point the invariants should match the desired conditions +on the program's output. + +Functional programming's avoidance of assignments arose because assignments are +difficult to handle with this technique; assignments can break invariants that +were true before the assignment without producing any new invariants that can be +propagated onward. + +Unfortunately, proving programs correct is largely impractical and not relevant +to Python software. Even trivial programs require proofs that are several pages +long; the proof of correctness for a moderately complicated program would be +enormous, and few or none of the programs you use daily (the Python interpreter, +your XML parser, your web browser) could be proven correct. Even if you wrote +down or generated a proof, there would then be the question of verifying the +proof; maybe there's an error in it, and you wrongly believe you've proved the +program correct. + + +Modularity +---------- + +A more practical benefit of functional programming is that it forces you to +break apart your problem into small pieces. Programs are more modular as a +result. It's easier to specify and write a small function that does one thing +than a large function that performs a complicated transformation. Small +functions are also easier to read and to check for errors. + + +Ease of debugging and testing +----------------------------- + +Testing and debugging a functional-style program is easier. + +Debugging is simplified because functions are generally small and clearly +specified. When a program doesn't work, each function is an interface point +where you can check that the data are correct. You can look at the intermediate +inputs and outputs to quickly isolate the function that's responsible for a bug. + +Testing is easier because each function is a potential subject for a unit test. +Functions don't depend on system state that needs to be replicated before +running a test; instead you only have to synthesize the right input and then +check that the output matches expectations. + + +Composability +------------- + +As you work on a functional-style program, you'll write a number of functions +with varying inputs and outputs. Some of these functions will be unavoidably +specialized to a particular application, but others will be useful in a wide +variety of programs. For example, a function that takes a directory path and +returns all the XML files in the directory, or a function that takes a filename +and returns its contents, can be applied to many different situations. + +Over time you'll form a personal library of utilities. Often you'll assemble +new programs by arranging existing functions in a new configuration and writing +a few functions specialized for the current task. + + +.. _functional-howto-iterators: + +Iterators +========= + +I'll start by looking at a Python language feature that's an important +foundation for writing functional-style programs: iterators. + +An iterator is an object representing a stream of data; this object returns the +data one element at a time. A Python iterator must support a method called +:meth:`~iterator.__next__` that takes no arguments and always returns the next +element of the stream. If there are no more elements in the stream, +:meth:`~iterator.__next__` must raise the :exc:`StopIteration` exception. +Iterators don't have to be finite, though; it's perfectly reasonable to write +an iterator that produces an infinite stream of data. + +The built-in :func:`iter` function takes an arbitrary object and tries to return +an iterator that will return the object's contents or elements, raising +:exc:`TypeError` if the object doesn't support iteration. Several of Python's +built-in data types support iteration, the most common being lists and +dictionaries. An object is called :term:`iterable` if you can get an iterator +for it. + +You can experiment with the iteration interface manually: + + >>> L = [1, 2, 3] + >>> it = iter(L) + >>> it #doctest: +ELLIPSIS + <...iterator object at ...> + >>> it.__next__() # same as next(it) + 1 + >>> next(it) + 2 + >>> next(it) + 3 + >>> next(it) + Traceback (most recent call last): + File "<stdin>", line 1, in <module> + StopIteration + >>> + +Python expects iterable objects in several different contexts, the most +important being the :keyword:`for` statement. In the statement ``for X in Y``, +Y must be an iterator or some object for which :func:`iter` can create an +iterator. These two statements are equivalent:: + + + for i in iter(obj): + print(i) + + for i in obj: + print(i) + +Iterators can be materialized as lists or tuples by using the :func:`list` or +:func:`tuple` constructor functions: + + >>> L = [1, 2, 3] + >>> iterator = iter(L) + >>> t = tuple(iterator) + >>> t + (1, 2, 3) + +Sequence unpacking also supports iterators: if you know an iterator will return +N elements, you can unpack them into an N-tuple: + + >>> L = [1, 2, 3] + >>> iterator = iter(L) + >>> a, b, c = iterator + >>> a, b, c + (1, 2, 3) + +Built-in functions such as :func:`max` and :func:`min` can take a single +iterator argument and will return the largest or smallest element. The ``"in"`` +and ``"not in"`` operators also support iterators: ``X in iterator`` is true if +X is found in the stream returned by the iterator. You'll run into obvious +problems if the iterator is infinite; :func:`max`, :func:`min` +will never return, and if the element X never appears in the stream, the +``"in"`` and ``"not in"`` operators won't return either. + +Note that you can only go forward in an iterator; there's no way to get the +previous element, reset the iterator, or make a copy of it. Iterator objects +can optionally provide these additional capabilities, but the iterator protocol +only specifies the :meth:`~iterator.__next__` method. Functions may therefore +consume all of the iterator's output, and if you need to do something different +with the same stream, you'll have to create a new iterator. + + + +Data Types That Support Iterators +--------------------------------- + +We've already seen how lists and tuples support iterators. In fact, any Python +sequence type, such as strings, will automatically support creation of an +iterator. + +Calling :func:`iter` on a dictionary returns an iterator that will loop over the +dictionary's keys:: + + >>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6, + ... 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12} + >>> for key in m: + ... print(key, m[key]) + Jan 1 + Feb 2 + Mar 3 + Apr 4 + May 5 + Jun 6 + Jul 7 + Aug 8 + Sep 9 + Oct 10 + Nov 11 + Dec 12 + +Note that starting with Python 3.7, dictionary iteration order is guaranteed +to be the same as the insertion order. In earlier versions, the behaviour was +unspecified and could vary between implementations. + +Applying :func:`iter` to a dictionary always loops over the keys, but +dictionaries have methods that return other iterators. If you want to iterate +over values or key/value pairs, you can explicitly call the +:meth:`~dict.values` or :meth:`~dict.items` methods to get an appropriate +iterator. + +The :func:`dict` constructor can accept an iterator that returns a finite stream +of ``(key, value)`` tuples: + + >>> L = [('Italy', 'Rome'), ('France', 'Paris'), ('US', 'Washington DC')] + >>> dict(iter(L)) + {'Italy': 'Rome', 'France': 'Paris', 'US': 'Washington DC'} + +Files also support iteration by calling the :meth:`~io.TextIOBase.readline` +method until there are no more lines in the file. This means you can read each +line of a file like this:: + + for line in file: + # do something for each line + ... + +Sets can take their contents from an iterable and let you iterate over the set's +elements:: + + S = {2, 3, 5, 7, 11, 13} + for i in S: + print(i) + + + +Generator expressions and list comprehensions +============================================= + +Two common operations on an iterator's output are 1) performing some operation +for every element, 2) selecting a subset of elements that meet some condition. +For example, given a list of strings, you might want to strip off trailing +whitespace from each line or extract all the strings containing a given +substring. + +List comprehensions and generator expressions (short form: "listcomps" and +"genexps") are a concise notation for such operations, borrowed from the +functional programming language Haskell (https://www.haskell.org/). You can strip +all the whitespace from a stream of strings with the following code:: + + line_list = [' line 1\n', 'line 2 \n', ...] + + # Generator expression -- returns iterator + stripped_iter = (line.strip() for line in line_list) + + # List comprehension -- returns list + stripped_list = [line.strip() for line in line_list] + +You can select only certain elements by adding an ``"if"`` condition:: + + stripped_list = [line.strip() for line in line_list + if line != ""] + +With a list comprehension, you get back a Python list; ``stripped_list`` is a +list containing the resulting lines, not an iterator. Generator expressions +return an iterator that computes the values as necessary, not needing to +materialize all the values at once. This means that list comprehensions aren't +useful if you're working with iterators that return an infinite stream or a very +large amount of data. Generator expressions are preferable in these situations. + +Generator expressions are surrounded by parentheses ("()") and list +comprehensions are surrounded by square brackets ("[]"). Generator expressions +have the form:: + + ( expression for expr in sequence1 + if condition1 + for expr2 in sequence2 + if condition2 + for expr3 in sequence3 ... + if condition3 + for exprN in sequenceN + if conditionN ) + +Again, for a list comprehension only the outside brackets are different (square +brackets instead of parentheses). + +The elements of the generated output will be the successive values of +``expression``. The ``if`` clauses are all optional; if present, ``expression`` +is only evaluated and added to the result when ``condition`` is true. + +Generator expressions always have to be written inside parentheses, but the +parentheses signalling a function call also count. If you want to create an +iterator that will be immediately passed to a function you can write:: + + obj_total = sum(obj.count for obj in list_all_objects()) + +The ``for...in`` clauses contain the sequences to be iterated over. The +sequences do not have to be the same length, because they are iterated over from +left to right, **not** in parallel. For each element in ``sequence1``, +``sequence2`` is looped over from the beginning. ``sequence3`` is then looped +over for each resulting pair of elements from ``sequence1`` and ``sequence2``. + +To put it another way, a list comprehension or generator expression is +equivalent to the following Python code:: + + for expr1 in sequence1: + if not (condition1): + continue # Skip this element + for expr2 in sequence2: + if not (condition2): + continue # Skip this element + ... + for exprN in sequenceN: + if not (conditionN): + continue # Skip this element + + # Output the value of + # the expression. + +This means that when there are multiple ``for...in`` clauses but no ``if`` +clauses, the length of the resulting output will be equal to the product of the +lengths of all the sequences. If you have two lists of length 3, the output +list is 9 elements long: + + >>> seq1 = 'abc' + >>> seq2 = (1, 2, 3) + >>> [(x, y) for x in seq1 for y in seq2] #doctest: +NORMALIZE_WHITESPACE + [('a', 1), ('a', 2), ('a', 3), + ('b', 1), ('b', 2), ('b', 3), + ('c', 1), ('c', 2), ('c', 3)] + +To avoid introducing an ambiguity into Python's grammar, if ``expression`` is +creating a tuple, it must be surrounded with parentheses. The first list +comprehension below is a syntax error, while the second one is correct:: + + # Syntax error + [x, y for x in seq1 for y in seq2] + # Correct + [(x, y) for x in seq1 for y in seq2] + + +Generators +========== + +Generators are a special class of functions that simplify the task of writing +iterators. Regular functions compute a value and return it, but generators +return an iterator that returns a stream of values. + +You're doubtless familiar with how regular function calls work in Python or C. +When you call a function, it gets a private namespace where its local variables +are created. When the function reaches a ``return`` statement, the local +variables are destroyed and the value is returned to the caller. A later call +to the same function creates a new private namespace and a fresh set of local +variables. But, what if the local variables weren't thrown away on exiting a +function? What if you could later resume the function where it left off? This +is what generators provide; they can be thought of as resumable functions. + +Here's the simplest example of a generator function: + + >>> def generate_ints(N): + ... for i in range(N): + ... yield i + +Any function containing a :keyword:`yield` keyword is a generator function; +this is detected by Python's :term:`bytecode` compiler which compiles the +function specially as a result. + +When you call a generator function, it doesn't return a single value; instead it +returns a generator object that supports the iterator protocol. On executing +the ``yield`` expression, the generator outputs the value of ``i``, similar to a +``return`` statement. The big difference between ``yield`` and a ``return`` +statement is that on reaching a ``yield`` the generator's state of execution is +suspended and local variables are preserved. On the next call to the +generator's :meth:`~generator.__next__` method, the function will resume +executing. + +Here's a sample usage of the ``generate_ints()`` generator: + + >>> gen = generate_ints(3) + >>> gen #doctest: +ELLIPSIS + <generator object generate_ints at ...> + >>> next(gen) + 0 + >>> next(gen) + 1 + >>> next(gen) + 2 + >>> next(gen) + Traceback (most recent call last): + File "stdin", line 1, in <module> + File "stdin", line 2, in generate_ints + StopIteration + +You could equally write ``for i in generate_ints(5)``, or ``a, b, c = +generate_ints(3)``. + +Inside a generator function, ``return value`` causes ``StopIteration(value)`` +to be raised from the :meth:`~generator.__next__` method. Once this happens, or +the bottom of the function is reached, the procession of values ends and the +generator cannot yield any further values. + +You could achieve the effect of generators manually by writing your own class +and storing all the local variables of the generator as instance variables. For +example, returning a list of integers could be done by setting ``self.count`` to +0, and having the :meth:`~iterator.__next__` method increment ``self.count`` and +return it. +However, for a moderately complicated generator, writing a corresponding class +can be much messier. + +The test suite included with Python's library, +:source:`Lib/test/test_generators.py`, contains +a number of more interesting examples. Here's one generator that implements an +in-order traversal of a tree using generators recursively. :: + + # A recursive generator that generates Tree leaves in in-order. + def inorder(t): + if t: + for x in inorder(t.left): + yield x + + yield t.label + + for x in inorder(t.right): + yield x + +Two other examples in ``test_generators.py`` produce solutions for the N-Queens +problem (placing N queens on an NxN chess board so that no queen threatens +another) and the Knight's Tour (finding a route that takes a knight to every +square of an NxN chessboard without visiting any square twice). + + + +Passing values into a generator +------------------------------- + +In Python 2.4 and earlier, generators only produced output. Once a generator's +code was invoked to create an iterator, there was no way to pass any new +information into the function when its execution is resumed. You could hack +together this ability by making the generator look at a global variable or by +passing in some mutable object that callers then modify, but these approaches +are messy. + +In Python 2.5 there's a simple way to pass values into a generator. +:keyword:`yield` became an expression, returning a value that can be assigned to +a variable or otherwise operated on:: + + val = (yield i) + +I recommend that you **always** put parentheses around a ``yield`` expression +when you're doing something with the returned value, as in the above example. +The parentheses aren't always necessary, but it's easier to always add them +instead of having to remember when they're needed. + +(:pep:`342` explains the exact rules, which are that a ``yield``-expression must +always be parenthesized except when it occurs at the top-level expression on the +right-hand side of an assignment. This means you can write ``val = yield i`` +but have to use parentheses when there's an operation, as in ``val = (yield i) ++ 12``.) + +Values are sent into a generator by calling its :meth:`send(value) +<generator.send>` method. This method resumes the generator's code and the +``yield`` expression returns the specified value. If the regular +:meth:`~generator.__next__` method is called, the ``yield`` returns ``None``. + +Here's a simple counter that increments by 1 and allows changing the value of +the internal counter. + +.. testcode:: + + def counter(maximum): + i = 0 + while i < maximum: + val = (yield i) + # If value provided, change counter + if val is not None: + i = val + else: + i += 1 + +And here's an example of changing the counter: + + >>> it = counter(10) #doctest: +SKIP + >>> next(it) #doctest: +SKIP + 0 + >>> next(it) #doctest: +SKIP + 1 + >>> it.send(8) #doctest: +SKIP + 8 + >>> next(it) #doctest: +SKIP + 9 + >>> next(it) #doctest: +SKIP + Traceback (most recent call last): + File "t.py", line 15, in <module> + it.next() + StopIteration + +Because ``yield`` will often be returning ``None``, you should always check for +this case. Don't just use its value in expressions unless you're sure that the +:meth:`~generator.send` method will be the only method used to resume your +generator function. + +In addition to :meth:`~generator.send`, there are two other methods on +generators: + +* :meth:`throw(type, value=None, traceback=None) <generator.throw>` is used to + raise an exception inside the generator; the exception is raised by the + ``yield`` expression where the generator's execution is paused. + +* :meth:`~generator.close` raises a :exc:`GeneratorExit` exception inside the + generator to terminate the iteration. On receiving this exception, the + generator's code must either raise :exc:`GeneratorExit` or + :exc:`StopIteration`; catching the exception and doing anything else is + illegal and will trigger a :exc:`RuntimeError`. :meth:`~generator.close` + will also be called by Python's garbage collector when the generator is + garbage-collected. + + If you need to run cleanup code when a :exc:`GeneratorExit` occurs, I suggest + using a ``try: ... finally:`` suite instead of catching :exc:`GeneratorExit`. + +The cumulative effect of these changes is to turn generators from one-way +producers of information into both producers and consumers. + +Generators also become **coroutines**, a more generalized form of subroutines. +Subroutines are entered at one point and exited at another point (the top of the +function, and a ``return`` statement), but coroutines can be entered, exited, +and resumed at many different points (the ``yield`` statements). + + +Built-in functions +================== + +Let's look in more detail at built-in functions often used with iterators. + +Two of Python's built-in functions, :func:`map` and :func:`filter` duplicate the +features of generator expressions: + +:func:`map(f, iterA, iterB, ...) <map>` returns an iterator over the sequence + ``f(iterA[0], iterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...``. + + >>> def upper(s): + ... return s.upper() + + >>> list(map(upper, ['sentence', 'fragment'])) + ['SENTENCE', 'FRAGMENT'] + >>> [upper(s) for s in ['sentence', 'fragment']] + ['SENTENCE', 'FRAGMENT'] + +You can of course achieve the same effect with a list comprehension. + +:func:`filter(predicate, iter) <filter>` returns an iterator over all the +sequence elements that meet a certain condition, and is similarly duplicated by +list comprehensions. A **predicate** is a function that returns the truth +value of some condition; for use with :func:`filter`, the predicate must take a +single value. + + >>> def is_even(x): + ... return (x % 2) == 0 + + >>> list(filter(is_even, range(10))) + [0, 2, 4, 6, 8] + + +This can also be written as a list comprehension: + + >>> list(x for x in range(10) if is_even(x)) + [0, 2, 4, 6, 8] + + +:func:`enumerate(iter, start=0) <enumerate>` counts off the elements in the +iterable returning 2-tuples containing the count (from *start*) and +each element. :: + + >>> for item in enumerate(['subject', 'verb', 'object']): + ... print(item) + (0, 'subject') + (1, 'verb') + (2, 'object') + +:func:`enumerate` is often used when looping through a list and recording the +indexes at which certain conditions are met:: + + f = open('data.txt', 'r') + for i, line in enumerate(f): + if line.strip() == '': + print('Blank line at line #%i' % i) + +:func:`sorted(iterable, key=None, reverse=False) <sorted>` collects all the +elements of the iterable into a list, sorts the list, and returns the sorted +result. The *key* and *reverse* arguments are passed through to the +constructed list's :meth:`~list.sort` method. :: + + >>> import random + >>> # Generate 8 random numbers between [0, 10000) + >>> rand_list = random.sample(range(10000), 8) + >>> rand_list #doctest: +SKIP + [769, 7953, 9828, 6431, 8442, 9878, 6213, 2207] + >>> sorted(rand_list) #doctest: +SKIP + [769, 2207, 6213, 6431, 7953, 8442, 9828, 9878] + >>> sorted(rand_list, reverse=True) #doctest: +SKIP + [9878, 9828, 8442, 7953, 6431, 6213, 2207, 769] + +(For a more detailed discussion of sorting, see the :ref:`sortinghowto`.) + + +The :func:`any(iter) <any>` and :func:`all(iter) <all>` built-ins look at the +truth values of an iterable's contents. :func:`any` returns ``True`` if any element +in the iterable is a true value, and :func:`all` returns ``True`` if all of the +elements are true values: + + >>> any([0, 1, 0]) + True + >>> any([0, 0, 0]) + False + >>> any([1, 1, 1]) + True + >>> all([0, 1, 0]) + False + >>> all([0, 0, 0]) + False + >>> all([1, 1, 1]) + True + + +:func:`zip(iterA, iterB, ...) <zip>` takes one element from each iterable and +returns them in a tuple:: + + zip(['a', 'b', 'c'], (1, 2, 3)) => + ('a', 1), ('b', 2), ('c', 3) + +It doesn't construct an in-memory list and exhaust all the input iterators +before returning; instead tuples are constructed and returned only if they're +requested. (The technical term for this behaviour is `lazy evaluation +<https://en.wikipedia.org/wiki/Lazy_evaluation>`__.) + +This iterator is intended to be used with iterables that are all of the same +length. If the iterables are of different lengths, the resulting stream will be +the same length as the shortest iterable. :: + + zip(['a', 'b'], (1, 2, 3)) => + ('a', 1), ('b', 2) + +You should avoid doing this, though, because an element may be taken from the +longer iterators and discarded. This means you can't go on to use the iterators +further because you risk skipping a discarded element. + + +The itertools module +==================== + +The :mod:`itertools` module contains a number of commonly-used iterators as well +as functions for combining several iterators. This section will introduce the +module's contents by showing small examples. + +The module's functions fall into a few broad classes: + +* Functions that create a new iterator based on an existing iterator. +* Functions for treating an iterator's elements as function arguments. +* Functions for selecting portions of an iterator's output. +* A function for grouping an iterator's output. + +Creating new iterators +---------------------- + +:func:`itertools.count(start, step) <itertools.count>` returns an infinite +stream of evenly spaced values. You can optionally supply the starting number, +which defaults to 0, and the interval between numbers, which defaults to 1:: + + itertools.count() => + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ... + itertools.count(10) => + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ... + itertools.count(10, 5) => + 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, ... + +:func:`itertools.cycle(iter) <itertools.cycle>` saves a copy of the contents of +a provided iterable and returns a new iterator that returns its elements from +first to last. The new iterator will repeat these elements infinitely. :: + + itertools.cycle([1, 2, 3, 4, 5]) => + 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ... + +:func:`itertools.repeat(elem, [n]) <itertools.repeat>` returns the provided +element *n* times, or returns the element endlessly if *n* is not provided. :: + + itertools.repeat('abc') => + abc, abc, abc, abc, abc, abc, abc, abc, abc, abc, ... + itertools.repeat('abc', 5) => + abc, abc, abc, abc, abc + +:func:`itertools.chain(iterA, iterB, ...) <itertools.chain>` takes an arbitrary +number of iterables as input, and returns all the elements of the first +iterator, then all the elements of the second, and so on, until all of the +iterables have been exhausted. :: + + itertools.chain(['a', 'b', 'c'], (1, 2, 3)) => + a, b, c, 1, 2, 3 + +:func:`itertools.islice(iter, [start], stop, [step]) <itertools.islice>` returns +a stream that's a slice of the iterator. With a single *stop* argument, it +will return the first *stop* elements. If you supply a starting index, you'll +get *stop-start* elements, and if you supply a value for *step*, elements +will be skipped accordingly. Unlike Python's string and list slicing, you can't +use negative values for *start*, *stop*, or *step*. :: + + itertools.islice(range(10), 8) => + 0, 1, 2, 3, 4, 5, 6, 7 + itertools.islice(range(10), 2, 8) => + 2, 3, 4, 5, 6, 7 + itertools.islice(range(10), 2, 8, 2) => + 2, 4, 6 + +:func:`itertools.tee(iter, [n]) <itertools.tee>` replicates an iterator; it +returns *n* independent iterators that will all return the contents of the +source iterator. +If you don't supply a value for *n*, the default is 2. Replicating iterators +requires saving some of the contents of the source iterator, so this can consume +significant memory if the iterator is large and one of the new iterators is +consumed more than the others. :: + + itertools.tee( itertools.count() ) => + iterA, iterB + + where iterA -> + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ... + + and iterB -> + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ... + + +Calling functions on elements +----------------------------- + +The :mod:`operator` module contains a set of functions corresponding to Python's +operators. Some examples are :func:`operator.add(a, b) <operator.add>` (adds +two values), :func:`operator.ne(a, b) <operator.ne>` (same as ``a != b``), and +:func:`operator.attrgetter('id') <operator.attrgetter>` +(returns a callable that fetches the ``.id`` attribute). + +:func:`itertools.starmap(func, iter) <itertools.starmap>` assumes that the +iterable will return a stream of tuples, and calls *func* using these tuples as +the arguments:: + + itertools.starmap(os.path.join, + [('/bin', 'python'), ('/usr', 'bin', 'java'), + ('/usr', 'bin', 'perl'), ('/usr', 'bin', 'ruby')]) + => + /bin/python, /usr/bin/java, /usr/bin/perl, /usr/bin/ruby + + +Selecting elements +------------------ + +Another group of functions chooses a subset of an iterator's elements based on a +predicate. + +:func:`itertools.filterfalse(predicate, iter) <itertools.filterfalse>` is the +opposite of :func:`filter`, returning all elements for which the predicate +returns false:: + + itertools.filterfalse(is_even, itertools.count()) => + 1, 3, 5, 7, 9, 11, 13, 15, ... + +:func:`itertools.takewhile(predicate, iter) <itertools.takewhile>` returns +elements for as long as the predicate returns true. Once the predicate returns +false, the iterator will signal the end of its results. :: + + def less_than_10(x): + return x < 10 + + itertools.takewhile(less_than_10, itertools.count()) => + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 + + itertools.takewhile(is_even, itertools.count()) => + 0 + +:func:`itertools.dropwhile(predicate, iter) <itertools.dropwhile>` discards +elements while the predicate returns true, and then returns the rest of the +iterable's results. :: + + itertools.dropwhile(less_than_10, itertools.count()) => + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ... + + itertools.dropwhile(is_even, itertools.count()) => + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ... + +:func:`itertools.compress(data, selectors) <itertools.compress>` takes two +iterators and returns only those elements of *data* for which the corresponding +element of *selectors* is true, stopping whenever either one is exhausted:: + + itertools.compress([1, 2, 3, 4, 5], [True, True, False, False, True]) => + 1, 2, 5 + + +Combinatoric functions +---------------------- + +The :func:`itertools.combinations(iterable, r) <itertools.combinations>` +returns an iterator giving all possible *r*-tuple combinations of the +elements contained in *iterable*. :: + + itertools.combinations([1, 2, 3, 4, 5], 2) => + (1, 2), (1, 3), (1, 4), (1, 5), + (2, 3), (2, 4), (2, 5), + (3, 4), (3, 5), + (4, 5) + + itertools.combinations([1, 2, 3, 4, 5], 3) => + (1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5), + (2, 3, 4), (2, 3, 5), (2, 4, 5), + (3, 4, 5) + +The elements within each tuple remain in the same order as +*iterable* returned them. For example, the number 1 is always before +2, 3, 4, or 5 in the examples above. A similar function, +:func:`itertools.permutations(iterable, r=None) <itertools.permutations>`, +removes this constraint on the order, returning all possible +arrangements of length *r*:: + + itertools.permutations([1, 2, 3, 4, 5], 2) => + (1, 2), (1, 3), (1, 4), (1, 5), + (2, 1), (2, 3), (2, 4), (2, 5), + (3, 1), (3, 2), (3, 4), (3, 5), + (4, 1), (4, 2), (4, 3), (4, 5), + (5, 1), (5, 2), (5, 3), (5, 4) + + itertools.permutations([1, 2, 3, 4, 5]) => + (1, 2, 3, 4, 5), (1, 2, 3, 5, 4), (1, 2, 4, 3, 5), + ... + (5, 4, 3, 2, 1) + +If you don't supply a value for *r* the length of the iterable is used, +meaning that all the elements are permuted. + +Note that these functions produce all of the possible combinations by +position and don't require that the contents of *iterable* are unique:: + + itertools.permutations('aba', 3) => + ('a', 'b', 'a'), ('a', 'a', 'b'), ('b', 'a', 'a'), + ('b', 'a', 'a'), ('a', 'a', 'b'), ('a', 'b', 'a') + +The identical tuple ``('a', 'a', 'b')`` occurs twice, but the two 'a' +strings came from different positions. + +The :func:`itertools.combinations_with_replacement(iterable, r) <itertools.combinations_with_replacement>` +function relaxes a different constraint: elements can be repeated +within a single tuple. Conceptually an element is selected for the +first position of each tuple and then is replaced before the second +element is selected. :: + + itertools.combinations_with_replacement([1, 2, 3, 4, 5], 2) => + (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), + (2, 2), (2, 3), (2, 4), (2, 5), + (3, 3), (3, 4), (3, 5), + (4, 4), (4, 5), + (5, 5) + + +Grouping elements +----------------- + +The last function I'll discuss, :func:`itertools.groupby(iter, key_func=None) +<itertools.groupby>`, is the most complicated. ``key_func(elem)`` is a function +that can compute a key value for each element returned by the iterable. If you +don't supply a key function, the key is simply each element itself. + +:func:`~itertools.groupby` collects all the consecutive elements from the +underlying iterable that have the same key value, and returns a stream of +2-tuples containing a key value and an iterator for the elements with that key. + +:: + + city_list = [('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL'), + ('Anchorage', 'AK'), ('Nome', 'AK'), + ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ'), + ... + ] + + def get_state(city_state): + return city_state[1] + + itertools.groupby(city_list, get_state) => + ('AL', iterator-1), + ('AK', iterator-2), + ('AZ', iterator-3), ... + + where + iterator-1 => + ('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL') + iterator-2 => + ('Anchorage', 'AK'), ('Nome', 'AK') + iterator-3 => + ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ') + +:func:`~itertools.groupby` assumes that the underlying iterable's contents will +already be sorted based on the key. Note that the returned iterators also use +the underlying iterable, so you have to consume the results of iterator-1 before +requesting iterator-2 and its corresponding key. + + +The functools module +==================== + +The :mod:`functools` module in Python 2.5 contains some higher-order functions. +A **higher-order function** takes one or more functions as input and returns a +new function. The most useful tool in this module is the +:func:`functools.partial` function. + +For programs written in a functional style, you'll sometimes want to construct +variants of existing functions that have some of the parameters filled in. +Consider a Python function ``f(a, b, c)``; you may wish to create a new function +``g(b, c)`` that's equivalent to ``f(1, b, c)``; you're filling in a value for +one of ``f()``'s parameters. This is called "partial function application". + +The constructor for :func:`~functools.partial` takes the arguments +``(function, arg1, arg2, ..., kwarg1=value1, kwarg2=value2)``. The resulting +object is callable, so you can just call it to invoke ``function`` with the +filled-in arguments. + +Here's a small but realistic example:: + + import functools + + def log(message, subsystem): + """Write the contents of 'message' to the specified subsystem.""" + print('%s: %s' % (subsystem, message)) + ... + + server_log = functools.partial(log, subsystem='server') + server_log('Unable to open socket') + +:func:`functools.reduce(func, iter, [initial_value]) <functools.reduce>` +cumulatively performs an operation on all the iterable's elements and, +therefore, can't be applied to infinite iterables. *func* must be a function +that takes two elements and returns a single value. :func:`functools.reduce` +takes the first two elements A and B returned by the iterator and calculates +``func(A, B)``. It then requests the third element, C, calculates +``func(func(A, B), C)``, combines this result with the fourth element returned, +and continues until the iterable is exhausted. If the iterable returns no +values at all, a :exc:`TypeError` exception is raised. If the initial value is +supplied, it's used as a starting point and ``func(initial_value, A)`` is the +first calculation. :: + + >>> import operator, functools + >>> functools.reduce(operator.concat, ['A', 'BB', 'C']) + 'ABBC' + >>> functools.reduce(operator.concat, []) + Traceback (most recent call last): + ... + TypeError: reduce() of empty sequence with no initial value + >>> functools.reduce(operator.mul, [1, 2, 3], 1) + 6 + >>> functools.reduce(operator.mul, [], 1) + 1 + +If you use :func:`operator.add` with :func:`functools.reduce`, you'll add up all the +elements of the iterable. This case is so common that there's a special +built-in called :func:`sum` to compute it: + + >>> import functools, operator + >>> functools.reduce(operator.add, [1, 2, 3, 4], 0) + 10 + >>> sum([1, 2, 3, 4]) + 10 + >>> sum([]) + 0 + +For many uses of :func:`functools.reduce`, though, it can be clearer to just +write the obvious :keyword:`for` loop:: + + import functools + # Instead of: + product = functools.reduce(operator.mul, [1, 2, 3], 1) + + # You can write: + product = 1 + for i in [1, 2, 3]: + product *= i + +A related function is :func:`itertools.accumulate(iterable, func=operator.add) +<itertools.accumulate>`. It performs the same calculation, but instead of +returning only the final result, :func:`accumulate` returns an iterator that +also yields each partial result:: + + itertools.accumulate([1, 2, 3, 4, 5]) => + 1, 3, 6, 10, 15 + + itertools.accumulate([1, 2, 3, 4, 5], operator.mul) => + 1, 2, 6, 24, 120 + + +The operator module +------------------- + +The :mod:`operator` module was mentioned earlier. It contains a set of +functions corresponding to Python's operators. These functions are often useful +in functional-style code because they save you from writing trivial functions +that perform a single operation. + +Some of the functions in this module are: + +* Math operations: ``add()``, ``sub()``, ``mul()``, ``floordiv()``, ``abs()``, ... +* Logical operations: ``not_()``, ``truth()``. +* Bitwise operations: ``and_()``, ``or_()``, ``invert()``. +* Comparisons: ``eq()``, ``ne()``, ``lt()``, ``le()``, ``gt()``, and ``ge()``. +* Object identity: ``is_()``, ``is_not()``. + +Consult the operator module's documentation for a complete list. + + +Small functions and the lambda expression +========================================= + +When writing functional-style programs, you'll often need little functions that +act as predicates or that combine elements in some way. + +If there's a Python built-in or a module function that's suitable, you don't +need to define a new function at all:: + + stripped_lines = [line.strip() for line in lines] + existing_files = filter(os.path.exists, file_list) + +If the function you need doesn't exist, you need to write it. One way to write +small functions is to use the :keyword:`lambda` expression. ``lambda`` takes a +number of parameters and an expression combining these parameters, and creates +an anonymous function that returns the value of the expression:: + + adder = lambda x, y: x+y + + print_assign = lambda name, value: name + '=' + str(value) + +An alternative is to just use the ``def`` statement and define a function in the +usual way:: + + def adder(x, y): + return x + y + + def print_assign(name, value): + return name + '=' + str(value) + +Which alternative is preferable? That's a style question; my usual course is to +avoid using ``lambda``. + +One reason for my preference is that ``lambda`` is quite limited in the +functions it can define. The result has to be computable as a single +expression, which means you can't have multiway ``if... elif... else`` +comparisons or ``try... except`` statements. If you try to do too much in a +``lambda`` statement, you'll end up with an overly complicated expression that's +hard to read. Quick, what's the following code doing? :: + + import functools + total = functools.reduce(lambda a, b: (0, a[1] + b[1]), items)[1] + +You can figure it out, but it takes time to disentangle the expression to figure +out what's going on. Using a short nested ``def`` statements makes things a +little bit better:: + + import functools + def combine(a, b): + return 0, a[1] + b[1] + + total = functools.reduce(combine, items)[1] + +But it would be best of all if I had simply used a ``for`` loop:: + + total = 0 + for a, b in items: + total += b + +Or the :func:`sum` built-in and a generator expression:: + + total = sum(b for a, b in items) + +Many uses of :func:`functools.reduce` are clearer when written as ``for`` loops. + +Fredrik Lundh once suggested the following set of rules for refactoring uses of +``lambda``: + +1. Write a lambda function. +2. Write a comment explaining what the heck that lambda does. +3. Study the comment for a while, and think of a name that captures the essence + of the comment. +4. Convert the lambda to a def statement, using that name. +5. Remove the comment. + +I really like these rules, but you're free to disagree +about whether this lambda-free style is better. + + +Revision History and Acknowledgements +===================================== + +The author would like to thank the following people for offering suggestions, +corrections and assistance with various drafts of this article: Ian Bicking, +Nick Coghlan, Nick Efford, Raymond Hettinger, Jim Jewett, Mike Krell, Leandro +Lameiro, Jussi Salmela, Collin Winter, Blake Winton. + +Version 0.1: posted June 30 2006. + +Version 0.11: posted July 1 2006. Typo fixes. + +Version 0.2: posted July 10 2006. Merged genexp and listcomp sections into one. +Typo fixes. + +Version 0.21: Added more references suggested on the tutor mailing list. + +Version 0.30: Adds a section on the ``functional`` module written by Collin +Winter; adds short section on the operator module; a few other edits. + + +References +========== + +General +------- + +**Structure and Interpretation of Computer Programs**, by Harold Abelson and +Gerald Jay Sussman with Julie Sussman. Full text at +https://mitpress.mit.edu/sicp/. In this classic textbook of computer science, +chapters 2 and 3 discuss the use of sequences and streams to organize the data +flow inside a program. The book uses Scheme for its examples, but many of the +design approaches described in these chapters are applicable to functional-style +Python code. + +http://www.defmacro.org/ramblings/fp.html: A general introduction to functional +programming that uses Java examples and has a lengthy historical introduction. + +https://en.wikipedia.org/wiki/Functional_programming: General Wikipedia entry +describing functional programming. + +https://en.wikipedia.org/wiki/Coroutine: Entry for coroutines. + +https://en.wikipedia.org/wiki/Currying: Entry for the concept of currying. + +Python-specific +--------------- + +http://gnosis.cx/TPiP/: The first chapter of David Mertz's book +:title-reference:`Text Processing in Python` discusses functional programming +for text processing, in the section titled "Utilizing Higher-Order Functions in +Text Processing". + +Mertz also wrote a 3-part series of articles on functional programming +for IBM's DeveloperWorks site; see +`part 1 <https://developer.ibm.com/articles/l-prog/>`__, +`part 2 <https://developer.ibm.com/tutorials/l-prog2/>`__, and +`part 3 <https://developer.ibm.com/tutorials/l-prog3/>`__, + + +Python documentation +-------------------- + +Documentation for the :mod:`itertools` module. + +Documentation for the :mod:`functools` module. + +Documentation for the :mod:`operator` module. + +:pep:`289`: "Generator Expressions" + +:pep:`342`: "Coroutines via Enhanced Generators" describes the new generator +features in Python 2.5. + +.. comment + + Handy little function for printing part of an iterator -- used + while writing this document. + + import itertools + def print_iter(it): + slice = itertools.islice(it, 10) + for elem in slice[:-1]: + sys.stdout.write(str(elem)) + sys.stdout.write(', ') + print(elem[-1]) diff --git a/cpython_2/environment/repo/Doc/howto/index.rst b/cpython_2/environment/repo/Doc/howto/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..593341cc2b8a1eb31ecf1b79b6b97feecf4c396c --- /dev/null +++ b/cpython_2/environment/repo/Doc/howto/index.rst @@ -0,0 +1,32 @@ +*************** + Python HOWTOs +*************** + +Python HOWTOs are documents that cover a single, specific topic, +and attempt to cover it fairly completely. Modelled on the Linux +Documentation Project's HOWTO collection, this collection is an +effort to foster documentation that's more detailed than the +Python Library Reference. + +Currently, the HOWTOs are: + +.. toctree:: + :maxdepth: 1 + + pyporting.rst + cporting.rst + curses.rst + descriptor.rst + functional.rst + logging.rst + logging-cookbook.rst + regex.rst + sockets.rst + sorting.rst + unicode.rst + urllib2.rst + argparse.rst + ipaddress.rst + clinic.rst + instrumentation.rst + diff --git a/cpython_2/environment/repo/Doc/howto/instrumentation.rst b/cpython_2/environment/repo/Doc/howto/instrumentation.rst new file mode 100644 index 0000000000000000000000000000000000000000..909deb5fed33fff52c6cd28249c3294541accc93 --- /dev/null +++ b/cpython_2/environment/repo/Doc/howto/instrumentation.rst @@ -0,0 +1,436 @@ +.. highlight:: shell-session + +.. _instrumentation: + +=============================================== +Instrumenting CPython with DTrace and SystemTap +=============================================== + +:author: David Malcolm +:author: Łukasz Langa + +DTrace and SystemTap are monitoring tools, each providing a way to inspect +what the processes on a computer system are doing. They both use +domain-specific languages allowing a user to write scripts which: + + - filter which processes are to be observed + - gather data from the processes of interest + - generate reports on the data + +As of Python 3.6, CPython can be built with embedded "markers", also +known as "probes", that can be observed by a DTrace or SystemTap script, +making it easier to monitor what the CPython processes on a system are +doing. + +.. impl-detail:: + + DTrace markers are implementation details of the CPython interpreter. + No guarantees are made about probe compatibility between versions of + CPython. DTrace scripts can stop working or work incorrectly without + warning when changing CPython versions. + + +Enabling the static markers +--------------------------- + +macOS comes with built-in support for DTrace. On Linux, in order to +build CPython with the embedded markers for SystemTap, the SystemTap +development tools must be installed. + +On a Linux machine, this can be done via:: + + $ yum install systemtap-sdt-devel + +or:: + + $ sudo apt-get install systemtap-sdt-dev + + +CPython must then be configured ``--with-dtrace``: + +.. code-block:: none + + checking for --with-dtrace... yes + +On macOS, you can list available DTrace probes by running a Python +process in the background and listing all probes made available by the +Python provider:: + + $ python3.6 -q & + $ sudo dtrace -l -P python$! # or: dtrace -l -m python3.6 + + ID PROVIDER MODULE FUNCTION NAME + 29564 python18035 python3.6 _PyEval_EvalFrameDefault function-entry + 29565 python18035 python3.6 dtrace_function_entry function-entry + 29566 python18035 python3.6 _PyEval_EvalFrameDefault function-return + 29567 python18035 python3.6 dtrace_function_return function-return + 29568 python18035 python3.6 collect gc-done + 29569 python18035 python3.6 collect gc-start + 29570 python18035 python3.6 _PyEval_EvalFrameDefault line + 29571 python18035 python3.6 maybe_dtrace_line line + +On Linux, you can verify if the SystemTap static markers are present in +the built binary by seeing if it contains a ".note.stapsdt" section. + +:: + + $ readelf -S ./python | grep .note.stapsdt + [30] .note.stapsdt NOTE 0000000000000000 00308d78 + +If you've built Python as a shared library (with --enable-shared), you +need to look instead within the shared library. For example:: + + $ readelf -S libpython3.3dm.so.1.0 | grep .note.stapsdt + [29] .note.stapsdt NOTE 0000000000000000 00365b68 + +Sufficiently modern readelf can print the metadata:: + + $ readelf -n ./python + + Displaying notes found at file offset 0x00000254 with length 0x00000020: + Owner Data size Description + GNU 0x00000010 NT_GNU_ABI_TAG (ABI version tag) + OS: Linux, ABI: 2.6.32 + + Displaying notes found at file offset 0x00000274 with length 0x00000024: + Owner Data size Description + GNU 0x00000014 NT_GNU_BUILD_ID (unique build ID bitstring) + Build ID: df924a2b08a7e89f6e11251d4602022977af2670 + + Displaying notes found at file offset 0x002d6c30 with length 0x00000144: + Owner Data size Description + stapsdt 0x00000031 NT_STAPSDT (SystemTap probe descriptors) + Provider: python + Name: gc__start + Location: 0x00000000004371c3, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6bf6 + Arguments: -4@%ebx + stapsdt 0x00000030 NT_STAPSDT (SystemTap probe descriptors) + Provider: python + Name: gc__done + Location: 0x00000000004374e1, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6bf8 + Arguments: -8@%rax + stapsdt 0x00000045 NT_STAPSDT (SystemTap probe descriptors) + Provider: python + Name: function__entry + Location: 0x000000000053db6c, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6be8 + Arguments: 8@%rbp 8@%r12 -4@%eax + stapsdt 0x00000046 NT_STAPSDT (SystemTap probe descriptors) + Provider: python + Name: function__return + Location: 0x000000000053dba8, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6bea + Arguments: 8@%rbp 8@%r12 -4@%eax + +The above metadata contains information for SystemTap describing how it +can patch strategically-placed machine code instructions to enable the +tracing hooks used by a SystemTap script. + + +Static DTrace probes +-------------------- + +The following example DTrace script can be used to show the call/return +hierarchy of a Python script, only tracing within the invocation of +a function called "start". In other words, import-time function +invocations are not going to be listed: + +.. code-block:: none + + self int indent; + + python$target:::function-entry + /copyinstr(arg1) == "start"/ + { + self->trace = 1; + } + + python$target:::function-entry + /self->trace/ + { + printf("%d\t%*s:", timestamp, 15, probename); + printf("%*s", self->indent, ""); + printf("%s:%s:%d\n", basename(copyinstr(arg0)), copyinstr(arg1), arg2); + self->indent++; + } + + python$target:::function-return + /self->trace/ + { + self->indent--; + printf("%d\t%*s:", timestamp, 15, probename); + printf("%*s", self->indent, ""); + printf("%s:%s:%d\n", basename(copyinstr(arg0)), copyinstr(arg1), arg2); + } + + python$target:::function-return + /copyinstr(arg1) == "start"/ + { + self->trace = 0; + } + +It can be invoked like this:: + + $ sudo dtrace -q -s call_stack.d -c "python3.6 script.py" + +The output looks like this: + +.. code-block:: none + + 156641360502280 function-entry:call_stack.py:start:23 + 156641360518804 function-entry: call_stack.py:function_1:1 + 156641360532797 function-entry: call_stack.py:function_3:9 + 156641360546807 function-return: call_stack.py:function_3:10 + 156641360563367 function-return: call_stack.py:function_1:2 + 156641360578365 function-entry: call_stack.py:function_2:5 + 156641360591757 function-entry: call_stack.py:function_1:1 + 156641360605556 function-entry: call_stack.py:function_3:9 + 156641360617482 function-return: call_stack.py:function_3:10 + 156641360629814 function-return: call_stack.py:function_1:2 + 156641360642285 function-return: call_stack.py:function_2:6 + 156641360656770 function-entry: call_stack.py:function_3:9 + 156641360669707 function-return: call_stack.py:function_3:10 + 156641360687853 function-entry: call_stack.py:function_4:13 + 156641360700719 function-return: call_stack.py:function_4:14 + 156641360719640 function-entry: call_stack.py:function_5:18 + 156641360732567 function-return: call_stack.py:function_5:21 + 156641360747370 function-return:call_stack.py:start:28 + + +Static SystemTap markers +------------------------ + +The low-level way to use the SystemTap integration is to use the static +markers directly. This requires you to explicitly state the binary file +containing them. + +For example, this SystemTap script can be used to show the call/return +hierarchy of a Python script: + +.. code-block:: none + + probe process("python").mark("function__entry") { + filename = user_string($arg1); + funcname = user_string($arg2); + lineno = $arg3; + + printf("%s => %s in %s:%d\\n", + thread_indent(1), funcname, filename, lineno); + } + + probe process("python").mark("function__return") { + filename = user_string($arg1); + funcname = user_string($arg2); + lineno = $arg3; + + printf("%s <= %s in %s:%d\\n", + thread_indent(-1), funcname, filename, lineno); + } + +It can be invoked like this:: + + $ stap \ + show-call-hierarchy.stp \ + -c "./python test.py" + +The output looks like this: + +.. code-block:: none + + 11408 python(8274): => __contains__ in Lib/_abcoll.py:362 + 11414 python(8274): => __getitem__ in Lib/os.py:425 + 11418 python(8274): => encode in Lib/os.py:490 + 11424 python(8274): <= encode in Lib/os.py:493 + 11428 python(8274): <= __getitem__ in Lib/os.py:426 + 11433 python(8274): <= __contains__ in Lib/_abcoll.py:366 + +where the columns are: + + - time in microseconds since start of script + + - name of executable + + - PID of process + +and the remainder indicates the call/return hierarchy as the script executes. + +For a `--enable-shared` build of CPython, the markers are contained within the +libpython shared library, and the probe's dotted path needs to reflect this. For +example, this line from the above example: + +.. code-block:: none + + probe process("python").mark("function__entry") { + +should instead read: + +.. code-block:: none + + probe process("python").library("libpython3.6dm.so.1.0").mark("function__entry") { + +(assuming a debug build of CPython 3.6) + + +Available static markers +------------------------ + +.. I'm reusing the "c:function" type for markers + +.. c:function:: function__entry(str filename, str funcname, int lineno) + + This marker indicates that execution of a Python function has begun. + It is only triggered for pure-Python (bytecode) functions. + + The filename, function name, and line number are provided back to the + tracing script as positional arguments, which must be accessed using + ``$arg1``, ``$arg2``, ``$arg3``: + + * ``$arg1`` : ``(const char *)`` filename, accessible using ``user_string($arg1)`` + + * ``$arg2`` : ``(const char *)`` function name, accessible using + ``user_string($arg2)`` + + * ``$arg3`` : ``int`` line number + +.. c:function:: function__return(str filename, str funcname, int lineno) + + This marker is the converse of :c:func:`function__entry`, and indicates that + execution of a Python function has ended (either via ``return``, or via an + exception). It is only triggered for pure-Python (bytecode) functions. + + The arguments are the same as for :c:func:`function__entry` + +.. c:function:: line(str filename, str funcname, int lineno) + + This marker indicates a Python line is about to be executed. It is + the equivalent of line-by-line tracing with a Python profiler. It is + not triggered within C functions. + + The arguments are the same as for :c:func:`function__entry`. + +.. c:function:: gc__start(int generation) + + Fires when the Python interpreter starts a garbage collection cycle. + ``arg0`` is the generation to scan, like :func:`gc.collect()`. + +.. c:function:: gc__done(long collected) + + Fires when the Python interpreter finishes a garbage collection + cycle. ``arg0`` is the number of collected objects. + +.. c:function:: import__find__load__start(str modulename) + + Fires before :mod:`importlib` attempts to find and load the module. + ``arg0`` is the module name. + + .. versionadded:: 3.7 + +.. c:function:: import__find__load__done(str modulename, int found) + + Fires after :mod:`importlib`'s find_and_load function is called. + ``arg0`` is the module name, ``arg1`` indicates if module was + successfully loaded. + + .. versionadded:: 3.7 + + +.. c:function:: audit(str event, void *tuple) + + Fires when :func:`sys.audit` or :c:func:`PySys_Audit` is called. + ``arg0`` is the event name as C string, ``arg1`` is a :c:type:`PyObject` + pointer to a tuple object. + + .. versionadded:: 3.8 + + +SystemTap Tapsets +----------------- + +The higher-level way to use the SystemTap integration is to use a "tapset": +SystemTap's equivalent of a library, which hides some of the lower-level +details of the static markers. + +Here is a tapset file, based on a non-shared build of CPython: + +.. code-block:: none + + /* + Provide a higher-level wrapping around the function__entry and + function__return markers: + \*/ + probe python.function.entry = process("python").mark("function__entry") + { + filename = user_string($arg1); + funcname = user_string($arg2); + lineno = $arg3; + frameptr = $arg4 + } + probe python.function.return = process("python").mark("function__return") + { + filename = user_string($arg1); + funcname = user_string($arg2); + lineno = $arg3; + frameptr = $arg4 + } + +If this file is installed in SystemTap's tapset directory (e.g. +``/usr/share/systemtap/tapset``), then these additional probepoints become +available: + +.. c:function:: python.function.entry(str filename, str funcname, int lineno, frameptr) + + This probe point indicates that execution of a Python function has begun. + It is only triggered for pure-Python (bytecode) functions. + +.. c:function:: python.function.return(str filename, str funcname, int lineno, frameptr) + + This probe point is the converse of :c:func:`python.function.return`, and + indicates that execution of a Python function has ended (either via + ``return``, or via an exception). It is only triggered for pure-Python + (bytecode) functions. + + +Examples +-------- +This SystemTap script uses the tapset above to more cleanly implement the +example given above of tracing the Python function-call hierarchy, without +needing to directly name the static markers: + +.. code-block:: none + + probe python.function.entry + { + printf("%s => %s in %s:%d\n", + thread_indent(1), funcname, filename, lineno); + } + + probe python.function.return + { + printf("%s <= %s in %s:%d\n", + thread_indent(-1), funcname, filename, lineno); + } + + +The following script uses the tapset above to provide a top-like view of all +running CPython code, showing the top 20 most frequently-entered bytecode +frames, each second, across the whole system: + +.. code-block:: none + + global fn_calls; + + probe python.function.entry + { + fn_calls[pid(), filename, funcname, lineno] += 1; + } + + probe timer.ms(1000) { + printf("\033[2J\033[1;1H") /* clear screen \*/ + printf("%6s %80s %6s %30s %6s\n", + "PID", "FILENAME", "LINE", "FUNCTION", "CALLS") + foreach ([pid, filename, funcname, lineno] in fn_calls- limit 20) { + printf("%6d %80s %6d %30s %6d\n", + pid, filename, lineno, funcname, + fn_calls[pid, filename, funcname, lineno]); + } + delete fn_calls; + } + diff --git a/cpython_2/environment/repo/Doc/howto/ipaddress.rst b/cpython_2/environment/repo/Doc/howto/ipaddress.rst new file mode 100644 index 0000000000000000000000000000000000000000..452e3671060a5ebd4491be74c2d43980f89294ff --- /dev/null +++ b/cpython_2/environment/repo/Doc/howto/ipaddress.rst @@ -0,0 +1,340 @@ +.. testsetup:: + + import ipaddress + +.. _ipaddress-howto: + +*************************************** +An introduction to the ipaddress module +*************************************** + +:author: Peter Moody +:author: Nick Coghlan + +.. topic:: Overview + + This document aims to provide a gentle introduction to the + :mod:`ipaddress` module. It is aimed primarily at users that aren't + already familiar with IP networking terminology, but may also be useful + to network engineers wanting an overview of how :mod:`ipaddress` + represents IP network addressing concepts. + + +Creating Address/Network/Interface objects +========================================== + +Since :mod:`ipaddress` is a module for inspecting and manipulating IP addresses, +the first thing you'll want to do is create some objects. You can use +:mod:`ipaddress` to create objects from strings and integers. + + +A Note on IP Versions +--------------------- + +For readers that aren't particularly familiar with IP addressing, it's +important to know that the Internet Protocol is currently in the process +of moving from version 4 of the protocol to version 6. This transition is +occurring largely because version 4 of the protocol doesn't provide enough +addresses to handle the needs of the whole world, especially given the +increasing number of devices with direct connections to the internet. + +Explaining the details of the differences between the two versions of the +protocol is beyond the scope of this introduction, but readers need to at +least be aware that these two versions exist, and it will sometimes be +necessary to force the use of one version or the other. + + +IP Host Addresses +----------------- + +Addresses, often referred to as "host addresses" are the most basic unit +when working with IP addressing. The simplest way to create addresses is +to use the :func:`ipaddress.ip_address` factory function, which automatically +determines whether to create an IPv4 or IPv6 address based on the passed in +value: + + >>> ipaddress.ip_address('192.0.2.1') + IPv4Address('192.0.2.1') + >>> ipaddress.ip_address('2001:DB8::1') + IPv6Address('2001:db8::1') + +Addresses can also be created directly from integers. Values that will +fit within 32 bits are assumed to be IPv4 addresses:: + + >>> ipaddress.ip_address(3221225985) + IPv4Address('192.0.2.1') + >>> ipaddress.ip_address(42540766411282592856903984951653826561) + IPv6Address('2001:db8::1') + +To force the use of IPv4 or IPv6 addresses, the relevant classes can be +invoked directly. This is particularly useful to force creation of IPv6 +addresses for small integers:: + + >>> ipaddress.ip_address(1) + IPv4Address('0.0.0.1') + >>> ipaddress.IPv4Address(1) + IPv4Address('0.0.0.1') + >>> ipaddress.IPv6Address(1) + IPv6Address('::1') + + +Defining Networks +----------------- + +Host addresses are usually grouped together into IP networks, so +:mod:`ipaddress` provides a way to create, inspect and manipulate network +definitions. IP network objects are constructed from strings that define the +range of host addresses that are part of that network. The simplest form +for that information is a "network address/network prefix" pair, where the +prefix defines the number of leading bits that are compared to determine +whether or not an address is part of the network and the network address +defines the expected value of those bits. + +As for addresses, a factory function is provided that determines the correct +IP version automatically:: + + >>> ipaddress.ip_network('192.0.2.0/24') + IPv4Network('192.0.2.0/24') + >>> ipaddress.ip_network('2001:db8::0/96') + IPv6Network('2001:db8::/96') + +Network objects cannot have any host bits set. The practical effect of this +is that ``192.0.2.1/24`` does not describe a network. Such definitions are +referred to as interface objects since the ip-on-a-network notation is +commonly used to describe network interfaces of a computer on a given network +and are described further in the next section. + +By default, attempting to create a network object with host bits set will +result in :exc:`ValueError` being raised. To request that the +additional bits instead be coerced to zero, the flag ``strict=False`` can +be passed to the constructor:: + + >>> ipaddress.ip_network('192.0.2.1/24') + Traceback (most recent call last): + ... + ValueError: 192.0.2.1/24 has host bits set + >>> ipaddress.ip_network('192.0.2.1/24', strict=False) + IPv4Network('192.0.2.0/24') + +While the string form offers significantly more flexibility, networks can +also be defined with integers, just like host addresses. In this case, the +network is considered to contain only the single address identified by the +integer, so the network prefix includes the entire network address:: + + >>> ipaddress.ip_network(3221225984) + IPv4Network('192.0.2.0/32') + >>> ipaddress.ip_network(42540766411282592856903984951653826560) + IPv6Network('2001:db8::/128') + +As with addresses, creation of a particular kind of network can be forced +by calling the class constructor directly instead of using the factory +function. + + +Host Interfaces +--------------- + +As mentioned just above, if you need to describe an address on a particular +network, neither the address nor the network classes are sufficient. +Notation like ``192.0.2.1/24`` is commonly used by network engineers and the +people who write tools for firewalls and routers as shorthand for "the host +``192.0.2.1`` on the network ``192.0.2.0/24``", Accordingly, :mod:`ipaddress` +provides a set of hybrid classes that associate an address with a particular +network. The interface for creation is identical to that for defining network +objects, except that the address portion isn't constrained to being a network +address. + + >>> ipaddress.ip_interface('192.0.2.1/24') + IPv4Interface('192.0.2.1/24') + >>> ipaddress.ip_interface('2001:db8::1/96') + IPv6Interface('2001:db8::1/96') + +Integer inputs are accepted (as with networks), and use of a particular IP +version can be forced by calling the relevant constructor directly. + + +Inspecting Address/Network/Interface Objects +============================================ + +You've gone to the trouble of creating an IPv(4|6)(Address|Network|Interface) +object, so you probably want to get information about it. :mod:`ipaddress` +tries to make doing this easy and intuitive. + +Extracting the IP version:: + + >>> addr4 = ipaddress.ip_address('192.0.2.1') + >>> addr6 = ipaddress.ip_address('2001:db8::1') + >>> addr6.version + 6 + >>> addr4.version + 4 + +Obtaining the network from an interface:: + + >>> host4 = ipaddress.ip_interface('192.0.2.1/24') + >>> host4.network + IPv4Network('192.0.2.0/24') + >>> host6 = ipaddress.ip_interface('2001:db8::1/96') + >>> host6.network + IPv6Network('2001:db8::/96') + +Finding out how many individual addresses are in a network:: + + >>> net4 = ipaddress.ip_network('192.0.2.0/24') + >>> net4.num_addresses + 256 + >>> net6 = ipaddress.ip_network('2001:db8::0/96') + >>> net6.num_addresses + 4294967296 + +Iterating through the "usable" addresses on a network:: + + >>> net4 = ipaddress.ip_network('192.0.2.0/24') + >>> for x in net4.hosts(): + ... print(x) # doctest: +ELLIPSIS + 192.0.2.1 + 192.0.2.2 + 192.0.2.3 + 192.0.2.4 + ... + 192.0.2.252 + 192.0.2.253 + 192.0.2.254 + + +Obtaining the netmask (i.e. set bits corresponding to the network prefix) or +the hostmask (any bits that are not part of the netmask): + + >>> net4 = ipaddress.ip_network('192.0.2.0/24') + >>> net4.netmask + IPv4Address('255.255.255.0') + >>> net4.hostmask + IPv4Address('0.0.0.255') + >>> net6 = ipaddress.ip_network('2001:db8::0/96') + >>> net6.netmask + IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff::') + >>> net6.hostmask + IPv6Address('::ffff:ffff') + + +Exploding or compressing the address:: + + >>> addr6.exploded + '2001:0db8:0000:0000:0000:0000:0000:0001' + >>> addr6.compressed + '2001:db8::1' + >>> net6.exploded + '2001:0db8:0000:0000:0000:0000:0000:0000/96' + >>> net6.compressed + '2001:db8::/96' + +While IPv4 doesn't support explosion or compression, the associated objects +still provide the relevant properties so that version neutral code can +easily ensure the most concise or most verbose form is used for IPv6 +addresses while still correctly handling IPv4 addresses. + + +Networks as lists of Addresses +============================== + +It's sometimes useful to treat networks as lists. This means it is possible +to index them like this:: + + >>> net4[1] + IPv4Address('192.0.2.1') + >>> net4[-1] + IPv4Address('192.0.2.255') + >>> net6[1] + IPv6Address('2001:db8::1') + >>> net6[-1] + IPv6Address('2001:db8::ffff:ffff') + + +It also means that network objects lend themselves to using the list +membership test syntax like this:: + + if address in network: + # do something + +Containment testing is done efficiently based on the network prefix:: + + >>> addr4 = ipaddress.ip_address('192.0.2.1') + >>> addr4 in ipaddress.ip_network('192.0.2.0/24') + True + >>> addr4 in ipaddress.ip_network('192.0.3.0/24') + False + + +Comparisons +=========== + +:mod:`ipaddress` provides some simple, hopefully intuitive ways to compare +objects, where it makes sense:: + + >>> ipaddress.ip_address('192.0.2.1') < ipaddress.ip_address('192.0.2.2') + True + +A :exc:`TypeError` exception is raised if you try to compare objects of +different versions or different types. + + +Using IP Addresses with other modules +===================================== + +Other modules that use IP addresses (such as :mod:`socket`) usually won't +accept objects from this module directly. Instead, they must be coerced to +an integer or string that the other module will accept:: + + >>> addr4 = ipaddress.ip_address('192.0.2.1') + >>> str(addr4) + '192.0.2.1' + >>> int(addr4) + 3221225985 + + +Getting more detail when instance creation fails +================================================ + +When creating address/network/interface objects using the version-agnostic +factory functions, any errors will be reported as :exc:`ValueError` with +a generic error message that simply says the passed in value was not +recognized as an object of that type. The lack of a specific error is +because it's necessary to know whether the value is *supposed* to be IPv4 +or IPv6 in order to provide more detail on why it has been rejected. + +To support use cases where it is useful to have access to this additional +detail, the individual class constructors actually raise the +:exc:`ValueError` subclasses :exc:`ipaddress.AddressValueError` and +:exc:`ipaddress.NetmaskValueError` to indicate exactly which part of +the definition failed to parse correctly. + +The error messages are significantly more detailed when using the +class constructors directly. For example:: + + >>> ipaddress.ip_address("192.168.0.256") + Traceback (most recent call last): + ... + ValueError: '192.168.0.256' does not appear to be an IPv4 or IPv6 address + >>> ipaddress.IPv4Address("192.168.0.256") + Traceback (most recent call last): + ... + ipaddress.AddressValueError: Octet 256 (> 255) not permitted in '192.168.0.256' + + >>> ipaddress.ip_network("192.168.0.1/64") + Traceback (most recent call last): + ... + ValueError: '192.168.0.1/64' does not appear to be an IPv4 or IPv6 network + >>> ipaddress.IPv4Network("192.168.0.1/64") + Traceback (most recent call last): + ... + ipaddress.NetmaskValueError: '64' is not a valid netmask + +However, both of the module specific exceptions have :exc:`ValueError` as their +parent class, so if you're not concerned with the particular type of error, +you can still write code like the following:: + + try: + network = ipaddress.IPv4Network(address) + except ValueError: + print('address/netmask is invalid for IPv4:', address) + diff --git a/cpython_2/environment/repo/Doc/howto/logging-cookbook.rst b/cpython_2/environment/repo/Doc/howto/logging-cookbook.rst new file mode 100644 index 0000000000000000000000000000000000000000..17f4ff6e474c23ef688d97600484176f82cf53a7 --- /dev/null +++ b/cpython_2/environment/repo/Doc/howto/logging-cookbook.rst @@ -0,0 +1,2981 @@ +.. _logging-cookbook: + +================ +Logging Cookbook +================ + +:Author: Vinay Sajip <vinay_sajip at red-dove dot com> + +This page contains a number of recipes related to logging, which have been found +useful in the past. + +.. currentmodule:: logging + +Using logging in multiple modules +--------------------------------- + +Multiple calls to ``logging.getLogger('someLogger')`` return a reference to the +same logger object. This is true not only within the same module, but also +across modules as long as it is in the same Python interpreter process. It is +true for references to the same object; additionally, application code can +define and configure a parent logger in one module and create (but not +configure) a child logger in a separate module, and all logger calls to the +child will pass up to the parent. Here is a main module:: + + import logging + import auxiliary_module + + # create logger with 'spam_application' + logger = logging.getLogger('spam_application') + logger.setLevel(logging.DEBUG) + # create file handler which logs even debug messages + fh = logging.FileHandler('spam.log') + fh.setLevel(logging.DEBUG) + # create console handler with a higher log level + ch = logging.StreamHandler() + ch.setLevel(logging.ERROR) + # create formatter and add it to the handlers + formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') + fh.setFormatter(formatter) + ch.setFormatter(formatter) + # add the handlers to the logger + logger.addHandler(fh) + logger.addHandler(ch) + + logger.info('creating an instance of auxiliary_module.Auxiliary') + a = auxiliary_module.Auxiliary() + logger.info('created an instance of auxiliary_module.Auxiliary') + logger.info('calling auxiliary_module.Auxiliary.do_something') + a.do_something() + logger.info('finished auxiliary_module.Auxiliary.do_something') + logger.info('calling auxiliary_module.some_function()') + auxiliary_module.some_function() + logger.info('done with auxiliary_module.some_function()') + +Here is the auxiliary module:: + + import logging + + # create logger + module_logger = logging.getLogger('spam_application.auxiliary') + + class Auxiliary: + def __init__(self): + self.logger = logging.getLogger('spam_application.auxiliary.Auxiliary') + self.logger.info('creating an instance of Auxiliary') + + def do_something(self): + self.logger.info('doing something') + a = 1 + 1 + self.logger.info('done doing something') + + def some_function(): + module_logger.info('received a call to "some_function"') + +The output looks like this: + +.. code-block:: none + + 2005-03-23 23:47:11,663 - spam_application - INFO - + creating an instance of auxiliary_module.Auxiliary + 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO - + creating an instance of Auxiliary + 2005-03-23 23:47:11,665 - spam_application - INFO - + created an instance of auxiliary_module.Auxiliary + 2005-03-23 23:47:11,668 - spam_application - INFO - + calling auxiliary_module.Auxiliary.do_something + 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO - + doing something + 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO - + done doing something + 2005-03-23 23:47:11,670 - spam_application - INFO - + finished auxiliary_module.Auxiliary.do_something + 2005-03-23 23:47:11,671 - spam_application - INFO - + calling auxiliary_module.some_function() + 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO - + received a call to 'some_function' + 2005-03-23 23:47:11,673 - spam_application - INFO - + done with auxiliary_module.some_function() + +Logging from multiple threads +----------------------------- + +Logging from multiple threads requires no special effort. The following example +shows logging from the main (initial) thread and another thread:: + + import logging + import threading + import time + + def worker(arg): + while not arg['stop']: + logging.debug('Hi from myfunc') + time.sleep(0.5) + + def main(): + logging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d %(threadName)s %(message)s') + info = {'stop': False} + thread = threading.Thread(target=worker, args=(info,)) + thread.start() + while True: + try: + logging.debug('Hello from main') + time.sleep(0.75) + except KeyboardInterrupt: + info['stop'] = True + break + thread.join() + + if __name__ == '__main__': + main() + +When run, the script should print something like the following: + +.. code-block:: none + + 0 Thread-1 Hi from myfunc + 3 MainThread Hello from main + 505 Thread-1 Hi from myfunc + 755 MainThread Hello from main + 1007 Thread-1 Hi from myfunc + 1507 MainThread Hello from main + 1508 Thread-1 Hi from myfunc + 2010 Thread-1 Hi from myfunc + 2258 MainThread Hello from main + 2512 Thread-1 Hi from myfunc + 3009 MainThread Hello from main + 3013 Thread-1 Hi from myfunc + 3515 Thread-1 Hi from myfunc + 3761 MainThread Hello from main + 4017 Thread-1 Hi from myfunc + 4513 MainThread Hello from main + 4518 Thread-1 Hi from myfunc + +This shows the logging output interspersed as one might expect. This approach +works for more threads than shown here, of course. + +Multiple handlers and formatters +-------------------------------- + +Loggers are plain Python objects. The :meth:`~Logger.addHandler` method has no +minimum or maximum quota for the number of handlers you may add. Sometimes it +will be beneficial for an application to log all messages of all severities to a +text file while simultaneously logging errors or above to the console. To set +this up, simply configure the appropriate handlers. The logging calls in the +application code will remain unchanged. Here is a slight modification to the +previous simple module-based configuration example:: + + import logging + + logger = logging.getLogger('simple_example') + logger.setLevel(logging.DEBUG) + # create file handler which logs even debug messages + fh = logging.FileHandler('spam.log') + fh.setLevel(logging.DEBUG) + # create console handler with a higher log level + ch = logging.StreamHandler() + ch.setLevel(logging.ERROR) + # create formatter and add it to the handlers + formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') + ch.setFormatter(formatter) + fh.setFormatter(formatter) + # add the handlers to logger + logger.addHandler(ch) + logger.addHandler(fh) + + # 'application' code + logger.debug('debug message') + logger.info('info message') + logger.warning('warn message') + logger.error('error message') + logger.critical('critical message') + +Notice that the 'application' code does not care about multiple handlers. All +that changed was the addition and configuration of a new handler named *fh*. + +The ability to create new handlers with higher- or lower-severity filters can be +very helpful when writing and testing an application. Instead of using many +``print`` statements for debugging, use ``logger.debug``: Unlike the print +statements, which you will have to delete or comment out later, the logger.debug +statements can remain intact in the source code and remain dormant until you +need them again. At that time, the only change that needs to happen is to +modify the severity level of the logger and/or handler to debug. + +.. _multiple-destinations: + +Logging to multiple destinations +-------------------------------- + +Let's say you want to log to console and file with different message formats and +in differing circumstances. Say you want to log messages with levels of DEBUG +and higher to file, and those messages at level INFO and higher to the console. +Let's also assume that the file should contain timestamps, but the console +messages should not. Here's how you can achieve this:: + + import logging + + # set up logging to file - see previous section for more details + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', + datefmt='%m-%d %H:%M', + filename='/temp/myapp.log', + filemode='w') + # define a Handler which writes INFO messages or higher to the sys.stderr + console = logging.StreamHandler() + console.setLevel(logging.INFO) + # set a format which is simpler for console use + formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s') + # tell the handler to use this format + console.setFormatter(formatter) + # add the handler to the root logger + logging.getLogger('').addHandler(console) + + # Now, we can log to the root logger, or any other logger. First the root... + logging.info('Jackdaws love my big sphinx of quartz.') + + # Now, define a couple of other loggers which might represent areas in your + # application: + + logger1 = logging.getLogger('myapp.area1') + logger2 = logging.getLogger('myapp.area2') + + logger1.debug('Quick zephyrs blow, vexing daft Jim.') + logger1.info('How quickly daft jumping zebras vex.') + logger2.warning('Jail zesty vixen who grabbed pay from quack.') + logger2.error('The five boxing wizards jump quickly.') + +When you run this, on the console you will see + +.. code-block:: none + + root : INFO Jackdaws love my big sphinx of quartz. + myapp.area1 : INFO How quickly daft jumping zebras vex. + myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack. + myapp.area2 : ERROR The five boxing wizards jump quickly. + +and in the file you will see something like + +.. code-block:: none + + 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz. + 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim. + 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex. + 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack. + 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly. + +As you can see, the DEBUG message only shows up in the file. The other messages +are sent to both destinations. + +This example uses console and file handlers, but you can use any number and +combination of handlers you choose. + + +Configuration server example +---------------------------- + +Here is an example of a module using the logging configuration server:: + + import logging + import logging.config + import time + import os + + # read initial config file + logging.config.fileConfig('logging.conf') + + # create and start listener on port 9999 + t = logging.config.listen(9999) + t.start() + + logger = logging.getLogger('simpleExample') + + try: + # loop through logging calls to see the difference + # new configurations make, until Ctrl+C is pressed + while True: + logger.debug('debug message') + logger.info('info message') + logger.warning('warn message') + logger.error('error message') + logger.critical('critical message') + time.sleep(5) + except KeyboardInterrupt: + # cleanup + logging.config.stopListening() + t.join() + +And here is a script that takes a filename and sends that file to the server, +properly preceded with the binary-encoded length, as the new logging +configuration:: + + #!/usr/bin/env python + import socket, sys, struct + + with open(sys.argv[1], 'rb') as f: + data_to_send = f.read() + + HOST = 'localhost' + PORT = 9999 + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + print('connecting...') + s.connect((HOST, PORT)) + print('sending config...') + s.send(struct.pack('>L', len(data_to_send))) + s.send(data_to_send) + s.close() + print('complete') + + +Dealing with handlers that block +-------------------------------- + +.. currentmodule:: logging.handlers + +Sometimes you have to get your logging handlers to do their work without +blocking the thread you're logging from. This is common in Web applications, +though of course it also occurs in other scenarios. + +A common culprit which demonstrates sluggish behaviour is the +:class:`SMTPHandler`: sending emails can take a long time, for a +number of reasons outside the developer's control (for example, a poorly +performing mail or network infrastructure). But almost any network-based +handler can block: Even a :class:`SocketHandler` operation may do a +DNS query under the hood which is too slow (and this query can be deep in the +socket library code, below the Python layer, and outside your control). + +One solution is to use a two-part approach. For the first part, attach only a +:class:`QueueHandler` to those loggers which are accessed from +performance-critical threads. They simply write to their queue, which can be +sized to a large enough capacity or initialized with no upper bound to their +size. The write to the queue will typically be accepted quickly, though you +will probably need to catch the :exc:`queue.Full` exception as a precaution +in your code. If you are a library developer who has performance-critical +threads in their code, be sure to document this (together with a suggestion to +attach only ``QueueHandlers`` to your loggers) for the benefit of other +developers who will use your code. + +The second part of the solution is :class:`QueueListener`, which has been +designed as the counterpart to :class:`QueueHandler`. A +:class:`QueueListener` is very simple: it's passed a queue and some handlers, +and it fires up an internal thread which listens to its queue for LogRecords +sent from ``QueueHandlers`` (or any other source of ``LogRecords``, for that +matter). The ``LogRecords`` are removed from the queue and passed to the +handlers for processing. + +The advantage of having a separate :class:`QueueListener` class is that you +can use the same instance to service multiple ``QueueHandlers``. This is more +resource-friendly than, say, having threaded versions of the existing handler +classes, which would eat up one thread per handler for no particular benefit. + +An example of using these two classes follows (imports omitted):: + + que = queue.Queue(-1) # no limit on size + queue_handler = QueueHandler(que) + handler = logging.StreamHandler() + listener = QueueListener(que, handler) + root = logging.getLogger() + root.addHandler(queue_handler) + formatter = logging.Formatter('%(threadName)s: %(message)s') + handler.setFormatter(formatter) + listener.start() + # The log output will display the thread which generated + # the event (the main thread) rather than the internal + # thread which monitors the internal queue. This is what + # you want to happen. + root.warning('Look out!') + listener.stop() + +which, when run, will produce: + +.. code-block:: none + + MainThread: Look out! + +.. versionchanged:: 3.5 + Prior to Python 3.5, the :class:`QueueListener` always passed every message + received from the queue to every handler it was initialized with. (This was + because it was assumed that level filtering was all done on the other side, + where the queue is filled.) From 3.5 onwards, this behaviour can be changed + by passing a keyword argument ``respect_handler_level=True`` to the + listener's constructor. When this is done, the listener compares the level + of each message with the handler's level, and only passes a message to a + handler if it's appropriate to do so. + +.. _network-logging: + +Sending and receiving logging events across a network +----------------------------------------------------- + +Let's say you want to send logging events across a network, and handle them at +the receiving end. A simple way of doing this is attaching a +:class:`SocketHandler` instance to the root logger at the sending end:: + + import logging, logging.handlers + + rootLogger = logging.getLogger('') + rootLogger.setLevel(logging.DEBUG) + socketHandler = logging.handlers.SocketHandler('localhost', + logging.handlers.DEFAULT_TCP_LOGGING_PORT) + # don't bother with a formatter, since a socket handler sends the event as + # an unformatted pickle + rootLogger.addHandler(socketHandler) + + # Now, we can log to the root logger, or any other logger. First the root... + logging.info('Jackdaws love my big sphinx of quartz.') + + # Now, define a couple of other loggers which might represent areas in your + # application: + + logger1 = logging.getLogger('myapp.area1') + logger2 = logging.getLogger('myapp.area2') + + logger1.debug('Quick zephyrs blow, vexing daft Jim.') + logger1.info('How quickly daft jumping zebras vex.') + logger2.warning('Jail zesty vixen who grabbed pay from quack.') + logger2.error('The five boxing wizards jump quickly.') + +At the receiving end, you can set up a receiver using the :mod:`socketserver` +module. Here is a basic working example:: + + import pickle + import logging + import logging.handlers + import socketserver + import struct + + + class LogRecordStreamHandler(socketserver.StreamRequestHandler): + """Handler for a streaming logging request. + + This basically logs the record using whatever logging policy is + configured locally. + """ + + def handle(self): + """ + Handle multiple requests - each expected to be a 4-byte length, + followed by the LogRecord in pickle format. Logs the record + according to whatever policy is configured locally. + """ + while True: + chunk = self.connection.recv(4) + if len(chunk) < 4: + break + slen = struct.unpack('>L', chunk)[0] + chunk = self.connection.recv(slen) + while len(chunk) < slen: + chunk = chunk + self.connection.recv(slen - len(chunk)) + obj = self.unPickle(chunk) + record = logging.makeLogRecord(obj) + self.handleLogRecord(record) + + def unPickle(self, data): + return pickle.loads(data) + + def handleLogRecord(self, record): + # if a name is specified, we use the named logger rather than the one + # implied by the record. + if self.server.logname is not None: + name = self.server.logname + else: + name = record.name + logger = logging.getLogger(name) + # N.B. EVERY record gets logged. This is because Logger.handle + # is normally called AFTER logger-level filtering. If you want + # to do filtering, do it at the client end to save wasting + # cycles and network bandwidth! + logger.handle(record) + + class LogRecordSocketReceiver(socketserver.ThreadingTCPServer): + """ + Simple TCP socket-based logging receiver suitable for testing. + """ + + allow_reuse_address = True + + def __init__(self, host='localhost', + port=logging.handlers.DEFAULT_TCP_LOGGING_PORT, + handler=LogRecordStreamHandler): + socketserver.ThreadingTCPServer.__init__(self, (host, port), handler) + self.abort = 0 + self.timeout = 1 + self.logname = None + + def serve_until_stopped(self): + import select + abort = 0 + while not abort: + rd, wr, ex = select.select([self.socket.fileno()], + [], [], + self.timeout) + if rd: + self.handle_request() + abort = self.abort + + def main(): + logging.basicConfig( + format='%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s') + tcpserver = LogRecordSocketReceiver() + print('About to start TCP server...') + tcpserver.serve_until_stopped() + + if __name__ == '__main__': + main() + +First run the server, and then the client. On the client side, nothing is +printed on the console; on the server side, you should see something like: + +.. code-block:: none + + About to start TCP server... + 59 root INFO Jackdaws love my big sphinx of quartz. + 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim. + 69 myapp.area1 INFO How quickly daft jumping zebras vex. + 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack. + 69 myapp.area2 ERROR The five boxing wizards jump quickly. + +Note that there are some security issues with pickle in some scenarios. If +these affect you, you can use an alternative serialization scheme by overriding +the :meth:`~handlers.SocketHandler.makePickle` method and implementing your +alternative there, as well as adapting the above script to use your alternative +serialization. + + +.. _context-info: + +Adding contextual information to your logging output +---------------------------------------------------- + +Sometimes you want logging output to contain contextual information in +addition to the parameters passed to the logging call. For example, in a +networked application, it may be desirable to log client-specific information +in the log (e.g. remote client's username, or IP address). Although you could +use the *extra* parameter to achieve this, it's not always convenient to pass +the information in this way. While it might be tempting to create +:class:`Logger` instances on a per-connection basis, this is not a good idea +because these instances are not garbage collected. While this is not a problem +in practice, when the number of :class:`Logger` instances is dependent on the +level of granularity you want to use in logging an application, it could +be hard to manage if the number of :class:`Logger` instances becomes +effectively unbounded. + + +Using LoggerAdapters to impart contextual information +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +An easy way in which you can pass contextual information to be output along +with logging event information is to use the :class:`LoggerAdapter` class. +This class is designed to look like a :class:`Logger`, so that you can call +:meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`, +:meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the +same signatures as their counterparts in :class:`Logger`, so you can use the +two types of instances interchangeably. + +When you create an instance of :class:`LoggerAdapter`, you pass it a +:class:`Logger` instance and a dict-like object which contains your contextual +information. When you call one of the logging methods on an instance of +:class:`LoggerAdapter`, it delegates the call to the underlying instance of +:class:`Logger` passed to its constructor, and arranges to pass the contextual +information in the delegated call. Here's a snippet from the code of +:class:`LoggerAdapter`:: + + def debug(self, msg, /, *args, **kwargs): + """ + Delegate a debug call to the underlying logger, after adding + contextual information from this adapter instance. + """ + msg, kwargs = self.process(msg, kwargs) + self.logger.debug(msg, *args, **kwargs) + +The :meth:`~LoggerAdapter.process` method of :class:`LoggerAdapter` is where the +contextual information is added to the logging output. It's passed the message +and keyword arguments of the logging call, and it passes back (potentially) +modified versions of these to use in the call to the underlying logger. The +default implementation of this method leaves the message alone, but inserts +an 'extra' key in the keyword argument whose value is the dict-like object +passed to the constructor. Of course, if you had passed an 'extra' keyword +argument in the call to the adapter, it will be silently overwritten. + +The advantage of using 'extra' is that the values in the dict-like object are +merged into the :class:`LogRecord` instance's __dict__, allowing you to use +customized strings with your :class:`Formatter` instances which know about +the keys of the dict-like object. If you need a different method, e.g. if you +want to prepend or append the contextual information to the message string, +you just need to subclass :class:`LoggerAdapter` and override +:meth:`~LoggerAdapter.process` to do what you need. Here is a simple example:: + + class CustomAdapter(logging.LoggerAdapter): + """ + This example adapter expects the passed in dict-like object to have a + 'connid' key, whose value in brackets is prepended to the log message. + """ + def process(self, msg, kwargs): + return '[%s] %s' % (self.extra['connid'], msg), kwargs + +which you can use like this:: + + logger = logging.getLogger(__name__) + adapter = CustomAdapter(logger, {'connid': some_conn_id}) + +Then any events that you log to the adapter will have the value of +``some_conn_id`` prepended to the log messages. + +Using objects other than dicts to pass contextual information +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You don't need to pass an actual dict to a :class:`LoggerAdapter` - you could +pass an instance of a class which implements ``__getitem__`` and ``__iter__`` so +that it looks like a dict to logging. This would be useful if you want to +generate values dynamically (whereas the values in a dict would be constant). + + +.. _filters-contextual: + +Using Filters to impart contextual information +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +You can also add contextual information to log output using a user-defined +:class:`Filter`. ``Filter`` instances are allowed to modify the ``LogRecords`` +passed to them, including adding additional attributes which can then be output +using a suitable format string, or if needed a custom :class:`Formatter`. + +For example in a web application, the request being processed (or at least, +the interesting parts of it) can be stored in a threadlocal +(:class:`threading.local`) variable, and then accessed from a ``Filter`` to +add, say, information from the request - say, the remote IP address and remote +user's username - to the ``LogRecord``, using the attribute names 'ip' and +'user' as in the ``LoggerAdapter`` example above. In that case, the same format +string can be used to get similar output to that shown above. Here's an example +script:: + + import logging + from random import choice + + class ContextFilter(logging.Filter): + """ + This is a filter which injects contextual information into the log. + + Rather than use actual contextual information, we just use random + data in this demo. + """ + + USERS = ['jim', 'fred', 'sheila'] + IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1'] + + def filter(self, record): + + record.ip = choice(ContextFilter.IPS) + record.user = choice(ContextFilter.USERS) + return True + + if __name__ == '__main__': + levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL) + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s') + a1 = logging.getLogger('a.b.c') + a2 = logging.getLogger('d.e.f') + + f = ContextFilter() + a1.addFilter(f) + a2.addFilter(f) + a1.debug('A debug message') + a1.info('An info message with %s', 'some parameters') + for x in range(10): + lvl = choice(levels) + lvlname = logging.getLevelName(lvl) + a2.log(lvl, 'A message at %s level with %d %s', lvlname, 2, 'parameters') + +which, when run, produces something like: + +.. code-block:: none + + 2010-09-06 22:38:15,292 a.b.c DEBUG IP: 123.231.231.123 User: fred A debug message + 2010-09-06 22:38:15,300 a.b.c INFO IP: 192.168.0.1 User: sheila An info message with some parameters + 2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1 User: sheila A message at CRITICAL level with 2 parameters + 2010-09-06 22:38:15,300 d.e.f ERROR IP: 127.0.0.1 User: jim A message at ERROR level with 2 parameters + 2010-09-06 22:38:15,300 d.e.f DEBUG IP: 127.0.0.1 User: sheila A message at DEBUG level with 2 parameters + 2010-09-06 22:38:15,300 d.e.f ERROR IP: 123.231.231.123 User: fred A message at ERROR level with 2 parameters + 2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 192.168.0.1 User: jim A message at CRITICAL level with 2 parameters + 2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1 User: sheila A message at CRITICAL level with 2 parameters + 2010-09-06 22:38:15,300 d.e.f DEBUG IP: 192.168.0.1 User: jim A message at DEBUG level with 2 parameters + 2010-09-06 22:38:15,301 d.e.f ERROR IP: 127.0.0.1 User: sheila A message at ERROR level with 2 parameters + 2010-09-06 22:38:15,301 d.e.f DEBUG IP: 123.231.231.123 User: fred A message at DEBUG level with 2 parameters + 2010-09-06 22:38:15,301 d.e.f INFO IP: 123.231.231.123 User: fred A message at INFO level with 2 parameters + + +.. _multiple-processes: + +Logging to a single file from multiple processes +------------------------------------------------ + +Although logging is thread-safe, and logging to a single file from multiple +threads in a single process *is* supported, logging to a single file from +*multiple processes* is *not* supported, because there is no standard way to +serialize access to a single file across multiple processes in Python. If you +need to log to a single file from multiple processes, one way of doing this is +to have all the processes log to a :class:`~handlers.SocketHandler`, and have a +separate process which implements a socket server which reads from the socket +and logs to file. (If you prefer, you can dedicate one thread in one of the +existing processes to perform this function.) +:ref:`This section <network-logging>` documents this approach in more detail and +includes a working socket receiver which can be used as a starting point for you +to adapt in your own applications. + +You could also write your own handler which uses the :class:`~multiprocessing.Lock` +class from the :mod:`multiprocessing` module to serialize access to the +file from your processes. The existing :class:`FileHandler` and subclasses do +not make use of :mod:`multiprocessing` at present, though they may do so in the +future. Note that at present, the :mod:`multiprocessing` module does not provide +working lock functionality on all platforms (see +https://bugs.python.org/issue3770). + +.. currentmodule:: logging.handlers + +Alternatively, you can use a ``Queue`` and a :class:`QueueHandler` to send +all logging events to one of the processes in your multi-process application. +The following example script demonstrates how you can do this; in the example +a separate listener process listens for events sent by other processes and logs +them according to its own logging configuration. Although the example only +demonstrates one way of doing it (for example, you may want to use a listener +thread rather than a separate listener process -- the implementation would be +analogous) it does allow for completely different logging configurations for +the listener and the other processes in your application, and can be used as +the basis for code meeting your own specific requirements:: + + # You'll need these imports in your own code + import logging + import logging.handlers + import multiprocessing + + # Next two import lines for this demo only + from random import choice, random + import time + + # + # Because you'll want to define the logging configurations for listener and workers, the + # listener and worker process functions take a configurer parameter which is a callable + # for configuring logging for that process. These functions are also passed the queue, + # which they use for communication. + # + # In practice, you can configure the listener however you want, but note that in this + # simple example, the listener does not apply level or filter logic to received records. + # In practice, you would probably want to do this logic in the worker processes, to avoid + # sending events which would be filtered out between processes. + # + # The size of the rotated files is made small so you can see the results easily. + def listener_configurer(): + root = logging.getLogger() + h = logging.handlers.RotatingFileHandler('mptest.log', 'a', 300, 10) + f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s %(levelname)-8s %(message)s') + h.setFormatter(f) + root.addHandler(h) + + # This is the listener process top-level loop: wait for logging events + # (LogRecords)on the queue and handle them, quit when you get a None for a + # LogRecord. + def listener_process(queue, configurer): + configurer() + while True: + try: + record = queue.get() + if record is None: # We send this as a sentinel to tell the listener to quit. + break + logger = logging.getLogger(record.name) + logger.handle(record) # No level or filter logic applied - just do it! + except Exception: + import sys, traceback + print('Whoops! Problem:', file=sys.stderr) + traceback.print_exc(file=sys.stderr) + + # Arrays used for random selections in this demo + + LEVELS = [logging.DEBUG, logging.INFO, logging.WARNING, + logging.ERROR, logging.CRITICAL] + + LOGGERS = ['a.b.c', 'd.e.f'] + + MESSAGES = [ + 'Random message #1', + 'Random message #2', + 'Random message #3', + ] + + # The worker configuration is done at the start of the worker process run. + # Note that on Windows you can't rely on fork semantics, so each process + # will run the logging configuration code when it starts. + def worker_configurer(queue): + h = logging.handlers.QueueHandler(queue) # Just the one handler needed + root = logging.getLogger() + root.addHandler(h) + # send all messages, for demo; no other level or filter logic applied. + root.setLevel(logging.DEBUG) + + # This is the worker process top-level loop, which just logs ten events with + # random intervening delays before terminating. + # The print messages are just so you know it's doing something! + def worker_process(queue, configurer): + configurer(queue) + name = multiprocessing.current_process().name + print('Worker started: %s' % name) + for i in range(10): + time.sleep(random()) + logger = logging.getLogger(choice(LOGGERS)) + level = choice(LEVELS) + message = choice(MESSAGES) + logger.log(level, message) + print('Worker finished: %s' % name) + + # Here's where the demo gets orchestrated. Create the queue, create and start + # the listener, create ten workers and start them, wait for them to finish, + # then send a None to the queue to tell the listener to finish. + def main(): + queue = multiprocessing.Queue(-1) + listener = multiprocessing.Process(target=listener_process, + args=(queue, listener_configurer)) + listener.start() + workers = [] + for i in range(10): + worker = multiprocessing.Process(target=worker_process, + args=(queue, worker_configurer)) + workers.append(worker) + worker.start() + for w in workers: + w.join() + queue.put_nowait(None) + listener.join() + + if __name__ == '__main__': + main() + +A variant of the above script keeps the logging in the main process, in a +separate thread:: + + import logging + import logging.config + import logging.handlers + from multiprocessing import Process, Queue + import random + import threading + import time + + def logger_thread(q): + while True: + record = q.get() + if record is None: + break + logger = logging.getLogger(record.name) + logger.handle(record) + + + def worker_process(q): + qh = logging.handlers.QueueHandler(q) + root = logging.getLogger() + root.setLevel(logging.DEBUG) + root.addHandler(qh) + levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, + logging.CRITICAL] + loggers = ['foo', 'foo.bar', 'foo.bar.baz', + 'spam', 'spam.ham', 'spam.ham.eggs'] + for i in range(100): + lvl = random.choice(levels) + logger = logging.getLogger(random.choice(loggers)) + logger.log(lvl, 'Message no. %d', i) + + if __name__ == '__main__': + q = Queue() + d = { + 'version': 1, + 'formatters': { + 'detailed': { + 'class': 'logging.Formatter', + 'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s' + } + }, + 'handlers': { + 'console': { + 'class': 'logging.StreamHandler', + 'level': 'INFO', + }, + 'file': { + 'class': 'logging.FileHandler', + 'filename': 'mplog.log', + 'mode': 'w', + 'formatter': 'detailed', + }, + 'foofile': { + 'class': 'logging.FileHandler', + 'filename': 'mplog-foo.log', + 'mode': 'w', + 'formatter': 'detailed', + }, + 'errors': { + 'class': 'logging.FileHandler', + 'filename': 'mplog-errors.log', + 'mode': 'w', + 'level': 'ERROR', + 'formatter': 'detailed', + }, + }, + 'loggers': { + 'foo': { + 'handlers': ['foofile'] + } + }, + 'root': { + 'level': 'DEBUG', + 'handlers': ['console', 'file', 'errors'] + }, + } + workers = [] + for i in range(5): + wp = Process(target=worker_process, name='worker %d' % (i + 1), args=(q,)) + workers.append(wp) + wp.start() + logging.config.dictConfig(d) + lp = threading.Thread(target=logger_thread, args=(q,)) + lp.start() + # At this point, the main process could do some useful work of its own + # Once it's done that, it can wait for the workers to terminate... + for wp in workers: + wp.join() + # And now tell the logging thread to finish up, too + q.put(None) + lp.join() + +This variant shows how you can e.g. apply configuration for particular loggers +- e.g. the ``foo`` logger has a special handler which stores all events in the +``foo`` subsystem in a file ``mplog-foo.log``. This will be used by the logging +machinery in the main process (even though the logging events are generated in +the worker processes) to direct the messages to the appropriate destinations. + +Using concurrent.futures.ProcessPoolExecutor +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +If you want to use :class:`concurrent.futures.ProcessPoolExecutor` to start +your worker processes, you need to create the queue slightly differently. +Instead of + +.. code-block:: python + + queue = multiprocessing.Queue(-1) + +you should use + +.. code-block:: python + + queue = multiprocessing.Manager().Queue(-1) # also works with the examples above + +and you can then replace the worker creation from this:: + + workers = [] + for i in range(10): + worker = multiprocessing.Process(target=worker_process, + args=(queue, worker_configurer)) + workers.append(worker) + worker.start() + for w in workers: + w.join() + +to this (remembering to first import :mod:`concurrent.futures`):: + + with concurrent.futures.ProcessPoolExecutor(max_workers=10) as executor: + for i in range(10): + executor.submit(worker_process, queue, worker_configurer) + + +Using file rotation +------------------- + +.. sectionauthor:: Doug Hellmann, Vinay Sajip (changes) +.. (see <https://pymotw.com/3/logging/>) + +Sometimes you want to let a log file grow to a certain size, then open a new +file and log to that. You may want to keep a certain number of these files, and +when that many files have been created, rotate the files so that the number of +files and the size of the files both remain bounded. For this usage pattern, the +logging package provides a :class:`~handlers.RotatingFileHandler`:: + + import glob + import logging + import logging.handlers + + LOG_FILENAME = 'logging_rotatingfile_example.out' + + # Set up a specific logger with our desired output level + my_logger = logging.getLogger('MyLogger') + my_logger.setLevel(logging.DEBUG) + + # Add the log message handler to the logger + handler = logging.handlers.RotatingFileHandler( + LOG_FILENAME, maxBytes=20, backupCount=5) + + my_logger.addHandler(handler) + + # Log some messages + for i in range(20): + my_logger.debug('i = %d' % i) + + # See what files are created + logfiles = glob.glob('%s*' % LOG_FILENAME) + + for filename in logfiles: + print(filename) + +The result should be 6 separate files, each with part of the log history for the +application: + +.. code-block:: none + + logging_rotatingfile_example.out + logging_rotatingfile_example.out.1 + logging_rotatingfile_example.out.2 + logging_rotatingfile_example.out.3 + logging_rotatingfile_example.out.4 + logging_rotatingfile_example.out.5 + +The most current file is always :file:`logging_rotatingfile_example.out`, +and each time it reaches the size limit it is renamed with the suffix +``.1``. Each of the existing backup files is renamed to increment the suffix +(``.1`` becomes ``.2``, etc.) and the ``.6`` file is erased. + +Obviously this example sets the log length much too small as an extreme +example. You would want to set *maxBytes* to an appropriate value. + +.. _format-styles: + +Use of alternative formatting styles +------------------------------------ + +When logging was added to the Python standard library, the only way of +formatting messages with variable content was to use the %-formatting +method. Since then, Python has gained two new formatting approaches: +:class:`string.Template` (added in Python 2.4) and :meth:`str.format` +(added in Python 2.6). + +Logging (as of 3.2) provides improved support for these two additional +formatting styles. The :class:`Formatter` class been enhanced to take an +additional, optional keyword parameter named ``style``. This defaults to +``'%'``, but other possible values are ``'{'`` and ``'$'``, which correspond +to the other two formatting styles. Backwards compatibility is maintained by +default (as you would expect), but by explicitly specifying a style parameter, +you get the ability to specify format strings which work with +:meth:`str.format` or :class:`string.Template`. Here's an example console +session to show the possibilities: + +.. code-block:: pycon + + >>> import logging + >>> root = logging.getLogger() + >>> root.setLevel(logging.DEBUG) + >>> handler = logging.StreamHandler() + >>> bf = logging.Formatter('{asctime} {name} {levelname:8s} {message}', + ... style='{') + >>> handler.setFormatter(bf) + >>> root.addHandler(handler) + >>> logger = logging.getLogger('foo.bar') + >>> logger.debug('This is a DEBUG message') + 2010-10-28 15:11:55,341 foo.bar DEBUG This is a DEBUG message + >>> logger.critical('This is a CRITICAL message') + 2010-10-28 15:12:11,526 foo.bar CRITICAL This is a CRITICAL message + >>> df = logging.Formatter('$asctime $name ${levelname} $message', + ... style='$') + >>> handler.setFormatter(df) + >>> logger.debug('This is a DEBUG message') + 2010-10-28 15:13:06,924 foo.bar DEBUG This is a DEBUG message + >>> logger.critical('This is a CRITICAL message') + 2010-10-28 15:13:11,494 foo.bar CRITICAL This is a CRITICAL message + >>> + +Note that the formatting of logging messages for final output to logs is +completely independent of how an individual logging message is constructed. +That can still use %-formatting, as shown here:: + + >>> logger.error('This is an%s %s %s', 'other,', 'ERROR,', 'message') + 2010-10-28 15:19:29,833 foo.bar ERROR This is another, ERROR, message + >>> + +Logging calls (``logger.debug()``, ``logger.info()`` etc.) only take +positional parameters for the actual logging message itself, with keyword +parameters used only for determining options for how to handle the actual +logging call (e.g. the ``exc_info`` keyword parameter to indicate that +traceback information should be logged, or the ``extra`` keyword parameter +to indicate additional contextual information to be added to the log). So +you cannot directly make logging calls using :meth:`str.format` or +:class:`string.Template` syntax, because internally the logging package +uses %-formatting to merge the format string and the variable arguments. +There would be no changing this while preserving backward compatibility, since +all logging calls which are out there in existing code will be using %-format +strings. + +There is, however, a way that you can use {}- and $- formatting to construct +your individual log messages. Recall that for a message you can use an +arbitrary object as a message format string, and that the logging package will +call ``str()`` on that object to get the actual format string. Consider the +following two classes:: + + class BraceMessage: + def __init__(self, fmt, /, *args, **kwargs): + self.fmt = fmt + self.args = args + self.kwargs = kwargs + + def __str__(self): + return self.fmt.format(*self.args, **self.kwargs) + + class DollarMessage: + def __init__(self, fmt, /, **kwargs): + self.fmt = fmt + self.kwargs = kwargs + + def __str__(self): + from string import Template + return Template(self.fmt).substitute(**self.kwargs) + +Either of these can be used in place of a format string, to allow {}- or +$-formatting to be used to build the actual "message" part which appears in the +formatted log output in place of "%(message)s" or "{message}" or "$message". +It's a little unwieldy to use the class names whenever you want to log +something, but it's quite palatable if you use an alias such as __ (double +underscore --- not to be confused with _, the single underscore used as a +synonym/alias for :func:`gettext.gettext` or its brethren). + +The above classes are not included in Python, though they're easy enough to +copy and paste into your own code. They can be used as follows (assuming that +they're declared in a module called ``wherever``): + +.. code-block:: pycon + + >>> from wherever import BraceMessage as __ + >>> print(__('Message with {0} {name}', 2, name='placeholders')) + Message with 2 placeholders + >>> class Point: pass + ... + >>> p = Point() + >>> p.x = 0.5 + >>> p.y = 0.5 + >>> print(__('Message with coordinates: ({point.x:.2f}, {point.y:.2f})', + ... point=p)) + Message with coordinates: (0.50, 0.50) + >>> from wherever import DollarMessage as __ + >>> print(__('Message with $num $what', num=2, what='placeholders')) + Message with 2 placeholders + >>> + +While the above examples use ``print()`` to show how the formatting works, you +would of course use ``logger.debug()`` or similar to actually log using this +approach. + +One thing to note is that you pay no significant performance penalty with this +approach: the actual formatting happens not when you make the logging call, but +when (and if) the logged message is actually about to be output to a log by a +handler. So the only slightly unusual thing which might trip you up is that the +parentheses go around the format string and the arguments, not just the format +string. That's because the __ notation is just syntax sugar for a constructor +call to one of the XXXMessage classes. + +If you prefer, you can use a :class:`LoggerAdapter` to achieve a similar effect +to the above, as in the following example:: + + import logging + + class Message: + def __init__(self, fmt, args): + self.fmt = fmt + self.args = args + + def __str__(self): + return self.fmt.format(*self.args) + + class StyleAdapter(logging.LoggerAdapter): + def __init__(self, logger, extra=None): + super(StyleAdapter, self).__init__(logger, extra or {}) + + def log(self, level, msg, /, *args, **kwargs): + if self.isEnabledFor(level): + msg, kwargs = self.process(msg, kwargs) + self.logger._log(level, Message(msg, args), (), **kwargs) + + logger = StyleAdapter(logging.getLogger(__name__)) + + def main(): + logger.debug('Hello, {}', 'world!') + + if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) + main() + +The above script should log the message ``Hello, world!`` when run with +Python 3.2 or later. + + +.. currentmodule:: logging + +.. _custom-logrecord: + +Customizing ``LogRecord`` +------------------------- + +Every logging event is represented by a :class:`LogRecord` instance. +When an event is logged and not filtered out by a logger's level, a +:class:`LogRecord` is created, populated with information about the event and +then passed to the handlers for that logger (and its ancestors, up to and +including the logger where further propagation up the hierarchy is disabled). +Before Python 3.2, there were only two places where this creation was done: + +* :meth:`Logger.makeRecord`, which is called in the normal process of + logging an event. This invoked :class:`LogRecord` directly to create an + instance. +* :func:`makeLogRecord`, which is called with a dictionary containing + attributes to be added to the LogRecord. This is typically invoked when a + suitable dictionary has been received over the network (e.g. in pickle form + via a :class:`~handlers.SocketHandler`, or in JSON form via an + :class:`~handlers.HTTPHandler`). + +This has usually meant that if you need to do anything special with a +:class:`LogRecord`, you've had to do one of the following. + +* Create your own :class:`Logger` subclass, which overrides + :meth:`Logger.makeRecord`, and set it using :func:`~logging.setLoggerClass` + before any loggers that you care about are instantiated. +* Add a :class:`Filter` to a logger or handler, which does the + necessary special manipulation you need when its + :meth:`~Filter.filter` method is called. + +The first approach would be a little unwieldy in the scenario where (say) +several different libraries wanted to do different things. Each would attempt +to set its own :class:`Logger` subclass, and the one which did this last would +win. + +The second approach works reasonably well for many cases, but does not allow +you to e.g. use a specialized subclass of :class:`LogRecord`. Library +developers can set a suitable filter on their loggers, but they would have to +remember to do this every time they introduced a new logger (which they would +do simply by adding new packages or modules and doing :: + + logger = logging.getLogger(__name__) + +at module level). It's probably one too many things to think about. Developers +could also add the filter to a :class:`~logging.NullHandler` attached to their +top-level logger, but this would not be invoked if an application developer +attached a handler to a lower-level library logger --- so output from that +handler would not reflect the intentions of the library developer. + +In Python 3.2 and later, :class:`~logging.LogRecord` creation is done through a +factory, which you can specify. The factory is just a callable you can set with +:func:`~logging.setLogRecordFactory`, and interrogate with +:func:`~logging.getLogRecordFactory`. The factory is invoked with the same +signature as the :class:`~logging.LogRecord` constructor, as :class:`LogRecord` +is the default setting for the factory. + +This approach allows a custom factory to control all aspects of LogRecord +creation. For example, you could return a subclass, or just add some additional +attributes to the record once created, using a pattern similar to this:: + + old_factory = logging.getLogRecordFactory() + + def record_factory(*args, **kwargs): + record = old_factory(*args, **kwargs) + record.custom_attribute = 0xdecafbad + return record + + logging.setLogRecordFactory(record_factory) + +This pattern allows different libraries to chain factories together, and as +long as they don't overwrite each other's attributes or unintentionally +overwrite the attributes provided as standard, there should be no surprises. +However, it should be borne in mind that each link in the chain adds run-time +overhead to all logging operations, and the technique should only be used when +the use of a :class:`Filter` does not provide the desired result. + + +.. _zeromq-handlers: + +Subclassing QueueHandler - a ZeroMQ example +------------------------------------------- + +You can use a :class:`QueueHandler` subclass to send messages to other kinds +of queues, for example a ZeroMQ 'publish' socket. In the example below,the +socket is created separately and passed to the handler (as its 'queue'):: + + import zmq # using pyzmq, the Python binding for ZeroMQ + import json # for serializing records portably + + ctx = zmq.Context() + sock = zmq.Socket(ctx, zmq.PUB) # or zmq.PUSH, or other suitable value + sock.bind('tcp://*:5556') # or wherever + + class ZeroMQSocketHandler(QueueHandler): + def enqueue(self, record): + self.queue.send_json(record.__dict__) + + + handler = ZeroMQSocketHandler(sock) + + +Of course there are other ways of organizing this, for example passing in the +data needed by the handler to create the socket:: + + class ZeroMQSocketHandler(QueueHandler): + def __init__(self, uri, socktype=zmq.PUB, ctx=None): + self.ctx = ctx or zmq.Context() + socket = zmq.Socket(self.ctx, socktype) + socket.bind(uri) + super().__init__(socket) + + def enqueue(self, record): + self.queue.send_json(record.__dict__) + + def close(self): + self.queue.close() + + +Subclassing QueueListener - a ZeroMQ example +-------------------------------------------- + +You can also subclass :class:`QueueListener` to get messages from other kinds +of queues, for example a ZeroMQ 'subscribe' socket. Here's an example:: + + class ZeroMQSocketListener(QueueListener): + def __init__(self, uri, /, *handlers, **kwargs): + self.ctx = kwargs.get('ctx') or zmq.Context() + socket = zmq.Socket(self.ctx, zmq.SUB) + socket.setsockopt_string(zmq.SUBSCRIBE, '') # subscribe to everything + socket.connect(uri) + super().__init__(socket, *handlers, **kwargs) + + def dequeue(self): + msg = self.queue.recv_json() + return logging.makeLogRecord(msg) + + +.. seealso:: + + Module :mod:`logging` + API reference for the logging module. + + Module :mod:`logging.config` + Configuration API for the logging module. + + Module :mod:`logging.handlers` + Useful handlers included with the logging module. + + :ref:`A basic logging tutorial <logging-basic-tutorial>` + + :ref:`A more advanced logging tutorial <logging-advanced-tutorial>` + + +An example dictionary-based configuration +----------------------------------------- + +Below is an example of a logging configuration dictionary - it's taken from +the `documentation on the Django project <https://docs.djangoproject.com/en/1.9/topics/logging/#configuring-logging>`_. +This dictionary is passed to :func:`~config.dictConfig` to put the configuration into effect:: + + LOGGING = { + 'version': 1, + 'disable_existing_loggers': True, + 'formatters': { + 'verbose': { + 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' + }, + 'simple': { + 'format': '%(levelname)s %(message)s' + }, + }, + 'filters': { + 'special': { + '()': 'project.logging.SpecialFilter', + 'foo': 'bar', + } + }, + 'handlers': { + 'null': { + 'level':'DEBUG', + 'class':'django.utils.log.NullHandler', + }, + 'console':{ + 'level':'DEBUG', + 'class':'logging.StreamHandler', + 'formatter': 'simple' + }, + 'mail_admins': { + 'level': 'ERROR', + 'class': 'django.utils.log.AdminEmailHandler', + 'filters': ['special'] + } + }, + 'loggers': { + 'django': { + 'handlers':['null'], + 'propagate': True, + 'level':'INFO', + }, + 'django.request': { + 'handlers': ['mail_admins'], + 'level': 'ERROR', + 'propagate': False, + }, + 'myproject.custom': { + 'handlers': ['console', 'mail_admins'], + 'level': 'INFO', + 'filters': ['special'] + } + } + } + +For more information about this configuration, you can see the `relevant +section <https://docs.djangoproject.com/en/1.9/topics/logging/#configuring-logging>`_ +of the Django documentation. + +.. _cookbook-rotator-namer: + +Using a rotator and namer to customize log rotation processing +-------------------------------------------------------------- + +An example of how you can define a namer and rotator is given in the following +snippet, which shows zlib-based compression of the log file:: + + def namer(name): + return name + ".gz" + + def rotator(source, dest): + with open(source, "rb") as sf: + data = sf.read() + compressed = zlib.compress(data, 9) + with open(dest, "wb") as df: + df.write(compressed) + os.remove(source) + + rh = logging.handlers.RotatingFileHandler(...) + rh.rotator = rotator + rh.namer = namer + +These are not "true" .gz files, as they are bare compressed data, with no +"container" such as you’d find in an actual gzip file. This snippet is just +for illustration purposes. + +A more elaborate multiprocessing example +---------------------------------------- + +The following working example shows how logging can be used with multiprocessing +using configuration files. The configurations are fairly simple, but serve to +illustrate how more complex ones could be implemented in a real multiprocessing +scenario. + +In the example, the main process spawns a listener process and some worker +processes. Each of the main process, the listener and the workers have three +separate configurations (the workers all share the same configuration). We can +see logging in the main process, how the workers log to a QueueHandler and how +the listener implements a QueueListener and a more complex logging +configuration, and arranges to dispatch events received via the queue to the +handlers specified in the configuration. Note that these configurations are +purely illustrative, but you should be able to adapt this example to your own +scenario. + +Here's the script - the docstrings and the comments hopefully explain how it +works:: + + import logging + import logging.config + import logging.handlers + from multiprocessing import Process, Queue, Event, current_process + import os + import random + import time + + class MyHandler: + """ + A simple handler for logging events. It runs in the listener process and + dispatches events to loggers based on the name in the received record, + which then get dispatched, by the logging system, to the handlers + configured for those loggers. + """ + + def handle(self, record): + if record.name == "root": + logger = logging.getLogger() + else: + logger = logging.getLogger(record.name) + + if logger.isEnabledFor(record.levelno): + # The process name is transformed just to show that it's the listener + # doing the logging to files and console + record.processName = '%s (for %s)' % (current_process().name, record.processName) + logger.handle(record) + + def listener_process(q, stop_event, config): + """ + This could be done in the main process, but is just done in a separate + process for illustrative purposes. + + This initialises logging according to the specified configuration, + starts the listener and waits for the main process to signal completion + via the event. The listener is then stopped, and the process exits. + """ + logging.config.dictConfig(config) + listener = logging.handlers.QueueListener(q, MyHandler()) + listener.start() + if os.name == 'posix': + # On POSIX, the setup logger will have been configured in the + # parent process, but should have been disabled following the + # dictConfig call. + # On Windows, since fork isn't used, the setup logger won't + # exist in the child, so it would be created and the message + # would appear - hence the "if posix" clause. + logger = logging.getLogger('setup') + logger.critical('Should not appear, because of disabled logger ...') + stop_event.wait() + listener.stop() + + def worker_process(config): + """ + A number of these are spawned for the purpose of illustration. In + practice, they could be a heterogeneous bunch of processes rather than + ones which are identical to each other. + + This initialises logging according to the specified configuration, + and logs a hundred messages with random levels to randomly selected + loggers. + + A small sleep is added to allow other processes a chance to run. This + is not strictly needed, but it mixes the output from the different + processes a bit more than if it's left out. + """ + logging.config.dictConfig(config) + levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, + logging.CRITICAL] + loggers = ['foo', 'foo.bar', 'foo.bar.baz', + 'spam', 'spam.ham', 'spam.ham.eggs'] + if os.name == 'posix': + # On POSIX, the setup logger will have been configured in the + # parent process, but should have been disabled following the + # dictConfig call. + # On Windows, since fork isn't used, the setup logger won't + # exist in the child, so it would be created and the message + # would appear - hence the "if posix" clause. + logger = logging.getLogger('setup') + logger.critical('Should not appear, because of disabled logger ...') + for i in range(100): + lvl = random.choice(levels) + logger = logging.getLogger(random.choice(loggers)) + logger.log(lvl, 'Message no. %d', i) + time.sleep(0.01) + + def main(): + q = Queue() + # The main process gets a simple configuration which prints to the console. + config_initial = { + 'version': 1, + 'handlers': { + 'console': { + 'class': 'logging.StreamHandler', + 'level': 'INFO' + } + }, + 'root': { + 'handlers': ['console'], + 'level': 'DEBUG' + } + } + # The worker process configuration is just a QueueHandler attached to the + # root logger, which allows all messages to be sent to the queue. + # We disable existing loggers to disable the "setup" logger used in the + # parent process. This is needed on POSIX because the logger will + # be there in the child following a fork(). + config_worker = { + 'version': 1, + 'disable_existing_loggers': True, + 'handlers': { + 'queue': { + 'class': 'logging.handlers.QueueHandler', + 'queue': q + } + }, + 'root': { + 'handlers': ['queue'], + 'level': 'DEBUG' + } + } + # The listener process configuration shows that the full flexibility of + # logging configuration is available to dispatch events to handlers however + # you want. + # We disable existing loggers to disable the "setup" logger used in the + # parent process. This is needed on POSIX because the logger will + # be there in the child following a fork(). + config_listener = { + 'version': 1, + 'disable_existing_loggers': True, + 'formatters': { + 'detailed': { + 'class': 'logging.Formatter', + 'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s' + }, + 'simple': { + 'class': 'logging.Formatter', + 'format': '%(name)-15s %(levelname)-8s %(processName)-10s %(message)s' + } + }, + 'handlers': { + 'console': { + 'class': 'logging.StreamHandler', + 'formatter': 'simple', + 'level': 'INFO' + }, + 'file': { + 'class': 'logging.FileHandler', + 'filename': 'mplog.log', + 'mode': 'w', + 'formatter': 'detailed' + }, + 'foofile': { + 'class': 'logging.FileHandler', + 'filename': 'mplog-foo.log', + 'mode': 'w', + 'formatter': 'detailed' + }, + 'errors': { + 'class': 'logging.FileHandler', + 'filename': 'mplog-errors.log', + 'mode': 'w', + 'formatter': 'detailed', + 'level': 'ERROR' + } + }, + 'loggers': { + 'foo': { + 'handlers': ['foofile'] + } + }, + 'root': { + 'handlers': ['console', 'file', 'errors'], + 'level': 'DEBUG' + } + } + # Log some initial events, just to show that logging in the parent works + # normally. + logging.config.dictConfig(config_initial) + logger = logging.getLogger('setup') + logger.info('About to create workers ...') + workers = [] + for i in range(5): + wp = Process(target=worker_process, name='worker %d' % (i + 1), + args=(config_worker,)) + workers.append(wp) + wp.start() + logger.info('Started worker: %s', wp.name) + logger.info('About to create listener ...') + stop_event = Event() + lp = Process(target=listener_process, name='listener', + args=(q, stop_event, config_listener)) + lp.start() + logger.info('Started listener') + # We now hang around for the workers to finish their work. + for wp in workers: + wp.join() + # Workers all done, listening can now stop. + # Logging in the parent still works normally. + logger.info('Telling listener to stop ...') + stop_event.set() + lp.join() + logger.info('All done.') + + if __name__ == '__main__': + main() + + +Inserting a BOM into messages sent to a SysLogHandler +----------------------------------------------------- + +:rfc:`5424` requires that a +Unicode message be sent to a syslog daemon as a set of bytes which have the +following structure: an optional pure-ASCII component, followed by a UTF-8 Byte +Order Mark (BOM), followed by Unicode encoded using UTF-8. (See the +:rfc:`relevant section of the specification <5424#section-6>`.) + +In Python 3.1, code was added to +:class:`~logging.handlers.SysLogHandler` to insert a BOM into the message, but +unfortunately, it was implemented incorrectly, with the BOM appearing at the +beginning of the message and hence not allowing any pure-ASCII component to +appear before it. + +As this behaviour is broken, the incorrect BOM insertion code is being removed +from Python 3.2.4 and later. However, it is not being replaced, and if you +want to produce :rfc:`5424`-compliant messages which include a BOM, an optional +pure-ASCII sequence before it and arbitrary Unicode after it, encoded using +UTF-8, then you need to do the following: + +#. Attach a :class:`~logging.Formatter` instance to your + :class:`~logging.handlers.SysLogHandler` instance, with a format string + such as:: + + 'ASCII section\ufeffUnicode section' + + The Unicode code point U+FEFF, when encoded using UTF-8, will be + encoded as a UTF-8 BOM -- the byte-string ``b'\xef\xbb\xbf'``. + +#. Replace the ASCII section with whatever placeholders you like, but make sure + that the data that appears in there after substitution is always ASCII (that + way, it will remain unchanged after UTF-8 encoding). + +#. Replace the Unicode section with whatever placeholders you like; if the data + which appears there after substitution contains characters outside the ASCII + range, that's fine -- it will be encoded using UTF-8. + +The formatted message *will* be encoded using UTF-8 encoding by +``SysLogHandler``. If you follow the above rules, you should be able to produce +:rfc:`5424`-compliant messages. If you don't, logging may not complain, but your +messages will not be RFC 5424-compliant, and your syslog daemon may complain. + + +Implementing structured logging +------------------------------- + +Although most logging messages are intended for reading by humans, and thus not +readily machine-parseable, there might be circumstances where you want to output +messages in a structured format which *is* capable of being parsed by a program +(without needing complex regular expressions to parse the log message). This is +straightforward to achieve using the logging package. There are a number of +ways in which this could be achieved, but the following is a simple approach +which uses JSON to serialise the event in a machine-parseable manner:: + + import json + import logging + + class StructuredMessage: + def __init__(self, message, /, **kwargs): + self.message = message + self.kwargs = kwargs + + def __str__(self): + return '%s >>> %s' % (self.message, json.dumps(self.kwargs)) + + _ = StructuredMessage # optional, to improve readability + + logging.basicConfig(level=logging.INFO, format='%(message)s') + logging.info(_('message 1', foo='bar', bar='baz', num=123, fnum=123.456)) + +If the above script is run, it prints: + +.. code-block:: none + + message 1 >>> {"fnum": 123.456, "num": 123, "bar": "baz", "foo": "bar"} + +Note that the order of items might be different according to the version of +Python used. + +If you need more specialised processing, you can use a custom JSON encoder, +as in the following complete example:: + + from __future__ import unicode_literals + + import json + import logging + + # This next bit is to ensure the script runs unchanged on 2.x and 3.x + try: + unicode + except NameError: + unicode = str + + class Encoder(json.JSONEncoder): + def default(self, o): + if isinstance(o, set): + return tuple(o) + elif isinstance(o, unicode): + return o.encode('unicode_escape').decode('ascii') + return super(Encoder, self).default(o) + + class StructuredMessage: + def __init__(self, message, /, **kwargs): + self.message = message + self.kwargs = kwargs + + def __str__(self): + s = Encoder().encode(self.kwargs) + return '%s >>> %s' % (self.message, s) + + _ = StructuredMessage # optional, to improve readability + + def main(): + logging.basicConfig(level=logging.INFO, format='%(message)s') + logging.info(_('message 1', set_value={1, 2, 3}, snowman='\u2603')) + + if __name__ == '__main__': + main() + +When the above script is run, it prints: + +.. code-block:: none + + message 1 >>> {"snowman": "\u2603", "set_value": [1, 2, 3]} + +Note that the order of items might be different according to the version of +Python used. + + +.. _custom-handlers: + +.. currentmodule:: logging.config + +Customizing handlers with :func:`dictConfig` +-------------------------------------------- + +There are times when you want to customize logging handlers in particular ways, +and if you use :func:`dictConfig` you may be able to do this without +subclassing. As an example, consider that you may want to set the ownership of a +log file. On POSIX, this is easily done using :func:`shutil.chown`, but the file +handlers in the stdlib don't offer built-in support. You can customize handler +creation using a plain function such as:: + + def owned_file_handler(filename, mode='a', encoding=None, owner=None): + if owner: + if not os.path.exists(filename): + open(filename, 'a').close() + shutil.chown(filename, *owner) + return logging.FileHandler(filename, mode, encoding) + +You can then specify, in a logging configuration passed to :func:`dictConfig`, +that a logging handler be created by calling this function:: + + LOGGING = { + 'version': 1, + 'disable_existing_loggers': False, + 'formatters': { + 'default': { + 'format': '%(asctime)s %(levelname)s %(name)s %(message)s' + }, + }, + 'handlers': { + 'file':{ + # The values below are popped from this dictionary and + # used to create the handler, set the handler's level and + # its formatter. + '()': owned_file_handler, + 'level':'DEBUG', + 'formatter': 'default', + # The values below are passed to the handler creator callable + # as keyword arguments. + 'owner': ['pulse', 'pulse'], + 'filename': 'chowntest.log', + 'mode': 'w', + 'encoding': 'utf-8', + }, + }, + 'root': { + 'handlers': ['file'], + 'level': 'DEBUG', + }, + } + +In this example I am setting the ownership using the ``pulse`` user and group, +just for the purposes of illustration. Putting it together into a working +script, ``chowntest.py``:: + + import logging, logging.config, os, shutil + + def owned_file_handler(filename, mode='a', encoding=None, owner=None): + if owner: + if not os.path.exists(filename): + open(filename, 'a').close() + shutil.chown(filename, *owner) + return logging.FileHandler(filename, mode, encoding) + + LOGGING = { + 'version': 1, + 'disable_existing_loggers': False, + 'formatters': { + 'default': { + 'format': '%(asctime)s %(levelname)s %(name)s %(message)s' + }, + }, + 'handlers': { + 'file':{ + # The values below are popped from this dictionary and + # used to create the handler, set the handler's level and + # its formatter. + '()': owned_file_handler, + 'level':'DEBUG', + 'formatter': 'default', + # The values below are passed to the handler creator callable + # as keyword arguments. + 'owner': ['pulse', 'pulse'], + 'filename': 'chowntest.log', + 'mode': 'w', + 'encoding': 'utf-8', + }, + }, + 'root': { + 'handlers': ['file'], + 'level': 'DEBUG', + }, + } + + logging.config.dictConfig(LOGGING) + logger = logging.getLogger('mylogger') + logger.debug('A debug message') + +To run this, you will probably need to run as ``root``: + +.. code-block:: shell-session + + $ sudo python3.3 chowntest.py + $ cat chowntest.log + 2013-11-05 09:34:51,128 DEBUG mylogger A debug message + $ ls -l chowntest.log + -rw-r--r-- 1 pulse pulse 55 2013-11-05 09:34 chowntest.log + +Note that this example uses Python 3.3 because that's where :func:`shutil.chown` +makes an appearance. This approach should work with any Python version that +supports :func:`dictConfig` - namely, Python 2.7, 3.2 or later. With pre-3.3 +versions, you would need to implement the actual ownership change using e.g. +:func:`os.chown`. + +In practice, the handler-creating function may be in a utility module somewhere +in your project. Instead of the line in the configuration:: + + '()': owned_file_handler, + +you could use e.g.:: + + '()': 'ext://project.util.owned_file_handler', + +where ``project.util`` can be replaced with the actual name of the package +where the function resides. In the above working script, using +``'ext://__main__.owned_file_handler'`` should work. Here, the actual callable +is resolved by :func:`dictConfig` from the ``ext://`` specification. + +This example hopefully also points the way to how you could implement other +types of file change - e.g. setting specific POSIX permission bits - in the +same way, using :func:`os.chmod`. + +Of course, the approach could also be extended to types of handler other than a +:class:`~logging.FileHandler` - for example, one of the rotating file handlers, +or a different type of handler altogether. + + +.. currentmodule:: logging + +.. _formatting-styles: + +Using particular formatting styles throughout your application +-------------------------------------------------------------- + +In Python 3.2, the :class:`~logging.Formatter` gained a ``style`` keyword +parameter which, while defaulting to ``%`` for backward compatibility, allowed +the specification of ``{`` or ``$`` to support the formatting approaches +supported by :meth:`str.format` and :class:`string.Template`. Note that this +governs the formatting of logging messages for final output to logs, and is +completely orthogonal to how an individual logging message is constructed. + +Logging calls (:meth:`~Logger.debug`, :meth:`~Logger.info` etc.) only take +positional parameters for the actual logging message itself, with keyword +parameters used only for determining options for how to handle the logging call +(e.g. the ``exc_info`` keyword parameter to indicate that traceback information +should be logged, or the ``extra`` keyword parameter to indicate additional +contextual information to be added to the log). So you cannot directly make +logging calls using :meth:`str.format` or :class:`string.Template` syntax, +because internally the logging package uses %-formatting to merge the format +string and the variable arguments. There would no changing this while preserving +backward compatibility, since all logging calls which are out there in existing +code will be using %-format strings. + +There have been suggestions to associate format styles with specific loggers, +but that approach also runs into backward compatibility problems because any +existing code could be using a given logger name and using %-formatting. + +For logging to work interoperably between any third-party libraries and your +code, decisions about formatting need to be made at the level of the +individual logging call. This opens up a couple of ways in which alternative +formatting styles can be accommodated. + + +Using LogRecord factories +^^^^^^^^^^^^^^^^^^^^^^^^^ + +In Python 3.2, along with the :class:`~logging.Formatter` changes mentioned +above, the logging package gained the ability to allow users to set their own +:class:`LogRecord` subclasses, using the :func:`setLogRecordFactory` function. +You can use this to set your own subclass of :class:`LogRecord`, which does the +Right Thing by overriding the :meth:`~LogRecord.getMessage` method. The base +class implementation of this method is where the ``msg % args`` formatting +happens, and where you can substitute your alternate formatting; however, you +should be careful to support all formatting styles and allow %-formatting as +the default, to ensure interoperability with other code. Care should also be +taken to call ``str(self.msg)``, just as the base implementation does. + +Refer to the reference documentation on :func:`setLogRecordFactory` and +:class:`LogRecord` for more information. + + +Using custom message objects +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +There is another, perhaps simpler way that you can use {}- and $- formatting to +construct your individual log messages. You may recall (from +:ref:`arbitrary-object-messages`) that when logging you can use an arbitrary +object as a message format string, and that the logging package will call +:func:`str` on that object to get the actual format string. Consider the +following two classes:: + + class BraceMessage: + def __init__(self, fmt, /, *args, **kwargs): + self.fmt = fmt + self.args = args + self.kwargs = kwargs + + def __str__(self): + return self.fmt.format(*self.args, **self.kwargs) + + class DollarMessage: + def __init__(self, fmt, /, **kwargs): + self.fmt = fmt + self.kwargs = kwargs + + def __str__(self): + from string import Template + return Template(self.fmt).substitute(**self.kwargs) + +Either of these can be used in place of a format string, to allow {}- or +$-formatting to be used to build the actual "message" part which appears in the +formatted log output in place of “%(message)s” or “{message}” or “$message”. +If you find it a little unwieldy to use the class names whenever you want to log +something, you can make it more palatable if you use an alias such as ``M`` or +``_`` for the message (or perhaps ``__``, if you are using ``_`` for +localization). + +Examples of this approach are given below. Firstly, formatting with +:meth:`str.format`:: + + >>> __ = BraceMessage + >>> print(__('Message with {0} {1}', 2, 'placeholders')) + Message with 2 placeholders + >>> class Point: pass + ... + >>> p = Point() + >>> p.x = 0.5 + >>> p.y = 0.5 + >>> print(__('Message with coordinates: ({point.x:.2f}, {point.y:.2f})', point=p)) + Message with coordinates: (0.50, 0.50) + +Secondly, formatting with :class:`string.Template`:: + + >>> __ = DollarMessage + >>> print(__('Message with $num $what', num=2, what='placeholders')) + Message with 2 placeholders + >>> + +One thing to note is that you pay no significant performance penalty with this +approach: the actual formatting happens not when you make the logging call, but +when (and if) the logged message is actually about to be output to a log by a +handler. So the only slightly unusual thing which might trip you up is that the +parentheses go around the format string and the arguments, not just the format +string. That’s because the __ notation is just syntax sugar for a constructor +call to one of the ``XXXMessage`` classes shown above. + + +.. _filters-dictconfig: + +.. currentmodule:: logging.config + +Configuring filters with :func:`dictConfig` +------------------------------------------- + +You *can* configure filters using :func:`~logging.config.dictConfig`, though it +might not be obvious at first glance how to do it (hence this recipe). Since +:class:`~logging.Filter` is the only filter class included in the standard +library, and it is unlikely to cater to many requirements (it's only there as a +base class), you will typically need to define your own :class:`~logging.Filter` +subclass with an overridden :meth:`~logging.Filter.filter` method. To do this, +specify the ``()`` key in the configuration dictionary for the filter, +specifying a callable which will be used to create the filter (a class is the +most obvious, but you can provide any callable which returns a +:class:`~logging.Filter` instance). Here is a complete example:: + + import logging + import logging.config + import sys + + class MyFilter(logging.Filter): + def __init__(self, param=None): + self.param = param + + def filter(self, record): + if self.param is None: + allow = True + else: + allow = self.param not in record.msg + if allow: + record.msg = 'changed: ' + record.msg + return allow + + LOGGING = { + 'version': 1, + 'filters': { + 'myfilter': { + '()': MyFilter, + 'param': 'noshow', + } + }, + 'handlers': { + 'console': { + 'class': 'logging.StreamHandler', + 'filters': ['myfilter'] + } + }, + 'root': { + 'level': 'DEBUG', + 'handlers': ['console'] + }, + } + + if __name__ == '__main__': + logging.config.dictConfig(LOGGING) + logging.debug('hello') + logging.debug('hello - noshow') + +This example shows how you can pass configuration data to the callable which +constructs the instance, in the form of keyword parameters. When run, the above +script will print: + +.. code-block:: none + + changed: hello + +which shows that the filter is working as configured. + +A couple of extra points to note: + +* If you can't refer to the callable directly in the configuration (e.g. if it + lives in a different module, and you can't import it directly where the + configuration dictionary is), you can use the form ``ext://...`` as described + in :ref:`logging-config-dict-externalobj`. For example, you could have used + the text ``'ext://__main__.MyFilter'`` instead of ``MyFilter`` in the above + example. + +* As well as for filters, this technique can also be used to configure custom + handlers and formatters. See :ref:`logging-config-dict-userdef` for more + information on how logging supports using user-defined objects in its + configuration, and see the other cookbook recipe :ref:`custom-handlers` above. + + +.. _custom-format-exception: + +Customized exception formatting +------------------------------- + +There might be times when you want to do customized exception formatting - for +argument's sake, let's say you want exactly one line per logged event, even +when exception information is present. You can do this with a custom formatter +class, as shown in the following example:: + + import logging + + class OneLineExceptionFormatter(logging.Formatter): + def formatException(self, exc_info): + """ + Format an exception so that it prints on a single line. + """ + result = super(OneLineExceptionFormatter, self).formatException(exc_info) + return repr(result) # or format into one line however you want to + + def format(self, record): + s = super(OneLineExceptionFormatter, self).format(record) + if record.exc_text: + s = s.replace('\n', '') + '|' + return s + + def configure_logging(): + fh = logging.FileHandler('output.txt', 'w') + f = OneLineExceptionFormatter('%(asctime)s|%(levelname)s|%(message)s|', + '%d/%m/%Y %H:%M:%S') + fh.setFormatter(f) + root = logging.getLogger() + root.setLevel(logging.DEBUG) + root.addHandler(fh) + + def main(): + configure_logging() + logging.info('Sample message') + try: + x = 1 / 0 + except ZeroDivisionError as e: + logging.exception('ZeroDivisionError: %s', e) + + if __name__ == '__main__': + main() + +When run, this produces a file with exactly two lines: + +.. code-block:: none + + 28/01/2015 07:21:23|INFO|Sample message| + 28/01/2015 07:21:23|ERROR|ZeroDivisionError: integer division or modulo by zero|'Traceback (most recent call last):\n File "logtest7.py", line 30, in main\n x = 1 / 0\nZeroDivisionError: integer division or modulo by zero'| + +While the above treatment is simplistic, it points the way to how exception +information can be formatted to your liking. The :mod:`traceback` module may be +helpful for more specialized needs. + +.. _spoken-messages: + +Speaking logging messages +------------------------- + +There might be situations when it is desirable to have logging messages rendered +in an audible rather than a visible format. This is easy to do if you have +text-to-speech (TTS) functionality available in your system, even if it doesn't have +a Python binding. Most TTS systems have a command line program you can run, and +this can be invoked from a handler using :mod:`subprocess`. It's assumed here +that TTS command line programs won't expect to interact with users or take a +long time to complete, and that the frequency of logged messages will be not so +high as to swamp the user with messages, and that it's acceptable to have the +messages spoken one at a time rather than concurrently, The example implementation +below waits for one message to be spoken before the next is processed, and this +might cause other handlers to be kept waiting. Here is a short example showing +the approach, which assumes that the ``espeak`` TTS package is available:: + + import logging + import subprocess + import sys + + class TTSHandler(logging.Handler): + def emit(self, record): + msg = self.format(record) + # Speak slowly in a female English voice + cmd = ['espeak', '-s150', '-ven+f3', msg] + p = subprocess.Popen(cmd, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT) + # wait for the program to finish + p.communicate() + + def configure_logging(): + h = TTSHandler() + root = logging.getLogger() + root.addHandler(h) + # the default formatter just returns the message + root.setLevel(logging.DEBUG) + + def main(): + logging.info('Hello') + logging.debug('Goodbye') + + if __name__ == '__main__': + configure_logging() + sys.exit(main()) + +When run, this script should say "Hello" and then "Goodbye" in a female voice. + +The above approach can, of course, be adapted to other TTS systems and even +other systems altogether which can process messages via external programs run +from a command line. + + +.. _buffered-logging: + +Buffering logging messages and outputting them conditionally +------------------------------------------------------------ + +There might be situations where you want to log messages in a temporary area +and only output them if a certain condition occurs. For example, you may want to +start logging debug events in a function, and if the function completes without +errors, you don't want to clutter the log with the collected debug information, +but if there is an error, you want all the debug information to be output as well +as the error. + +Here is an example which shows how you could do this using a decorator for your +functions where you want logging to behave this way. It makes use of the +:class:`logging.handlers.MemoryHandler`, which allows buffering of logged events +until some condition occurs, at which point the buffered events are ``flushed`` +- passed to another handler (the ``target`` handler) for processing. By default, +the ``MemoryHandler`` flushed when its buffer gets filled up or an event whose +level is greater than or equal to a specified threshold is seen. You can use this +recipe with a more specialised subclass of ``MemoryHandler`` if you want custom +flushing behavior. + +The example script has a simple function, ``foo``, which just cycles through +all the logging levels, writing to ``sys.stderr`` to say what level it's about +to log at, and then actually logging a message at that level. You can pass a +parameter to ``foo`` which, if true, will log at ERROR and CRITICAL levels - +otherwise, it only logs at DEBUG, INFO and WARNING levels. + +The script just arranges to decorate ``foo`` with a decorator which will do the +conditional logging that's required. The decorator takes a logger as a parameter +and attaches a memory handler for the duration of the call to the decorated +function. The decorator can be additionally parameterised using a target handler, +a level at which flushing should occur, and a capacity for the buffer (number of +records buffered). These default to a :class:`~logging.StreamHandler` which +writes to ``sys.stderr``, ``logging.ERROR`` and ``100`` respectively. + +Here's the script:: + + import logging + from logging.handlers import MemoryHandler + import sys + + logger = logging.getLogger(__name__) + logger.addHandler(logging.NullHandler()) + + def log_if_errors(logger, target_handler=None, flush_level=None, capacity=None): + if target_handler is None: + target_handler = logging.StreamHandler() + if flush_level is None: + flush_level = logging.ERROR + if capacity is None: + capacity = 100 + handler = MemoryHandler(capacity, flushLevel=flush_level, target=target_handler) + + def decorator(fn): + def wrapper(*args, **kwargs): + logger.addHandler(handler) + try: + return fn(*args, **kwargs) + except Exception: + logger.exception('call failed') + raise + finally: + super(MemoryHandler, handler).flush() + logger.removeHandler(handler) + return wrapper + + return decorator + + def write_line(s): + sys.stderr.write('%s\n' % s) + + def foo(fail=False): + write_line('about to log at DEBUG ...') + logger.debug('Actually logged at DEBUG') + write_line('about to log at INFO ...') + logger.info('Actually logged at INFO') + write_line('about to log at WARNING ...') + logger.warning('Actually logged at WARNING') + if fail: + write_line('about to log at ERROR ...') + logger.error('Actually logged at ERROR') + write_line('about to log at CRITICAL ...') + logger.critical('Actually logged at CRITICAL') + return fail + + decorated_foo = log_if_errors(logger)(foo) + + if __name__ == '__main__': + logger.setLevel(logging.DEBUG) + write_line('Calling undecorated foo with False') + assert not foo(False) + write_line('Calling undecorated foo with True') + assert foo(True) + write_line('Calling decorated foo with False') + assert not decorated_foo(False) + write_line('Calling decorated foo with True') + assert decorated_foo(True) + +When this script is run, the following output should be observed: + +.. code-block:: none + + Calling undecorated foo with False + about to log at DEBUG ... + about to log at INFO ... + about to log at WARNING ... + Calling undecorated foo with True + about to log at DEBUG ... + about to log at INFO ... + about to log at WARNING ... + about to log at ERROR ... + about to log at CRITICAL ... + Calling decorated foo with False + about to log at DEBUG ... + about to log at INFO ... + about to log at WARNING ... + Calling decorated foo with True + about to log at DEBUG ... + about to log at INFO ... + about to log at WARNING ... + about to log at ERROR ... + Actually logged at DEBUG + Actually logged at INFO + Actually logged at WARNING + Actually logged at ERROR + about to log at CRITICAL ... + Actually logged at CRITICAL + +As you can see, actual logging output only occurs when an event is logged whose +severity is ERROR or greater, but in that case, any previous events at lower +severities are also logged. + +You can of course use the conventional means of decoration:: + + @log_if_errors(logger) + def foo(fail=False): + ... + + +.. _utc-formatting: + +Formatting times using UTC (GMT) via configuration +-------------------------------------------------- + +Sometimes you want to format times using UTC, which can be done using a class +such as `UTCFormatter`, shown below:: + + import logging + import time + + class UTCFormatter(logging.Formatter): + converter = time.gmtime + +and you can then use the ``UTCFormatter`` in your code instead of +:class:`~logging.Formatter`. If you want to do that via configuration, you can +use the :func:`~logging.config.dictConfig` API with an approach illustrated by +the following complete example:: + + import logging + import logging.config + import time + + class UTCFormatter(logging.Formatter): + converter = time.gmtime + + LOGGING = { + 'version': 1, + 'disable_existing_loggers': False, + 'formatters': { + 'utc': { + '()': UTCFormatter, + 'format': '%(asctime)s %(message)s', + }, + 'local': { + 'format': '%(asctime)s %(message)s', + } + }, + 'handlers': { + 'console1': { + 'class': 'logging.StreamHandler', + 'formatter': 'utc', + }, + 'console2': { + 'class': 'logging.StreamHandler', + 'formatter': 'local', + }, + }, + 'root': { + 'handlers': ['console1', 'console2'], + } + } + + if __name__ == '__main__': + logging.config.dictConfig(LOGGING) + logging.warning('The local time is %s', time.asctime()) + +When this script is run, it should print something like: + +.. code-block:: none + + 2015-10-17 12:53:29,501 The local time is Sat Oct 17 13:53:29 2015 + 2015-10-17 13:53:29,501 The local time is Sat Oct 17 13:53:29 2015 + +showing how the time is formatted both as local time and UTC, one for each +handler. + + +.. _context-manager: + +Using a context manager for selective logging +--------------------------------------------- + +There are times when it would be useful to temporarily change the logging +configuration and revert it back after doing something. For this, a context +manager is the most obvious way of saving and restoring the logging context. +Here is a simple example of such a context manager, which allows you to +optionally change the logging level and add a logging handler purely in the +scope of the context manager:: + + import logging + import sys + + class LoggingContext: + def __init__(self, logger, level=None, handler=None, close=True): + self.logger = logger + self.level = level + self.handler = handler + self.close = close + + def __enter__(self): + if self.level is not None: + self.old_level = self.logger.level + self.logger.setLevel(self.level) + if self.handler: + self.logger.addHandler(self.handler) + + def __exit__(self, et, ev, tb): + if self.level is not None: + self.logger.setLevel(self.old_level) + if self.handler: + self.logger.removeHandler(self.handler) + if self.handler and self.close: + self.handler.close() + # implicit return of None => don't swallow exceptions + +If you specify a level value, the logger's level is set to that value in the +scope of the with block covered by the context manager. If you specify a +handler, it is added to the logger on entry to the block and removed on exit +from the block. You can also ask the manager to close the handler for you on +block exit - you could do this if you don't need the handler any more. + +To illustrate how it works, we can add the following block of code to the +above:: + + if __name__ == '__main__': + logger = logging.getLogger('foo') + logger.addHandler(logging.StreamHandler()) + logger.setLevel(logging.INFO) + logger.info('1. This should appear just once on stderr.') + logger.debug('2. This should not appear.') + with LoggingContext(logger, level=logging.DEBUG): + logger.debug('3. This should appear once on stderr.') + logger.debug('4. This should not appear.') + h = logging.StreamHandler(sys.stdout) + with LoggingContext(logger, level=logging.DEBUG, handler=h, close=True): + logger.debug('5. This should appear twice - once on stderr and once on stdout.') + logger.info('6. This should appear just once on stderr.') + logger.debug('7. This should not appear.') + +We initially set the logger's level to ``INFO``, so message #1 appears and +message #2 doesn't. We then change the level to ``DEBUG`` temporarily in the +following ``with`` block, and so message #3 appears. After the block exits, the +logger's level is restored to ``INFO`` and so message #4 doesn't appear. In the +next ``with`` block, we set the level to ``DEBUG`` again but also add a handler +writing to ``sys.stdout``. Thus, message #5 appears twice on the console (once +via ``stderr`` and once via ``stdout``). After the ``with`` statement's +completion, the status is as it was before so message #6 appears (like message +#1) whereas message #7 doesn't (just like message #2). + +If we run the resulting script, the result is as follows: + +.. code-block:: shell-session + + $ python logctx.py + 1. This should appear just once on stderr. + 3. This should appear once on stderr. + 5. This should appear twice - once on stderr and once on stdout. + 5. This should appear twice - once on stderr and once on stdout. + 6. This should appear just once on stderr. + +If we run it again, but pipe ``stderr`` to ``/dev/null``, we see the following, +which is the only message written to ``stdout``: + +.. code-block:: shell-session + + $ python logctx.py 2>/dev/null + 5. This should appear twice - once on stderr and once on stdout. + +Once again, but piping ``stdout`` to ``/dev/null``, we get: + +.. code-block:: shell-session + + $ python logctx.py >/dev/null + 1. This should appear just once on stderr. + 3. This should appear once on stderr. + 5. This should appear twice - once on stderr and once on stdout. + 6. This should appear just once on stderr. + +In this case, the message #5 printed to ``stdout`` doesn't appear, as expected. + +Of course, the approach described here can be generalised, for example to attach +logging filters temporarily. Note that the above code works in Python 2 as well +as Python 3. + + +.. _starter-template: + +A CLI application starter template +---------------------------------- + +Here's an example which shows how you can: + +* Use a logging level based on command-line arguments +* Dispatch to multiple subcommands in separate files, all logging at the same + level in a consistent way +* Make use of simple, minimal configuration + +Suppose we have a command-line application whose job is to stop, start or +restart some services. This could be organised for the purposes of illustration +as a file ``app.py`` that is the main script for the application, with individual +commands implemented in ``start.py``, ``stop.py`` and ``restart.py``. Suppose +further that we want to control the verbosity of the application via a +command-line argument, defaulting to ``logging.INFO``. Here's one way that +``app.py`` could be written:: + + import argparse + import importlib + import logging + import os + import sys + + def main(args=None): + scriptname = os.path.basename(__file__) + parser = argparse.ArgumentParser(scriptname) + levels = ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL') + parser.add_argument('--log-level', default='INFO', choices=levels) + subparsers = parser.add_subparsers(dest='command', + help='Available commands:') + start_cmd = subparsers.add_parser('start', help='Start a service') + start_cmd.add_argument('name', metavar='NAME', + help='Name of service to start') + stop_cmd = subparsers.add_parser('stop', + help='Stop one or more services') + stop_cmd.add_argument('names', metavar='NAME', nargs='+', + help='Name of service to stop') + restart_cmd = subparsers.add_parser('restart', + help='Restart one or more services') + restart_cmd.add_argument('names', metavar='NAME', nargs='+', + help='Name of service to restart') + options = parser.parse_args() + # the code to dispatch commands could all be in this file. For the purposes + # of illustration only, we implement each command in a separate module. + try: + mod = importlib.import_module(options.command) + cmd = getattr(mod, 'command') + except (ImportError, AttributeError): + print('Unable to find the code for command \'%s\'' % options.command) + return 1 + # Could get fancy here and load configuration from file or dictionary + logging.basicConfig(level=options.log_level, + format='%(levelname)s %(name)s %(message)s') + cmd(options) + + if __name__ == '__main__': + sys.exit(main()) + +And the ``start``, ``stop`` and ``restart`` commands can be implemented in +separate modules, like so for starting:: + + # start.py + import logging + + logger = logging.getLogger(__name__) + + def command(options): + logger.debug('About to start %s', options.name) + # actually do the command processing here ... + logger.info('Started the \'%s\' service.', options.name) + +and thus for stopping:: + + # stop.py + import logging + + logger = logging.getLogger(__name__) + + def command(options): + n = len(options.names) + if n == 1: + plural = '' + services = '\'%s\'' % options.names[0] + else: + plural = 's' + services = ', '.join('\'%s\'' % name for name in options.names) + i = services.rfind(', ') + services = services[:i] + ' and ' + services[i + 2:] + logger.debug('About to stop %s', services) + # actually do the command processing here ... + logger.info('Stopped the %s service%s.', services, plural) + +and similarly for restarting:: + + # restart.py + import logging + + logger = logging.getLogger(__name__) + + def command(options): + n = len(options.names) + if n == 1: + plural = '' + services = '\'%s\'' % options.names[0] + else: + plural = 's' + services = ', '.join('\'%s\'' % name for name in options.names) + i = services.rfind(', ') + services = services[:i] + ' and ' + services[i + 2:] + logger.debug('About to restart %s', services) + # actually do the command processing here ... + logger.info('Restarted the %s service%s.', services, plural) + +If we run this application with the default log level, we get output like this: + +.. code-block:: shell-session + + $ python app.py start foo + INFO start Started the 'foo' service. + + $ python app.py stop foo bar + INFO stop Stopped the 'foo' and 'bar' services. + + $ python app.py restart foo bar baz + INFO restart Restarted the 'foo', 'bar' and 'baz' services. + +The first word is the logging level, and the second word is the module or +package name of the place where the event was logged. + +If we change the logging level, then we can change the information sent to the +log. For example, if we want more information: + +.. code-block:: shell-session + + $ python app.py --log-level DEBUG start foo + DEBUG start About to start foo + INFO start Started the 'foo' service. + + $ python app.py --log-level DEBUG stop foo bar + DEBUG stop About to stop 'foo' and 'bar' + INFO stop Stopped the 'foo' and 'bar' services. + + $ python app.py --log-level DEBUG restart foo bar baz + DEBUG restart About to restart 'foo', 'bar' and 'baz' + INFO restart Restarted the 'foo', 'bar' and 'baz' services. + +And if we want less: + +.. code-block:: shell-session + + $ python app.py --log-level WARNING start foo + $ python app.py --log-level WARNING stop foo bar + $ python app.py --log-level WARNING restart foo bar baz + +In this case, the commands don't print anything to the console, since nothing +at ``WARNING`` level or above is logged by them. + +.. _qt-gui: + +A Qt GUI for logging +-------------------- + +A question that comes up from time to time is about how to log to a GUI +application. The `Qt <https://www.qt.io/>`_ framework is a popular +cross-platform UI framework with Python bindings using `PySide2 +<https://pypi.org/project/PySide2/>`_ or `PyQt5 +<https://pypi.org/project/PyQt5/>`_ libraries. + +The following example shows how to log to a Qt GUI. This introduces a simple +``QtHandler`` class which takes a callable, which should be a slot in the main +thread that does GUI updates. A worker thread is also created to show how you +can log to the GUI from both the UI itself (via a button for manual logging) +as well as a worker thread doing work in the background (here, just logging +messages at random levels with random short delays in between). + +The worker thread is implemented using Qt's ``QThread`` class rather than the +:mod:`threading` module, as there are circumstances where one has to use +``QThread``, which offers better integration with other ``Qt`` components. + +The code should work with recent releases of either ``PySide2`` or ``PyQt5``. +You should be able to adapt the approach to earlier versions of Qt. Please +refer to the comments in the code snippet for more detailed information. + +.. code-block:: python3 + + import datetime + import logging + import random + import sys + import time + + # Deal with minor differences between PySide2 and PyQt5 + try: + from PySide2 import QtCore, QtGui, QtWidgets + Signal = QtCore.Signal + Slot = QtCore.Slot + except ImportError: + from PyQt5 import QtCore, QtGui, QtWidgets + Signal = QtCore.pyqtSignal + Slot = QtCore.pyqtSlot + + + logger = logging.getLogger(__name__) + + + # + # Signals need to be contained in a QObject or subclass in order to be correctly + # initialized. + # + class Signaller(QtCore.QObject): + signal = Signal(str, logging.LogRecord) + + # + # Output to a Qt GUI is only supposed to happen on the main thread. So, this + # handler is designed to take a slot function which is set up to run in the main + # thread. In this example, the function takes a string argument which is a + # formatted log message, and the log record which generated it. The formatted + # string is just a convenience - you could format a string for output any way + # you like in the slot function itself. + # + # You specify the slot function to do whatever GUI updates you want. The handler + # doesn't know or care about specific UI elements. + # + class QtHandler(logging.Handler): + def __init__(self, slotfunc, *args, **kwargs): + super(QtHandler, self).__init__(*args, **kwargs) + self.signaller = Signaller() + self.signaller.signal.connect(slotfunc) + + def emit(self, record): + s = self.format(record) + self.signaller.signal.emit(s, record) + + # + # This example uses QThreads, which means that the threads at the Python level + # are named something like "Dummy-1". The function below gets the Qt name of the + # current thread. + # + def ctname(): + return QtCore.QThread.currentThread().objectName() + + + # + # Used to generate random levels for logging. + # + LEVELS = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, + logging.CRITICAL) + + # + # This worker class represents work that is done in a thread separate to the + # main thread. The way the thread is kicked off to do work is via a button press + # that connects to a slot in the worker. + # + # Because the default threadName value in the LogRecord isn't much use, we add + # a qThreadName which contains the QThread name as computed above, and pass that + # value in an "extra" dictionary which is used to update the LogRecord with the + # QThread name. + # + # This example worker just outputs messages sequentially, interspersed with + # random delays of the order of a few seconds. + # + class Worker(QtCore.QObject): + @Slot() + def start(self): + extra = {'qThreadName': ctname() } + logger.debug('Started work', extra=extra) + i = 1 + # Let the thread run until interrupted. This allows reasonably clean + # thread termination. + while not QtCore.QThread.currentThread().isInterruptionRequested(): + delay = 0.5 + random.random() * 2 + time.sleep(delay) + level = random.choice(LEVELS) + logger.log(level, 'Message after delay of %3.1f: %d', delay, i, extra=extra) + i += 1 + + # + # Implement a simple UI for this cookbook example. This contains: + # + # * A read-only text edit window which holds formatted log messages + # * A button to start work and log stuff in a separate thread + # * A button to log something from the main thread + # * A button to clear the log window + # + class Window(QtWidgets.QWidget): + + COLORS = { + logging.DEBUG: 'black', + logging.INFO: 'blue', + logging.WARNING: 'orange', + logging.ERROR: 'red', + logging.CRITICAL: 'purple', + } + + def __init__(self, app): + super(Window, self).__init__() + self.app = app + self.textedit = te = QtWidgets.QPlainTextEdit(self) + # Set whatever the default monospace font is for the platform + f = QtGui.QFont('nosuchfont') + f.setStyleHint(f.Monospace) + te.setFont(f) + te.setReadOnly(True) + PB = QtWidgets.QPushButton + self.work_button = PB('Start background work', self) + self.log_button = PB('Log a message at a random level', self) + self.clear_button = PB('Clear log window', self) + self.handler = h = QtHandler(self.update_status) + # Remember to use qThreadName rather than threadName in the format string. + fs = '%(asctime)s %(qThreadName)-12s %(levelname)-8s %(message)s' + formatter = logging.Formatter(fs) + h.setFormatter(formatter) + logger.addHandler(h) + # Set up to terminate the QThread when we exit + app.aboutToQuit.connect(self.force_quit) + + # Lay out all the widgets + layout = QtWidgets.QVBoxLayout(self) + layout.addWidget(te) + layout.addWidget(self.work_button) + layout.addWidget(self.log_button) + layout.addWidget(self.clear_button) + self.setFixedSize(900, 400) + + # Connect the non-worker slots and signals + self.log_button.clicked.connect(self.manual_update) + self.clear_button.clicked.connect(self.clear_display) + + # Start a new worker thread and connect the slots for the worker + self.start_thread() + self.work_button.clicked.connect(self.worker.start) + # Once started, the button should be disabled + self.work_button.clicked.connect(lambda : self.work_button.setEnabled(False)) + + def start_thread(self): + self.worker = Worker() + self.worker_thread = QtCore.QThread() + self.worker.setObjectName('Worker') + self.worker_thread.setObjectName('WorkerThread') # for qThreadName + self.worker.moveToThread(self.worker_thread) + # This will start an event loop in the worker thread + self.worker_thread.start() + + def kill_thread(self): + # Just tell the worker to stop, then tell it to quit and wait for that + # to happen + self.worker_thread.requestInterruption() + if self.worker_thread.isRunning(): + self.worker_thread.quit() + self.worker_thread.wait() + else: + print('worker has already exited.') + + def force_quit(self): + # For use when the window is closed + if self.worker_thread.isRunning(): + self.kill_thread() + + # The functions below update the UI and run in the main thread because + # that's where the slots are set up + + @Slot(str, logging.LogRecord) + def update_status(self, status, record): + color = self.COLORS.get(record.levelno, 'black') + s = '<pre><font color="%s">%s</font></pre>' % (color, status) + self.textedit.appendHtml(s) + + @Slot() + def manual_update(self): + # This function uses the formatted message passed in, but also uses + # information from the record to format the message in an appropriate + # color according to its severity (level). + level = random.choice(LEVELS) + extra = {'qThreadName': ctname() } + logger.log(level, 'Manually logged!', extra=extra) + + @Slot() + def clear_display(self): + self.textedit.clear() + + + def main(): + QtCore.QThread.currentThread().setObjectName('MainThread') + logging.getLogger().setLevel(logging.DEBUG) + app = QtWidgets.QApplication(sys.argv) + example = Window(app) + example.show() + sys.exit(app.exec_()) + + if __name__=='__main__': + main() diff --git a/cpython_2/environment/repo/Doc/howto/logging.rst b/cpython_2/environment/repo/Doc/howto/logging.rst new file mode 100644 index 0000000000000000000000000000000000000000..6316e086ef43ba25bd15f3804aff5cc45e84ba0a --- /dev/null +++ b/cpython_2/environment/repo/Doc/howto/logging.rst @@ -0,0 +1,1111 @@ +============= +Logging HOWTO +============= + +:Author: Vinay Sajip <vinay_sajip at red-dove dot com> + +.. _logging-basic-tutorial: + +.. currentmodule:: logging + +Basic Logging Tutorial +---------------------- + +Logging is a means of tracking events that happen when some software runs. The +software's developer adds logging calls to their code to indicate that certain +events have occurred. An event is described by a descriptive message which can +optionally contain variable data (i.e. data that is potentially different for +each occurrence of the event). Events also have an importance which the +developer ascribes to the event; the importance can also be called the *level* +or *severity*. + +When to use logging +^^^^^^^^^^^^^^^^^^^ + +Logging provides a set of convenience functions for simple logging usage. These +are :func:`debug`, :func:`info`, :func:`warning`, :func:`error` and +:func:`critical`. To determine when to use logging, see the table below, which +states, for each of a set of common tasks, the best tool to use for it. + ++-------------------------------------+--------------------------------------+ +| Task you want to perform | The best tool for the task | ++=====================================+======================================+ +| Display console output for ordinary | :func:`print` | +| usage of a command line script or | | +| program | | ++-------------------------------------+--------------------------------------+ +| Report events that occur during | :func:`logging.info` (or | +| normal operation of a program (e.g. | :func:`logging.debug` for very | +| for status monitoring or fault | detailed output for diagnostic | +| investigation) | purposes) | ++-------------------------------------+--------------------------------------+ +| Issue a warning regarding a | :func:`warnings.warn` in library | +| particular runtime event | code if the issue is avoidable and | +| | the client application should be | +| | modified to eliminate the warning | +| | | +| | :func:`logging.warning` if there is | +| | nothing the client application can do| +| | about the situation, but the event | +| | should still be noted | ++-------------------------------------+--------------------------------------+ +| Report an error regarding a | Raise an exception | +| particular runtime event | | ++-------------------------------------+--------------------------------------+ +| Report suppression of an error | :func:`logging.error`, | +| without raising an exception (e.g. | :func:`logging.exception` or | +| error handler in a long-running | :func:`logging.critical` as | +| server process) | appropriate for the specific error | +| | and application domain | ++-------------------------------------+--------------------------------------+ + +The logging functions are named after the level or severity of the events +they are used to track. The standard levels and their applicability are +described below (in increasing order of severity): + +.. tabularcolumns:: |l|L| + ++--------------+---------------------------------------------+ +| Level | When it's used | ++==============+=============================================+ +| ``DEBUG`` | Detailed information, typically of interest | +| | only when diagnosing problems. | ++--------------+---------------------------------------------+ +| ``INFO`` | Confirmation that things are working as | +| | expected. | ++--------------+---------------------------------------------+ +| ``WARNING`` | An indication that something unexpected | +| | happened, or indicative of some problem in | +| | the near future (e.g. 'disk space low'). | +| | The software is still working as expected. | ++--------------+---------------------------------------------+ +| ``ERROR`` | Due to a more serious problem, the software | +| | has not been able to perform some function. | ++--------------+---------------------------------------------+ +| ``CRITICAL`` | A serious error, indicating that the program| +| | itself may be unable to continue running. | ++--------------+---------------------------------------------+ + +The default level is ``WARNING``, which means that only events of this level +and above will be tracked, unless the logging package is configured to do +otherwise. + +Events that are tracked can be handled in different ways. The simplest way of +handling tracked events is to print them to the console. Another common way +is to write them to a disk file. + + +.. _howto-minimal-example: + +A simple example +^^^^^^^^^^^^^^^^ + +A very simple example is:: + + import logging + logging.warning('Watch out!') # will print a message to the console + logging.info('I told you so') # will not print anything + +If you type these lines into a script and run it, you'll see: + +.. code-block:: none + + WARNING:root:Watch out! + +printed out on the console. The ``INFO`` message doesn't appear because the +default level is ``WARNING``. The printed message includes the indication of +the level and the description of the event provided in the logging call, i.e. +'Watch out!'. Don't worry about the 'root' part for now: it will be explained +later. The actual output can be formatted quite flexibly if you need that; +formatting options will also be explained later. + + +Logging to a file +^^^^^^^^^^^^^^^^^ + +A very common situation is that of recording logging events in a file, so let's +look at that next. Be sure to try the following in a newly-started Python +interpreter, and don't just continue from the session described above:: + + import logging + logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG) + logging.debug('This message should go to the log file') + logging.info('So should this') + logging.warning('And this, too') + logging.error('And non-ASCII stuff, too, like Øresund and Malmö') + +.. versionchanged:: 3.9 + The *encoding* argument was added. In earlier Python versions, or if not + specified, the encoding used is the default value used by :func:`open`. While + not shown in the above example, an *errors* argument can also now be passed, + which determines how encoding errors are handled. For available values and + the default, see the documentation for :func:`open`. + +And now if we open the file and look at what we have, we should find the log +messages: + +.. code-block:: none + + DEBUG:root:This message should go to the log file + INFO:root:So should this + WARNING:root:And this, too + ERROR:root:And non-ASCII stuff, too, like Øresund and Malmö + +This example also shows how you can set the logging level which acts as the +threshold for tracking. In this case, because we set the threshold to +``DEBUG``, all of the messages were printed. + +If you want to set the logging level from a command-line option such as: + +.. code-block:: none + + --log=INFO + +and you have the value of the parameter passed for ``--log`` in some variable +*loglevel*, you can use:: + + getattr(logging, loglevel.upper()) + +to get the value which you'll pass to :func:`basicConfig` via the *level* +argument. You may want to error check any user input value, perhaps as in the +following example:: + + # assuming loglevel is bound to the string value obtained from the + # command line argument. Convert to upper case to allow the user to + # specify --log=DEBUG or --log=debug + numeric_level = getattr(logging, loglevel.upper(), None) + if not isinstance(numeric_level, int): + raise ValueError('Invalid log level: %s' % loglevel) + logging.basicConfig(level=numeric_level, ...) + +The call to :func:`basicConfig` should come *before* any calls to :func:`debug`, +:func:`info` etc. As it's intended as a one-off simple configuration facility, +only the first call will actually do anything: subsequent calls are effectively +no-ops. + +If you run the above script several times, the messages from successive runs +are appended to the file *example.log*. If you want each run to start afresh, +not remembering the messages from earlier runs, you can specify the *filemode* +argument, by changing the call in the above example to:: + + logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG) + +The output will be the same as before, but the log file is no longer appended +to, so the messages from earlier runs are lost. + + +Logging from multiple modules +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +If your program consists of multiple modules, here's an example of how you +could organize logging in it:: + + # myapp.py + import logging + import mylib + + def main(): + logging.basicConfig(filename='myapp.log', level=logging.INFO) + logging.info('Started') + mylib.do_something() + logging.info('Finished') + + if __name__ == '__main__': + main() + +:: + + # mylib.py + import logging + + def do_something(): + logging.info('Doing something') + +If you run *myapp.py*, you should see this in *myapp.log*: + +.. code-block:: none + + INFO:root:Started + INFO:root:Doing something + INFO:root:Finished + +which is hopefully what you were expecting to see. You can generalize this to +multiple modules, using the pattern in *mylib.py*. Note that for this simple +usage pattern, you won't know, by looking in the log file, *where* in your +application your messages came from, apart from looking at the event +description. If you want to track the location of your messages, you'll need +to refer to the documentation beyond the tutorial level -- see +:ref:`logging-advanced-tutorial`. + + +Logging variable data +^^^^^^^^^^^^^^^^^^^^^ + +To log variable data, use a format string for the event description message and +append the variable data as arguments. For example:: + + import logging + logging.warning('%s before you %s', 'Look', 'leap!') + +will display: + +.. code-block:: none + + WARNING:root:Look before you leap! + +As you can see, merging of variable data into the event description message +uses the old, %-style of string formatting. This is for backwards +compatibility: the logging package pre-dates newer formatting options such as +:meth:`str.format` and :class:`string.Template`. These newer formatting +options *are* supported, but exploring them is outside the scope of this +tutorial: see :ref:`formatting-styles` for more information. + + +Changing the format of displayed messages +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +To change the format which is used to display messages, you need to +specify the format you want to use:: + + import logging + logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG) + logging.debug('This message should appear on the console') + logging.info('So should this') + logging.warning('And this, too') + +which would print: + +.. code-block:: none + + DEBUG:This message should appear on the console + INFO:So should this + WARNING:And this, too + +Notice that the 'root' which appeared in earlier examples has disappeared. For +a full set of things that can appear in format strings, you can refer to the +documentation for :ref:`logrecord-attributes`, but for simple usage, you just +need the *levelname* (severity), *message* (event description, including +variable data) and perhaps to display when the event occurred. This is +described in the next section. + + +Displaying the date/time in messages +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +To display the date and time of an event, you would place '%(asctime)s' in +your format string:: + + import logging + logging.basicConfig(format='%(asctime)s %(message)s') + logging.warning('is when this event was logged.') + +which should print something like this: + +.. code-block:: none + + 2010-12-12 11:41:42,612 is when this event was logged. + +The default format for date/time display (shown above) is like ISO8601 or +:rfc:`3339`. If you need more control over the formatting of the date/time, provide +a *datefmt* argument to ``basicConfig``, as in this example:: + + import logging + logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p') + logging.warning('is when this event was logged.') + +which would display something like this: + +.. code-block:: none + + 12/12/2010 11:46:36 AM is when this event was logged. + +The format of the *datefmt* argument is the same as supported by +:func:`time.strftime`. + + +Next Steps +^^^^^^^^^^ + +That concludes the basic tutorial. It should be enough to get you up and +running with logging. There's a lot more that the logging package offers, but +to get the best out of it, you'll need to invest a little more of your time in +reading the following sections. If you're ready for that, grab some of your +favourite beverage and carry on. + +If your logging needs are simple, then use the above examples to incorporate +logging into your own scripts, and if you run into problems or don't +understand something, please post a question on the comp.lang.python Usenet +group (available at https://groups.google.com/forum/#!forum/comp.lang.python) and you +should receive help before too long. + +Still here? You can carry on reading the next few sections, which provide a +slightly more advanced/in-depth tutorial than the basic one above. After that, +you can take a look at the :ref:`logging-cookbook`. + +.. _logging-advanced-tutorial: + + +Advanced Logging Tutorial +------------------------- + +The logging library takes a modular approach and offers several categories +of components: loggers, handlers, filters, and formatters. + +* Loggers expose the interface that application code directly uses. +* Handlers send the log records (created by loggers) to the appropriate + destination. +* Filters provide a finer grained facility for determining which log records + to output. +* Formatters specify the layout of log records in the final output. + +Log event information is passed between loggers, handlers, filters and +formatters in a :class:`LogRecord` instance. + +Logging is performed by calling methods on instances of the :class:`Logger` +class (hereafter called :dfn:`loggers`). Each instance has a name, and they are +conceptually arranged in a namespace hierarchy using dots (periods) as +separators. For example, a logger named 'scan' is the parent of loggers +'scan.text', 'scan.html' and 'scan.pdf'. Logger names can be anything you want, +and indicate the area of an application in which a logged message originates. + +A good convention to use when naming loggers is to use a module-level logger, +in each module which uses logging, named as follows:: + + logger = logging.getLogger(__name__) + +This means that logger names track the package/module hierarchy, and it's +intuitively obvious where events are logged just from the logger name. + +The root of the hierarchy of loggers is called the root logger. That's the +logger used by the functions :func:`debug`, :func:`info`, :func:`warning`, +:func:`error` and :func:`critical`, which just call the same-named method of +the root logger. The functions and the methods have the same signatures. The +root logger's name is printed as 'root' in the logged output. + +It is, of course, possible to log messages to different destinations. Support +is included in the package for writing log messages to files, HTTP GET/POST +locations, email via SMTP, generic sockets, queues, or OS-specific logging +mechanisms such as syslog or the Windows NT event log. Destinations are served +by :dfn:`handler` classes. You can create your own log destination class if +you have special requirements not met by any of the built-in handler classes. + +By default, no destination is set for any logging messages. You can specify +a destination (such as console or file) by using :func:`basicConfig` as in the +tutorial examples. If you call the functions :func:`debug`, :func:`info`, +:func:`warning`, :func:`error` and :func:`critical`, they will check to see +if no destination is set; and if one is not set, they will set a destination +of the console (``sys.stderr``) and a default format for the displayed +message before delegating to the root logger to do the actual message output. + +The default format set by :func:`basicConfig` for messages is: + +.. code-block:: none + + severity:logger name:message + +You can change this by passing a format string to :func:`basicConfig` with the +*format* keyword argument. For all options regarding how a format string is +constructed, see :ref:`formatter-objects`. + +Logging Flow +^^^^^^^^^^^^ + +The flow of log event information in loggers and handlers is illustrated in the +following diagram. + +.. image:: logging_flow.png + +Loggers +^^^^^^^ + +:class:`Logger` objects have a threefold job. First, they expose several +methods to application code so that applications can log messages at runtime. +Second, logger objects determine which log messages to act upon based upon +severity (the default filtering facility) or filter objects. Third, logger +objects pass along relevant log messages to all interested log handlers. + +The most widely used methods on logger objects fall into two categories: +configuration and message sending. + +These are the most common configuration methods: + +* :meth:`Logger.setLevel` specifies the lowest-severity log message a logger + will handle, where debug is the lowest built-in severity level and critical + is the highest built-in severity. For example, if the severity level is + INFO, the logger will handle only INFO, WARNING, ERROR, and CRITICAL messages + and will ignore DEBUG messages. + +* :meth:`Logger.addHandler` and :meth:`Logger.removeHandler` add and remove + handler objects from the logger object. Handlers are covered in more detail + in :ref:`handler-basic`. + +* :meth:`Logger.addFilter` and :meth:`Logger.removeFilter` add and remove filter + objects from the logger object. Filters are covered in more detail in + :ref:`filter`. + +You don't need to always call these methods on every logger you create. See the +last two paragraphs in this section. + +With the logger object configured, the following methods create log messages: + +* :meth:`Logger.debug`, :meth:`Logger.info`, :meth:`Logger.warning`, + :meth:`Logger.error`, and :meth:`Logger.critical` all create log records with + a message and a level that corresponds to their respective method names. The + message is actually a format string, which may contain the standard string + substitution syntax of ``%s``, ``%d``, ``%f``, and so on. The + rest of their arguments is a list of objects that correspond with the + substitution fields in the message. With regard to ``**kwargs``, the + logging methods care only about a keyword of ``exc_info`` and use it to + determine whether to log exception information. + +* :meth:`Logger.exception` creates a log message similar to + :meth:`Logger.error`. The difference is that :meth:`Logger.exception` dumps a + stack trace along with it. Call this method only from an exception handler. + +* :meth:`Logger.log` takes a log level as an explicit argument. This is a + little more verbose for logging messages than using the log level convenience + methods listed above, but this is how to log at custom log levels. + +:func:`getLogger` returns a reference to a logger instance with the specified +name if it is provided, or ``root`` if not. The names are period-separated +hierarchical structures. Multiple calls to :func:`getLogger` with the same name +will return a reference to the same logger object. Loggers that are further +down in the hierarchical list are children of loggers higher up in the list. +For example, given a logger with a name of ``foo``, loggers with names of +``foo.bar``, ``foo.bar.baz``, and ``foo.bam`` are all descendants of ``foo``. + +Loggers have a concept of *effective level*. If a level is not explicitly set +on a logger, the level of its parent is used instead as its effective level. +If the parent has no explicit level set, *its* parent is examined, and so on - +all ancestors are searched until an explicitly set level is found. The root +logger always has an explicit level set (``WARNING`` by default). When deciding +whether to process an event, the effective level of the logger is used to +determine whether the event is passed to the logger's handlers. + +Child loggers propagate messages up to the handlers associated with their +ancestor loggers. Because of this, it is unnecessary to define and configure +handlers for all the loggers an application uses. It is sufficient to +configure handlers for a top-level logger and create child loggers as needed. +(You can, however, turn off propagation by setting the *propagate* +attribute of a logger to ``False``.) + + +.. _handler-basic: + +Handlers +^^^^^^^^ + +:class:`~logging.Handler` objects are responsible for dispatching the +appropriate log messages (based on the log messages' severity) to the handler's +specified destination. :class:`Logger` objects can add zero or more handler +objects to themselves with an :meth:`~Logger.addHandler` method. As an example +scenario, an application may want to send all log messages to a log file, all +log messages of error or higher to stdout, and all messages of critical to an +email address. This scenario requires three individual handlers where each +handler is responsible for sending messages of a specific severity to a specific +location. + +The standard library includes quite a few handler types (see +:ref:`useful-handlers`); the tutorials use mainly :class:`StreamHandler` and +:class:`FileHandler` in its examples. + +There are very few methods in a handler for application developers to concern +themselves with. The only handler methods that seem relevant for application +developers who are using the built-in handler objects (that is, not creating +custom handlers) are the following configuration methods: + +* The :meth:`~Handler.setLevel` method, just as in logger objects, specifies the + lowest severity that will be dispatched to the appropriate destination. Why + are there two :func:`setLevel` methods? The level set in the logger + determines which severity of messages it will pass to its handlers. The level + set in each handler determines which messages that handler will send on. + +* :meth:`~Handler.setFormatter` selects a Formatter object for this handler to + use. + +* :meth:`~Handler.addFilter` and :meth:`~Handler.removeFilter` respectively + configure and deconfigure filter objects on handlers. + +Application code should not directly instantiate and use instances of +:class:`Handler`. Instead, the :class:`Handler` class is a base class that +defines the interface that all handlers should have and establishes some +default behavior that child classes can use (or override). + + +Formatters +^^^^^^^^^^ + +Formatter objects configure the final order, structure, and contents of the log +message. Unlike the base :class:`logging.Handler` class, application code may +instantiate formatter classes, although you could likely subclass the formatter +if your application needs special behavior. The constructor takes three +optional arguments -- a message format string, a date format string and a style +indicator. + +.. method:: logging.Formatter.__init__(fmt=None, datefmt=None, style='%') + +If there is no message format string, the default is to use the +raw message. If there is no date format string, the default date format is: + +.. code-block:: none + + %Y-%m-%d %H:%M:%S + +with the milliseconds tacked on at the end. The ``style`` is one of `%`, '{' +or '$'. If one of these is not specified, then '%' will be used. + +If the ``style`` is '%', the message format string uses +``%(<dictionary key>)s`` styled string substitution; the possible keys are +documented in :ref:`logrecord-attributes`. If the style is '{', the message +format string is assumed to be compatible with :meth:`str.format` (using +keyword arguments), while if the style is '$' then the message format string +should conform to what is expected by :meth:`string.Template.substitute`. + +.. versionchanged:: 3.2 + Added the ``style`` parameter. + +The following message format string will log the time in a human-readable +format, the severity of the message, and the contents of the message, in that +order:: + + '%(asctime)s - %(levelname)s - %(message)s' + +Formatters use a user-configurable function to convert the creation time of a +record to a tuple. By default, :func:`time.localtime` is used; to change this +for a particular formatter instance, set the ``converter`` attribute of the +instance to a function with the same signature as :func:`time.localtime` or +:func:`time.gmtime`. To change it for all formatters, for example if you want +all logging times to be shown in GMT, set the ``converter`` attribute in the +Formatter class (to ``time.gmtime`` for GMT display). + + +Configuring Logging +^^^^^^^^^^^^^^^^^^^ + +.. currentmodule:: logging.config + +Programmers can configure logging in three ways: + +1. Creating loggers, handlers, and formatters explicitly using Python + code that calls the configuration methods listed above. +2. Creating a logging config file and reading it using the :func:`fileConfig` + function. +3. Creating a dictionary of configuration information and passing it + to the :func:`dictConfig` function. + +For the reference documentation on the last two options, see +:ref:`logging-config-api`. The following example configures a very simple +logger, a console handler, and a simple formatter using Python code:: + + import logging + + # create logger + logger = logging.getLogger('simple_example') + logger.setLevel(logging.DEBUG) + + # create console handler and set level to debug + ch = logging.StreamHandler() + ch.setLevel(logging.DEBUG) + + # create formatter + formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') + + # add formatter to ch + ch.setFormatter(formatter) + + # add ch to logger + logger.addHandler(ch) + + # 'application' code + logger.debug('debug message') + logger.info('info message') + logger.warning('warn message') + logger.error('error message') + logger.critical('critical message') + +Running this module from the command line produces the following output: + +.. code-block:: shell-session + + $ python simple_logging_module.py + 2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message + 2005-03-19 15:10:26,620 - simple_example - INFO - info message + 2005-03-19 15:10:26,695 - simple_example - WARNING - warn message + 2005-03-19 15:10:26,697 - simple_example - ERROR - error message + 2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message + +The following Python module creates a logger, handler, and formatter nearly +identical to those in the example listed above, with the only difference being +the names of the objects:: + + import logging + import logging.config + + logging.config.fileConfig('logging.conf') + + # create logger + logger = logging.getLogger('simpleExample') + + # 'application' code + logger.debug('debug message') + logger.info('info message') + logger.warning('warn message') + logger.error('error message') + logger.critical('critical message') + +Here is the logging.conf file: + +.. code-block:: ini + + [loggers] + keys=root,simpleExample + + [handlers] + keys=consoleHandler + + [formatters] + keys=simpleFormatter + + [logger_root] + level=DEBUG + handlers=consoleHandler + + [logger_simpleExample] + level=DEBUG + handlers=consoleHandler + qualname=simpleExample + propagate=0 + + [handler_consoleHandler] + class=StreamHandler + level=DEBUG + formatter=simpleFormatter + args=(sys.stdout,) + + [formatter_simpleFormatter] + format=%(asctime)s - %(name)s - %(levelname)s - %(message)s + datefmt= + +The output is nearly identical to that of the non-config-file-based example: + +.. code-block:: shell-session + + $ python simple_logging_config.py + 2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message + 2005-03-19 15:38:55,979 - simpleExample - INFO - info message + 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message + 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message + 2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message + +You can see that the config file approach has a few advantages over the Python +code approach, mainly separation of configuration and code and the ability of +noncoders to easily modify the logging properties. + +.. warning:: The :func:`fileConfig` function takes a default parameter, + ``disable_existing_loggers``, which defaults to ``True`` for reasons of + backward compatibility. This may or may not be what you want, since it + will cause any non-root loggers existing before the :func:`fileConfig` + call to be disabled unless they (or an ancestor) are explicitly named in + the configuration. Please refer to the reference documentation for more + information, and specify ``False`` for this parameter if you wish. + + The dictionary passed to :func:`dictConfig` can also specify a Boolean + value with key ``disable_existing_loggers``, which if not specified + explicitly in the dictionary also defaults to being interpreted as + ``True``. This leads to the logger-disabling behaviour described above, + which may not be what you want - in which case, provide the key + explicitly with a value of ``False``. + + +.. currentmodule:: logging + +Note that the class names referenced in config files need to be either relative +to the logging module, or absolute values which can be resolved using normal +import mechanisms. Thus, you could use either +:class:`~logging.handlers.WatchedFileHandler` (relative to the logging module) or +``mypackage.mymodule.MyHandler`` (for a class defined in package ``mypackage`` +and module ``mymodule``, where ``mypackage`` is available on the Python import +path). + +In Python 3.2, a new means of configuring logging has been introduced, using +dictionaries to hold configuration information. This provides a superset of the +functionality of the config-file-based approach outlined above, and is the +recommended configuration method for new applications and deployments. Because +a Python dictionary is used to hold configuration information, and since you +can populate that dictionary using different means, you have more options for +configuration. For example, you can use a configuration file in JSON format, +or, if you have access to YAML processing functionality, a file in YAML +format, to populate the configuration dictionary. Or, of course, you can +construct the dictionary in Python code, receive it in pickled form over a +socket, or use whatever approach makes sense for your application. + +Here's an example of the same configuration as above, in YAML format for +the new dictionary-based approach: + +.. code-block:: yaml + + version: 1 + formatters: + simple: + format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s' + handlers: + console: + class: logging.StreamHandler + level: DEBUG + formatter: simple + stream: ext://sys.stdout + loggers: + simpleExample: + level: DEBUG + handlers: [console] + propagate: no + root: + level: DEBUG + handlers: [console] + +For more information about logging using a dictionary, see +:ref:`logging-config-api`. + +What happens if no configuration is provided +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +If no logging configuration is provided, it is possible to have a situation +where a logging event needs to be output, but no handlers can be found to +output the event. The behaviour of the logging package in these +circumstances is dependent on the Python version. + +For versions of Python prior to 3.2, the behaviour is as follows: + +* If *logging.raiseExceptions* is ``False`` (production mode), the event is + silently dropped. + +* If *logging.raiseExceptions* is ``True`` (development mode), a message + 'No handlers could be found for logger X.Y.Z' is printed once. + +In Python 3.2 and later, the behaviour is as follows: + +* The event is output using a 'handler of last resort', stored in + ``logging.lastResort``. This internal handler is not associated with any + logger, and acts like a :class:`~logging.StreamHandler` which writes the + event description message to the current value of ``sys.stderr`` (therefore + respecting any redirections which may be in effect). No formatting is + done on the message - just the bare event description message is printed. + The handler's level is set to ``WARNING``, so all events at this and + greater severities will be output. + +To obtain the pre-3.2 behaviour, ``logging.lastResort`` can be set to ``None``. + +.. _library-config: + +Configuring Logging for a Library +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +When developing a library which uses logging, you should take care to +document how the library uses logging - for example, the names of loggers +used. Some consideration also needs to be given to its logging configuration. +If the using application does not use logging, and library code makes logging +calls, then (as described in the previous section) events of severity +``WARNING`` and greater will be printed to ``sys.stderr``. This is regarded as +the best default behaviour. + +If for some reason you *don't* want these messages printed in the absence of +any logging configuration, you can attach a do-nothing handler to the top-level +logger for your library. This avoids the message being printed, since a handler +will always be found for the library's events: it just doesn't produce any +output. If the library user configures logging for application use, presumably +that configuration will add some handlers, and if levels are suitably +configured then logging calls made in library code will send output to those +handlers, as normal. + +A do-nothing handler is included in the logging package: +:class:`~logging.NullHandler` (since Python 3.1). An instance of this handler +could be added to the top-level logger of the logging namespace used by the +library (*if* you want to prevent your library's logged events being output to +``sys.stderr`` in the absence of logging configuration). If all logging by a +library *foo* is done using loggers with names matching 'foo.x', 'foo.x.y', +etc. then the code:: + + import logging + logging.getLogger('foo').addHandler(logging.NullHandler()) + +should have the desired effect. If an organisation produces a number of +libraries, then the logger name specified can be 'orgname.foo' rather than +just 'foo'. + +.. note:: It is strongly advised that you *do not add any handlers other + than* :class:`~logging.NullHandler` *to your library's loggers*. This is + because the configuration of handlers is the prerogative of the application + developer who uses your library. The application developer knows their + target audience and what handlers are most appropriate for their + application: if you add handlers 'under the hood', you might well interfere + with their ability to carry out unit tests and deliver logs which suit their + requirements. + + +Logging Levels +-------------- + +The numeric values of logging levels are given in the following table. These are +primarily of interest if you want to define your own levels, and need them to +have specific values relative to the predefined levels. If you define a level +with the same numeric value, it overwrites the predefined value; the predefined +name is lost. + ++--------------+---------------+ +| Level | Numeric value | ++==============+===============+ +| ``CRITICAL`` | 50 | ++--------------+---------------+ +| ``ERROR`` | 40 | ++--------------+---------------+ +| ``WARNING`` | 30 | ++--------------+---------------+ +| ``INFO`` | 20 | ++--------------+---------------+ +| ``DEBUG`` | 10 | ++--------------+---------------+ +| ``NOTSET`` | 0 | ++--------------+---------------+ + +Levels can also be associated with loggers, being set either by the developer or +through loading a saved logging configuration. When a logging method is called +on a logger, the logger compares its own level with the level associated with +the method call. If the logger's level is higher than the method call's, no +logging message is actually generated. This is the basic mechanism controlling +the verbosity of logging output. + +Logging messages are encoded as instances of the :class:`~logging.LogRecord` +class. When a logger decides to actually log an event, a +:class:`~logging.LogRecord` instance is created from the logging message. + +Logging messages are subjected to a dispatch mechanism through the use of +:dfn:`handlers`, which are instances of subclasses of the :class:`Handler` +class. Handlers are responsible for ensuring that a logged message (in the form +of a :class:`LogRecord`) ends up in a particular location (or set of locations) +which is useful for the target audience for that message (such as end users, +support desk staff, system administrators, developers). Handlers are passed +:class:`LogRecord` instances intended for particular destinations. Each logger +can have zero, one or more handlers associated with it (via the +:meth:`~Logger.addHandler` method of :class:`Logger`). In addition to any +handlers directly associated with a logger, *all handlers associated with all +ancestors of the logger* are called to dispatch the message (unless the +*propagate* flag for a logger is set to a false value, at which point the +passing to ancestor handlers stops). + +Just as for loggers, handlers can have levels associated with them. A handler's +level acts as a filter in the same way as a logger's level does. If a handler +decides to actually dispatch an event, the :meth:`~Handler.emit` method is used +to send the message to its destination. Most user-defined subclasses of +:class:`Handler` will need to override this :meth:`~Handler.emit`. + +.. _custom-levels: + +Custom Levels +^^^^^^^^^^^^^ + +Defining your own levels is possible, but should not be necessary, as the +existing levels have been chosen on the basis of practical experience. +However, if you are convinced that you need custom levels, great care should +be exercised when doing this, and it is possibly *a very bad idea to define +custom levels if you are developing a library*. That's because if multiple +library authors all define their own custom levels, there is a chance that +the logging output from such multiple libraries used together will be +difficult for the using developer to control and/or interpret, because a +given numeric value might mean different things for different libraries. + +.. _useful-handlers: + +Useful Handlers +--------------- + +In addition to the base :class:`Handler` class, many useful subclasses are +provided: + +#. :class:`StreamHandler` instances send messages to streams (file-like + objects). + +#. :class:`FileHandler` instances send messages to disk files. + +#. :class:`~handlers.BaseRotatingHandler` is the base class for handlers that + rotate log files at a certain point. It is not meant to be instantiated + directly. Instead, use :class:`~handlers.RotatingFileHandler` or + :class:`~handlers.TimedRotatingFileHandler`. + +#. :class:`~handlers.RotatingFileHandler` instances send messages to disk + files, with support for maximum log file sizes and log file rotation. + +#. :class:`~handlers.TimedRotatingFileHandler` instances send messages to + disk files, rotating the log file at certain timed intervals. + +#. :class:`~handlers.SocketHandler` instances send messages to TCP/IP + sockets. Since 3.4, Unix domain sockets are also supported. + +#. :class:`~handlers.DatagramHandler` instances send messages to UDP + sockets. Since 3.4, Unix domain sockets are also supported. + +#. :class:`~handlers.SMTPHandler` instances send messages to a designated + email address. + +#. :class:`~handlers.SysLogHandler` instances send messages to a Unix + syslog daemon, possibly on a remote machine. + +#. :class:`~handlers.NTEventLogHandler` instances send messages to a + Windows NT/2000/XP event log. + +#. :class:`~handlers.MemoryHandler` instances send messages to a buffer + in memory, which is flushed whenever specific criteria are met. + +#. :class:`~handlers.HTTPHandler` instances send messages to an HTTP + server using either ``GET`` or ``POST`` semantics. + +#. :class:`~handlers.WatchedFileHandler` instances watch the file they are + logging to. If the file changes, it is closed and reopened using the file + name. This handler is only useful on Unix-like systems; Windows does not + support the underlying mechanism used. + +#. :class:`~handlers.QueueHandler` instances send messages to a queue, such as + those implemented in the :mod:`queue` or :mod:`multiprocessing` modules. + +#. :class:`NullHandler` instances do nothing with error messages. They are used + by library developers who want to use logging, but want to avoid the 'No + handlers could be found for logger XXX' message which can be displayed if + the library user has not configured logging. See :ref:`library-config` for + more information. + +.. versionadded:: 3.1 + The :class:`NullHandler` class. + +.. versionadded:: 3.2 + The :class:`~handlers.QueueHandler` class. + +The :class:`NullHandler`, :class:`StreamHandler` and :class:`FileHandler` +classes are defined in the core logging package. The other handlers are +defined in a sub-module, :mod:`logging.handlers`. (There is also another +sub-module, :mod:`logging.config`, for configuration functionality.) + +Logged messages are formatted for presentation through instances of the +:class:`Formatter` class. They are initialized with a format string suitable for +use with the % operator and a dictionary. + +For formatting multiple messages in a batch, instances of +:class:`~handlers.BufferingFormatter` can be used. In addition to the format +string (which is applied to each message in the batch), there is provision for +header and trailer format strings. + +When filtering based on logger level and/or handler level is not enough, +instances of :class:`Filter` can be added to both :class:`Logger` and +:class:`Handler` instances (through their :meth:`~Handler.addFilter` method). +Before deciding to process a message further, both loggers and handlers consult +all their filters for permission. If any filter returns a false value, the +message is not processed further. + +The basic :class:`Filter` functionality allows filtering by specific logger +name. If this feature is used, messages sent to the named logger and its +children are allowed through the filter, and all others dropped. + + +.. _logging-exceptions: + +Exceptions raised during logging +-------------------------------- + +The logging package is designed to swallow exceptions which occur while logging +in production. This is so that errors which occur while handling logging events +- such as logging misconfiguration, network or other similar errors - do not +cause the application using logging to terminate prematurely. + +:class:`SystemExit` and :class:`KeyboardInterrupt` exceptions are never +swallowed. Other exceptions which occur during the :meth:`~Handler.emit` method +of a :class:`Handler` subclass are passed to its :meth:`~Handler.handleError` +method. + +The default implementation of :meth:`~Handler.handleError` in :class:`Handler` +checks to see if a module-level variable, :data:`raiseExceptions`, is set. If +set, a traceback is printed to :data:`sys.stderr`. If not set, the exception is +swallowed. + +.. note:: The default value of :data:`raiseExceptions` is ``True``. This is + because during development, you typically want to be notified of any + exceptions that occur. It's advised that you set :data:`raiseExceptions` to + ``False`` for production usage. + +.. currentmodule:: logging + +.. _arbitrary-object-messages: + +Using arbitrary objects as messages +----------------------------------- + +In the preceding sections and examples, it has been assumed that the message +passed when logging the event is a string. However, this is not the only +possibility. You can pass an arbitrary object as a message, and its +:meth:`~object.__str__` method will be called when the logging system needs to +convert it to a string representation. In fact, if you want to, you can avoid +computing a string representation altogether - for example, the +:class:`~handlers.SocketHandler` emits an event by pickling it and sending it +over the wire. + + +Optimization +------------ + +Formatting of message arguments is deferred until it cannot be avoided. +However, computing the arguments passed to the logging method can also be +expensive, and you may want to avoid doing it if the logger will just throw +away your event. To decide what to do, you can call the +:meth:`~Logger.isEnabledFor` method which takes a level argument and returns +true if the event would be created by the Logger for that level of call. +You can write code like this:: + + if logger.isEnabledFor(logging.DEBUG): + logger.debug('Message with %s, %s', expensive_func1(), + expensive_func2()) + +so that if the logger's threshold is set above ``DEBUG``, the calls to +:func:`expensive_func1` and :func:`expensive_func2` are never made. + +.. note:: In some cases, :meth:`~Logger.isEnabledFor` can itself be more + expensive than you'd like (e.g. for deeply nested loggers where an explicit + level is only set high up in the logger hierarchy). In such cases (or if you + want to avoid calling a method in tight loops), you can cache the result of a + call to :meth:`~Logger.isEnabledFor` in a local or instance variable, and use + that instead of calling the method each time. Such a cached value would only + need to be recomputed when the logging configuration changes dynamically + while the application is running (which is not all that common). + +There are other optimizations which can be made for specific applications which +need more precise control over what logging information is collected. Here's a +list of things you can do to avoid processing during logging which you don't +need: + ++-----------------------------------------------+----------------------------------------+ +| What you don't want to collect | How to avoid collecting it | ++===============================================+========================================+ +| Information about where calls were made from. | Set ``logging._srcfile`` to ``None``. | +| | This avoids calling | +| | :func:`sys._getframe`, which may help | +| | to speed up your code in environments | +| | like PyPy (which can't speed up code | +| | that uses :func:`sys._getframe`). | ++-----------------------------------------------+----------------------------------------+ +| Threading information. | Set ``logging.logThreads`` to ``0``. | ++-----------------------------------------------+----------------------------------------+ +| Process information. | Set ``logging.logProcesses`` to ``0``. | ++-----------------------------------------------+----------------------------------------+ + +Also note that the core logging module only includes the basic handlers. If +you don't import :mod:`logging.handlers` and :mod:`logging.config`, they won't +take up any memory. + +.. seealso:: + + Module :mod:`logging` + API reference for the logging module. + + Module :mod:`logging.config` + Configuration API for the logging module. + + Module :mod:`logging.handlers` + Useful handlers included with the logging module. + + :ref:`A logging cookbook <logging-cookbook>` diff --git a/cpython_2/environment/repo/Doc/howto/logging_flow.png b/cpython_2/environment/repo/Doc/howto/logging_flow.png new file mode 100644 index 0000000000000000000000000000000000000000..efc3614eed8b4473bc1408e27c952fdf5e178c32 Binary files /dev/null and b/cpython_2/environment/repo/Doc/howto/logging_flow.png differ diff --git a/cpython_2/environment/repo/Doc/howto/pyporting.rst b/cpython_2/environment/repo/Doc/howto/pyporting.rst new file mode 100644 index 0000000000000000000000000000000000000000..1543823c104c289409f8c071e076784754a4cd43 --- /dev/null +++ b/cpython_2/environment/repo/Doc/howto/pyporting.rst @@ -0,0 +1,454 @@ +.. _pyporting-howto: + +********************************* +Porting Python 2 Code to Python 3 +********************************* + +:author: Brett Cannon + +.. topic:: Abstract + + With Python 3 being the future of Python while Python 2 is still in active + use, it is good to have your project available for both major releases of + Python. This guide is meant to help you figure out how best to support both + Python 2 & 3 simultaneously. + + If you are looking to port an extension module instead of pure Python code, + please see :ref:`cporting-howto`. + + If you would like to read one core Python developer's take on why Python 3 + came into existence, you can read Nick Coghlan's `Python 3 Q & A`_ or + Brett Cannon's `Why Python 3 exists`_. + + For help with porting, you can email the python-porting_ mailing list with + questions. + +The Short Explanation +===================== + +To make your project be single-source Python 2/3 compatible, the basic steps +are: + +#. Only worry about supporting Python 2.7 +#. Make sure you have good test coverage (coverage.py_ can help; + ``python -m pip install coverage``) +#. Learn the differences between Python 2 & 3 +#. Use Futurize_ (or Modernize_) to update your code (e.g. ``python -m pip install future``) +#. Use Pylint_ to help make sure you don't regress on your Python 3 support + (``python -m pip install pylint``) +#. Use caniusepython3_ to find out which of your dependencies are blocking your + use of Python 3 (``python -m pip install caniusepython3``) +#. Once your dependencies are no longer blocking you, use continuous integration + to make sure you stay compatible with Python 2 & 3 (tox_ can help test + against multiple versions of Python; ``python -m pip install tox``) +#. Consider using optional static type checking to make sure your type usage + works in both Python 2 & 3 (e.g. use mypy_ to check your typing under both + Python 2 & Python 3; ``python -m pip install mypy``). + +.. note:: + + Note: Using ``python -m pip install`` guarantees that the ``pip`` you invoke + is the one installed for the Python currently in use, whether it be + a system-wide ``pip`` or one installed within a + :ref:`virtual environment <tut-venv>`. + +Details +======= + +A key point about supporting Python 2 & 3 simultaneously is that you can start +**today**! Even if your dependencies are not supporting Python 3 yet that does +not mean you can't modernize your code **now** to support Python 3. Most changes +required to support Python 3 lead to cleaner code using newer practices even in +Python 2 code. + +Another key point is that modernizing your Python 2 code to also support +Python 3 is largely automated for you. While you might have to make some API +decisions thanks to Python 3 clarifying text data versus binary data, the +lower-level work is now mostly done for you and thus can at least benefit from +the automated changes immediately. + +Keep those key points in mind while you read on about the details of porting +your code to support Python 2 & 3 simultaneously. + + +Drop support for Python 2.6 and older +------------------------------------- + +While you can make Python 2.5 work with Python 3, it is **much** easier if you +only have to work with Python 2.7. If dropping Python 2.5 is not an +option then the six_ project can help you support Python 2.5 & 3 simultaneously +(``python -m pip install six``). Do realize, though, that nearly all the projects listed +in this HOWTO will not be available to you. + +If you are able to skip Python 2.5 and older, then the required changes +to your code should continue to look and feel like idiomatic Python code. At +worst you will have to use a function instead of a method in some instances or +have to import a function instead of using a built-in one, but otherwise the +overall transformation should not feel foreign to you. + +But you should aim for only supporting Python 2.7. Python 2.6 is no longer +freely supported and thus is not receiving bugfixes. This means **you** will have +to work around any issues you come across with Python 2.6. There are also some +tools mentioned in this HOWTO which do not support Python 2.6 (e.g., Pylint_), +and this will become more commonplace as time goes on. It will simply be easier +for you if you only support the versions of Python that you have to support. + + +Make sure you specify the proper version support in your ``setup.py`` file +-------------------------------------------------------------------------- + +In your ``setup.py`` file you should have the proper `trove classifier`_ +specifying what versions of Python you support. As your project does not support +Python 3 yet you should at least have +``Programming Language :: Python :: 2 :: Only`` specified. Ideally you should +also specify each major/minor version of Python that you do support, e.g. +``Programming Language :: Python :: 2.7``. + + +Have good test coverage +----------------------- + +Once you have your code supporting the oldest version of Python 2 you want it +to, you will want to make sure your test suite has good coverage. A good rule of +thumb is that if you want to be confident enough in your test suite that any +failures that appear after having tools rewrite your code are actual bugs in the +tools and not in your code. If you want a number to aim for, try to get over 80% +coverage (and don't feel bad if you find it hard to get better than 90% +coverage). If you don't already have a tool to measure test coverage then +coverage.py_ is recommended. + + +Learn the differences between Python 2 & 3 +------------------------------------------- + +Once you have your code well-tested you are ready to begin porting your code to +Python 3! But to fully understand how your code is going to change and what +you want to look out for while you code, you will want to learn what changes +Python 3 makes in terms of Python 2. Typically the two best ways of doing that +is reading the :ref:`"What's New" <whatsnew-index>` doc for each release of Python 3 and the +`Porting to Python 3`_ book (which is free online). There is also a handy +`cheat sheet`_ from the Python-Future project. + + +Update your code +---------------- + +Once you feel like you know what is different in Python 3 compared to Python 2, +it's time to update your code! You have a choice between two tools in porting +your code automatically: Futurize_ and Modernize_. Which tool you choose will +depend on how much like Python 3 you want your code to be. Futurize_ does its +best to make Python 3 idioms and practices exist in Python 2, e.g. backporting +the ``bytes`` type from Python 3 so that you have semantic parity between the +major versions of Python. Modernize_, +on the other hand, is more conservative and targets a Python 2/3 subset of +Python, directly relying on six_ to help provide compatibility. As Python 3 is +the future, it might be best to consider Futurize to begin adjusting to any new +practices that Python 3 introduces which you are not accustomed to yet. + +Regardless of which tool you choose, they will update your code to run under +Python 3 while staying compatible with the version of Python 2 you started with. +Depending on how conservative you want to be, you may want to run the tool over +your test suite first and visually inspect the diff to make sure the +transformation is accurate. After you have transformed your test suite and +verified that all the tests still pass as expected, then you can transform your +application code knowing that any tests which fail is a translation failure. + +Unfortunately the tools can't automate everything to make your code work under +Python 3 and so there are a handful of things you will need to update manually +to get full Python 3 support (which of these steps are necessary vary between +the tools). Read the documentation for the tool you choose to use to see what it +fixes by default and what it can do optionally to know what will (not) be fixed +for you and what you may have to fix on your own (e.g. using ``io.open()`` over +the built-in ``open()`` function is off by default in Modernize). Luckily, +though, there are only a couple of things to watch out for which can be +considered large issues that may be hard to debug if not watched for. + + +Division +++++++++ + +In Python 3, ``5 / 2 == 2.5`` and not ``2``; all division between ``int`` values +result in a ``float``. This change has actually been planned since Python 2.2 +which was released in 2002. Since then users have been encouraged to add +``from __future__ import division`` to any and all files which use the ``/`` and +``//`` operators or to be running the interpreter with the ``-Q`` flag. If you +have not been doing this then you will need to go through your code and do two +things: + +#. Add ``from __future__ import division`` to your files +#. Update any division operator as necessary to either use ``//`` to use floor + division or continue using ``/`` and expect a float + +The reason that ``/`` isn't simply translated to ``//`` automatically is that if +an object defines a ``__truediv__`` method but not ``__floordiv__`` then your +code would begin to fail (e.g. a user-defined class that uses ``/`` to +signify some operation but not ``//`` for the same thing or at all). + + +Text versus binary data ++++++++++++++++++++++++ + +In Python 2 you could use the ``str`` type for both text and binary data. +Unfortunately this confluence of two different concepts could lead to brittle +code which sometimes worked for either kind of data, sometimes not. It also +could lead to confusing APIs if people didn't explicitly state that something +that accepted ``str`` accepted either text or binary data instead of one +specific type. This complicated the situation especially for anyone supporting +multiple languages as APIs wouldn't bother explicitly supporting ``unicode`` +when they claimed text data support. + +To make the distinction between text and binary data clearer and more +pronounced, Python 3 did what most languages created in the age of the internet +have done and made text and binary data distinct types that cannot blindly be +mixed together (Python predates widespread access to the internet). For any code +that deals only with text or only binary data, this separation doesn't pose an +issue. But for code that has to deal with both, it does mean you might have to +now care about when you are using text compared to binary data, which is why +this cannot be entirely automated. + +To start, you will need to decide which APIs take text and which take binary +(it is **highly** recommended you don't design APIs that can take both due to +the difficulty of keeping the code working; as stated earlier it is difficult to +do well). In Python 2 this means making sure the APIs that take text can work +with ``unicode`` and those that work with binary data work with the +``bytes`` type from Python 3 (which is a subset of ``str`` in Python 2 and acts +as an alias for ``bytes`` type in Python 2). Usually the biggest issue is +realizing which methods exist on which types in Python 2 & 3 simultaneously +(for text that's ``unicode`` in Python 2 and ``str`` in Python 3, for binary +that's ``str``/``bytes`` in Python 2 and ``bytes`` in Python 3). The following +table lists the **unique** methods of each data type across Python 2 & 3 +(e.g., the ``decode()`` method is usable on the equivalent binary data type in +either Python 2 or 3, but it can't be used by the textual data type consistently +between Python 2 and 3 because ``str`` in Python 3 doesn't have the method). Do +note that as of Python 3.5 the ``__mod__`` method was added to the bytes type. + +======================== ===================== +**Text data** **Binary data** +------------------------ --------------------- +\ decode +------------------------ --------------------- +encode +------------------------ --------------------- +format +------------------------ --------------------- +isdecimal +------------------------ --------------------- +isnumeric +======================== ===================== + +Making the distinction easier to handle can be accomplished by encoding and +decoding between binary data and text at the edge of your code. This means that +when you receive text in binary data, you should immediately decode it. And if +your code needs to send text as binary data then encode it as late as possible. +This allows your code to work with only text internally and thus eliminates +having to keep track of what type of data you are working with. + +The next issue is making sure you know whether the string literals in your code +represent text or binary data. You should add a ``b`` prefix to any +literal that presents binary data. For text you should add a ``u`` prefix to +the text literal. (there is a :mod:`__future__` import to force all unspecified +literals to be Unicode, but usage has shown it isn't as effective as adding a +``b`` or ``u`` prefix to all literals explicitly) + +As part of this dichotomy you also need to be careful about opening files. +Unless you have been working on Windows, there is a chance you have not always +bothered to add the ``b`` mode when opening a binary file (e.g., ``rb`` for +binary reading). Under Python 3, binary files and text files are clearly +distinct and mutually incompatible; see the :mod:`io` module for details. +Therefore, you **must** make a decision of whether a file will be used for +binary access (allowing binary data to be read and/or written) or textual access +(allowing text data to be read and/or written). You should also use :func:`io.open` +for opening files instead of the built-in :func:`open` function as the :mod:`io` +module is consistent from Python 2 to 3 while the built-in :func:`open` function +is not (in Python 3 it's actually :func:`io.open`). Do not bother with the +outdated practice of using :func:`codecs.open` as that's only necessary for +keeping compatibility with Python 2.5. + +The constructors of both ``str`` and ``bytes`` have different semantics for the +same arguments between Python 2 & 3. Passing an integer to ``bytes`` in Python 2 +will give you the string representation of the integer: ``bytes(3) == '3'``. +But in Python 3, an integer argument to ``bytes`` will give you a bytes object +as long as the integer specified, filled with null bytes: +``bytes(3) == b'\x00\x00\x00'``. A similar worry is necessary when passing a +bytes object to ``str``. In Python 2 you just get the bytes object back: +``str(b'3') == b'3'``. But in Python 3 you get the string representation of the +bytes object: ``str(b'3') == "b'3'"``. + +Finally, the indexing of binary data requires careful handling (slicing does +**not** require any special handling). In Python 2, +``b'123'[1] == b'2'`` while in Python 3 ``b'123'[1] == 50``. Because binary data +is simply a collection of binary numbers, Python 3 returns the integer value for +the byte you index on. But in Python 2 because ``bytes == str``, indexing +returns a one-item slice of bytes. The six_ project has a function +named ``six.indexbytes()`` which will return an integer like in Python 3: +``six.indexbytes(b'123', 1)``. + +To summarize: + +#. Decide which of your APIs take text and which take binary data +#. Make sure that your code that works with text also works with ``unicode`` and + code for binary data works with ``bytes`` in Python 2 (see the table above + for what methods you cannot use for each type) +#. Mark all binary literals with a ``b`` prefix, textual literals with a ``u`` + prefix +#. Decode binary data to text as soon as possible, encode text as binary data as + late as possible +#. Open files using :func:`io.open` and make sure to specify the ``b`` mode when + appropriate +#. Be careful when indexing into binary data + + +Use feature detection instead of version detection +++++++++++++++++++++++++++++++++++++++++++++++++++ + +Inevitably you will have code that has to choose what to do based on what +version of Python is running. The best way to do this is with feature detection +of whether the version of Python you're running under supports what you need. +If for some reason that doesn't work then you should make the version check be +against Python 2 and not Python 3. To help explain this, let's look at an +example. + +Let's pretend that you need access to a feature of :mod:`importlib` that +is available in Python's standard library since Python 3.3 and available for +Python 2 through importlib2_ on PyPI. You might be tempted to write code to +access e.g. the :mod:`importlib.abc` module by doing the following:: + + import sys + + if sys.version_info[0] == 3: + from importlib import abc + else: + from importlib2 import abc + +The problem with this code is what happens when Python 4 comes out? It would +be better to treat Python 2 as the exceptional case instead of Python 3 and +assume that future Python versions will be more compatible with Python 3 than +Python 2:: + + import sys + + if sys.version_info[0] > 2: + from importlib import abc + else: + from importlib2 import abc + +The best solution, though, is to do no version detection at all and instead rely +on feature detection. That avoids any potential issues of getting the version +detection wrong and helps keep you future-compatible:: + + try: + from importlib import abc + except ImportError: + from importlib2 import abc + + +Prevent compatibility regressions +--------------------------------- + +Once you have fully translated your code to be compatible with Python 3, you +will want to make sure your code doesn't regress and stop working under +Python 3. This is especially true if you have a dependency which is blocking you +from actually running under Python 3 at the moment. + +To help with staying compatible, any new modules you create should have +at least the following block of code at the top of it:: + + from __future__ import absolute_import + from __future__ import division + from __future__ import print_function + +You can also run Python 2 with the ``-3`` flag to be warned about various +compatibility issues your code triggers during execution. If you turn warnings +into errors with ``-Werror`` then you can make sure that you don't accidentally +miss a warning. + +You can also use the Pylint_ project and its ``--py3k`` flag to lint your code +to receive warnings when your code begins to deviate from Python 3 +compatibility. This also prevents you from having to run Modernize_ or Futurize_ +over your code regularly to catch compatibility regressions. This does require +you only support Python 2.7 and Python 3.4 or newer as that is Pylint's +minimum Python version support. + + +Check which dependencies block your transition +---------------------------------------------- + +**After** you have made your code compatible with Python 3 you should begin to +care about whether your dependencies have also been ported. The caniusepython3_ +project was created to help you determine which projects +-- directly or indirectly -- are blocking you from supporting Python 3. There +is both a command-line tool as well as a web interface at +https://caniusepython3.com. + +The project also provides code which you can integrate into your test suite so +that you will have a failing test when you no longer have dependencies blocking +you from using Python 3. This allows you to avoid having to manually check your +dependencies and to be notified quickly when you can start running on Python 3. + + +Update your ``setup.py`` file to denote Python 3 compatibility +-------------------------------------------------------------- + +Once your code works under Python 3, you should update the classifiers in +your ``setup.py`` to contain ``Programming Language :: Python :: 3`` and to not +specify sole Python 2 support. This will tell anyone using your code that you +support Python 2 **and** 3. Ideally you will also want to add classifiers for +each major/minor version of Python you now support. + + +Use continuous integration to stay compatible +--------------------------------------------- + +Once you are able to fully run under Python 3 you will want to make sure your +code always works under both Python 2 & 3. Probably the best tool for running +your tests under multiple Python interpreters is tox_. You can then integrate +tox with your continuous integration system so that you never accidentally break +Python 2 or 3 support. + +You may also want to use the ``-bb`` flag with the Python 3 interpreter to +trigger an exception when you are comparing bytes to strings or bytes to an int +(the latter is available starting in Python 3.5). By default type-differing +comparisons simply return ``False``, but if you made a mistake in your +separation of text/binary data handling or indexing on bytes you wouldn't easily +find the mistake. This flag will raise an exception when these kinds of +comparisons occur, making the mistake much easier to track down. + +And that's mostly it! At this point your code base is compatible with both +Python 2 and 3 simultaneously. Your testing will also be set up so that you +don't accidentally break Python 2 or 3 compatibility regardless of which version +you typically run your tests under while developing. + + +Consider using optional static type checking +-------------------------------------------- + +Another way to help port your code is to use a static type checker like +mypy_ or pytype_ on your code. These tools can be used to analyze your code as +if it's being run under Python 2, then you can run the tool a second time as if +your code is running under Python 3. By running a static type checker twice like +this you can discover if you're e.g. misusing binary data type in one version +of Python compared to another. If you add optional type hints to your code you +can also explicitly state whether your APIs use textual or binary data, helping +to make sure everything functions as expected in both versions of Python. + + +.. _caniusepython3: https://pypi.org/project/caniusepython3 +.. _cheat sheet: http://python-future.org/compatible_idioms.html +.. _coverage.py: https://pypi.org/project/coverage +.. _Futurize: http://python-future.org/automatic_conversion.html +.. _importlib2: https://pypi.org/project/importlib2 +.. _Modernize: https://python-modernize.readthedocs.io/ +.. _mypy: http://mypy-lang.org/ +.. _Porting to Python 3: http://python3porting.com/ +.. _Pylint: https://pypi.org/project/pylint + +.. _Python 3 Q & A: https://ncoghlan-devs-python-notes.readthedocs.io/en/latest/python3/questions_and_answers.html + +.. _pytype: https://github.com/google/pytype +.. _python-future: http://python-future.org/ +.. _python-porting: https://mail.python.org/mailman/listinfo/python-porting +.. _six: https://pypi.org/project/six +.. _tox: https://pypi.org/project/tox +.. _trove classifier: https://pypi.org/classifiers + +.. _Why Python 3 exists: https://snarky.ca/why-python-3-exists diff --git a/cpython_2/environment/repo/Doc/howto/regex.rst b/cpython_2/environment/repo/Doc/howto/regex.rst new file mode 100644 index 0000000000000000000000000000000000000000..d574c3736b1cb78348dade8e1cd36f613d6789f7 --- /dev/null +++ b/cpython_2/environment/repo/Doc/howto/regex.rst @@ -0,0 +1,1393 @@ +.. _regex-howto: + +**************************** + Regular Expression HOWTO +**************************** + +:Author: A.M. Kuchling <amk@amk.ca> + +.. TODO: + Document lookbehind assertions + Better way of displaying a RE, a string, and what it matches + Mention optional argument to match.groups() + Unicode (at least a reference) + + +.. topic:: Abstract + + This document is an introductory tutorial to using regular expressions in Python + with the :mod:`re` module. It provides a gentler introduction than the + corresponding section in the Library Reference. + + +Introduction +============ + +Regular expressions (called REs, or regexes, or regex patterns) are essentially +a tiny, highly specialized programming language embedded inside Python and made +available through the :mod:`re` module. Using this little language, you specify +the rules for the set of possible strings that you want to match; this set might +contain English sentences, or e-mail addresses, or TeX commands, or anything you +like. You can then ask questions such as "Does this string match the pattern?", +or "Is there a match for the pattern anywhere in this string?". You can also +use REs to modify a string or to split it apart in various ways. + +Regular expression patterns are compiled into a series of bytecodes which are +then executed by a matching engine written in C. For advanced use, it may be +necessary to pay careful attention to how the engine will execute a given RE, +and write the RE in a certain way in order to produce bytecode that runs faster. +Optimization isn't covered in this document, because it requires that you have a +good understanding of the matching engine's internals. + +The regular expression language is relatively small and restricted, so not all +possible string processing tasks can be done using regular expressions. There +are also tasks that *can* be done with regular expressions, but the expressions +turn out to be very complicated. In these cases, you may be better off writing +Python code to do the processing; while Python code will be slower than an +elaborate regular expression, it will also probably be more understandable. + + +Simple Patterns +=============== + +We'll start by learning about the simplest possible regular expressions. Since +regular expressions are used to operate on strings, we'll begin with the most +common task: matching characters. + +For a detailed explanation of the computer science underlying regular +expressions (deterministic and non-deterministic finite automata), you can refer +to almost any textbook on writing compilers. + + +Matching Characters +------------------- + +Most letters and characters will simply match themselves. For example, the +regular expression ``test`` will match the string ``test`` exactly. (You can +enable a case-insensitive mode that would let this RE match ``Test`` or ``TEST`` +as well; more about this later.) + +There are exceptions to this rule; some characters are special +:dfn:`metacharacters`, and don't match themselves. Instead, they signal that +some out-of-the-ordinary thing should be matched, or they affect other portions +of the RE by repeating them or changing their meaning. Much of this document is +devoted to discussing various metacharacters and what they do. + +Here's a complete list of the metacharacters; their meanings will be discussed +in the rest of this HOWTO. + +.. code-block:: none + + . ^ $ * + ? { } [ ] \ | ( ) + +The first metacharacters we'll look at are ``[`` and ``]``. They're used for +specifying a character class, which is a set of characters that you wish to +match. Characters can be listed individually, or a range of characters can be +indicated by giving two characters and separating them by a ``'-'``. For +example, ``[abc]`` will match any of the characters ``a``, ``b``, or ``c``; this +is the same as ``[a-c]``, which uses a range to express the same set of +characters. If you wanted to match only lowercase letters, your RE would be +``[a-z]``. + +Metacharacters are not active inside classes. For example, ``[akm$]`` will +match any of the characters ``'a'``, ``'k'``, ``'m'``, or ``'$'``; ``'$'`` is +usually a metacharacter, but inside a character class it's stripped of its +special nature. + +You can match the characters not listed within the class by :dfn:`complementing` +the set. This is indicated by including a ``'^'`` as the first character of the +class. For example, ``[^5]`` will match any character except ``'5'``. If the +caret appears elsewhere in a character class, it does not have special meaning. +For example: ``[5^]`` will match either a ``'5'`` or a ``'^'``. + +Perhaps the most important metacharacter is the backslash, ``\``. As in Python +string literals, the backslash can be followed by various characters to signal +various special sequences. It's also used to escape all the metacharacters so +you can still match them in patterns; for example, if you need to match a ``[`` +or ``\``, you can precede them with a backslash to remove their special +meaning: ``\[`` or ``\\``. + +Some of the special sequences beginning with ``'\'`` represent +predefined sets of characters that are often useful, such as the set +of digits, the set of letters, or the set of anything that isn't +whitespace. + +Let's take an example: ``\w`` matches any alphanumeric character. If +the regex pattern is expressed in bytes, this is equivalent to the +class ``[a-zA-Z0-9_]``. If the regex pattern is a string, ``\w`` will +match all the characters marked as letters in the Unicode database +provided by the :mod:`unicodedata` module. You can use the more +restricted definition of ``\w`` in a string pattern by supplying the +:const:`re.ASCII` flag when compiling the regular expression. + +The following list of special sequences isn't complete. For a complete +list of sequences and expanded class definitions for Unicode string +patterns, see the last part of :ref:`Regular Expression Syntax +<re-syntax>` in the Standard Library reference. In general, the +Unicode versions match any character that's in the appropriate +category in the Unicode database. + +``\d`` + Matches any decimal digit; this is equivalent to the class ``[0-9]``. + +``\D`` + Matches any non-digit character; this is equivalent to the class ``[^0-9]``. + +``\s`` + Matches any whitespace character; this is equivalent to the class ``[ + \t\n\r\f\v]``. + +``\S`` + Matches any non-whitespace character; this is equivalent to the class ``[^ + \t\n\r\f\v]``. + +``\w`` + Matches any alphanumeric character; this is equivalent to the class + ``[a-zA-Z0-9_]``. + +``\W`` + Matches any non-alphanumeric character; this is equivalent to the class + ``[^a-zA-Z0-9_]``. + +These sequences can be included inside a character class. For example, +``[\s,.]`` is a character class that will match any whitespace character, or +``','`` or ``'.'``. + +The final metacharacter in this section is ``.``. It matches anything except a +newline character, and there's an alternate mode (:const:`re.DOTALL`) where it will +match even a newline. ``.`` is often used where you want to match "any +character". + + +Repeating Things +---------------- + +Being able to match varying sets of characters is the first thing regular +expressions can do that isn't already possible with the methods available on +strings. However, if that was the only additional capability of regexes, they +wouldn't be much of an advance. Another capability is that you can specify that +portions of the RE must be repeated a certain number of times. + +The first metacharacter for repeating things that we'll look at is ``*``. ``*`` +doesn't match the literal character ``'*'``; instead, it specifies that the +previous character can be matched zero or more times, instead of exactly once. + +For example, ``ca*t`` will match ``'ct'`` (0 ``'a'`` characters), ``'cat'`` (1 ``'a'``), +``'caaat'`` (3 ``'a'`` characters), and so forth. + +Repetitions such as ``*`` are :dfn:`greedy`; when repeating a RE, the matching +engine will try to repeat it as many times as possible. If later portions of the +pattern don't match, the matching engine will then back up and try again with +fewer repetitions. + +A step-by-step example will make this more obvious. Let's consider the +expression ``a[bcd]*b``. This matches the letter ``'a'``, zero or more letters +from the class ``[bcd]``, and finally ends with a ``'b'``. Now imagine matching +this RE against the string ``'abcbd'``. + ++------+-----------+---------------------------------+ +| Step | Matched | Explanation | ++======+===========+=================================+ +| 1 | ``a`` | The ``a`` in the RE matches. | ++------+-----------+---------------------------------+ +| 2 | ``abcbd`` | The engine matches ``[bcd]*``, | +| | | going as far as it can, which | +| | | is to the end of the string. | ++------+-----------+---------------------------------+ +| 3 | *Failure* | The engine tries to match | +| | | ``b``, but the current position | +| | | is at the end of the string, so | +| | | it fails. | ++------+-----------+---------------------------------+ +| 4 | ``abcb`` | Back up, so that ``[bcd]*`` | +| | | matches one less character. | ++------+-----------+---------------------------------+ +| 5 | *Failure* | Try ``b`` again, but the | +| | | current position is at the last | +| | | character, which is a ``'d'``. | ++------+-----------+---------------------------------+ +| 6 | ``abc`` | Back up again, so that | +| | | ``[bcd]*`` is only matching | +| | | ``bc``. | ++------+-----------+---------------------------------+ +| 6 | ``abcb`` | Try ``b`` again. This time | +| | | the character at the | +| | | current position is ``'b'``, so | +| | | it succeeds. | ++------+-----------+---------------------------------+ + +The end of the RE has now been reached, and it has matched ``'abcb'``. This +demonstrates how the matching engine goes as far as it can at first, and if no +match is found it will then progressively back up and retry the rest of the RE +again and again. It will back up until it has tried zero matches for +``[bcd]*``, and if that subsequently fails, the engine will conclude that the +string doesn't match the RE at all. + +Another repeating metacharacter is ``+``, which matches one or more times. Pay +careful attention to the difference between ``*`` and ``+``; ``*`` matches +*zero* or more times, so whatever's being repeated may not be present at all, +while ``+`` requires at least *one* occurrence. To use a similar example, +``ca+t`` will match ``'cat'`` (1 ``'a'``), ``'caaat'`` (3 ``'a'``\ s), but won't +match ``'ct'``. + +There are two more repeating qualifiers. The question mark character, ``?``, +matches either once or zero times; you can think of it as marking something as +being optional. For example, ``home-?brew`` matches either ``'homebrew'`` or +``'home-brew'``. + +The most complicated repeated qualifier is ``{m,n}``, where *m* and *n* are +decimal integers. This qualifier means there must be at least *m* repetitions, +and at most *n*. For example, ``a/{1,3}b`` will match ``'a/b'``, ``'a//b'``, and +``'a///b'``. It won't match ``'ab'``, which has no slashes, or ``'a////b'``, which +has four. + +You can omit either *m* or *n*; in that case, a reasonable value is assumed for +the missing value. Omitting *m* is interpreted as a lower limit of 0, while +omitting *n* results in an upper bound of infinity. + +Readers of a reductionist bent may notice that the three other qualifiers can +all be expressed using this notation. ``{0,}`` is the same as ``*``, ``{1,}`` +is equivalent to ``+``, and ``{0,1}`` is the same as ``?``. It's better to use +``*``, ``+``, or ``?`` when you can, simply because they're shorter and easier +to read. + + +Using Regular Expressions +========================= + +Now that we've looked at some simple regular expressions, how do we actually use +them in Python? The :mod:`re` module provides an interface to the regular +expression engine, allowing you to compile REs into objects and then perform +matches with them. + + +Compiling Regular Expressions +----------------------------- + +Regular expressions are compiled into pattern objects, which have +methods for various operations such as searching for pattern matches or +performing string substitutions. :: + + >>> import re + >>> p = re.compile('ab*') + >>> p + re.compile('ab*') + +:func:`re.compile` also accepts an optional *flags* argument, used to enable +various special features and syntax variations. We'll go over the available +settings later, but for now a single example will do:: + + >>> p = re.compile('ab*', re.IGNORECASE) + +The RE is passed to :func:`re.compile` as a string. REs are handled as strings +because regular expressions aren't part of the core Python language, and no +special syntax was created for expressing them. (There are applications that +don't need REs at all, so there's no need to bloat the language specification by +including them.) Instead, the :mod:`re` module is simply a C extension module +included with Python, just like the :mod:`socket` or :mod:`zlib` modules. + +Putting REs in strings keeps the Python language simpler, but has one +disadvantage which is the topic of the next section. + + +.. _the-backslash-plague: + +The Backslash Plague +-------------------- + +As stated earlier, regular expressions use the backslash character (``'\'``) to +indicate special forms or to allow special characters to be used without +invoking their special meaning. This conflicts with Python's usage of the same +character for the same purpose in string literals. + +Let's say you want to write a RE that matches the string ``\section``, which +might be found in a LaTeX file. To figure out what to write in the program +code, start with the desired string to be matched. Next, you must escape any +backslashes and other metacharacters by preceding them with a backslash, +resulting in the string ``\\section``. The resulting string that must be passed +to :func:`re.compile` must be ``\\section``. However, to express this as a +Python string literal, both backslashes must be escaped *again*. + ++-------------------+------------------------------------------+ +| Characters | Stage | ++===================+==========================================+ +| ``\section`` | Text string to be matched | ++-------------------+------------------------------------------+ +| ``\\section`` | Escaped backslash for :func:`re.compile` | ++-------------------+------------------------------------------+ +| ``"\\\\section"`` | Escaped backslashes for a string literal | ++-------------------+------------------------------------------+ + +In short, to match a literal backslash, one has to write ``'\\\\'`` as the RE +string, because the regular expression must be ``\\``, and each backslash must +be expressed as ``\\`` inside a regular Python string literal. In REs that +feature backslashes repeatedly, this leads to lots of repeated backslashes and +makes the resulting strings difficult to understand. + +The solution is to use Python's raw string notation for regular expressions; +backslashes are not handled in any special way in a string literal prefixed with +``'r'``, so ``r"\n"`` is a two-character string containing ``'\'`` and ``'n'``, +while ``"\n"`` is a one-character string containing a newline. Regular +expressions will often be written in Python code using this raw string notation. + +In addition, special escape sequences that are valid in regular expressions, +but not valid as Python string literals, now result in a +:exc:`DeprecationWarning` and will eventually become a :exc:`SyntaxError`, +which means the sequences will be invalid if raw string notation or escaping +the backslashes isn't used. + + ++-------------------+------------------+ +| Regular String | Raw string | ++===================+==================+ +| ``"ab*"`` | ``r"ab*"`` | ++-------------------+------------------+ +| ``"\\\\section"`` | ``r"\\section"`` | ++-------------------+------------------+ +| ``"\\w+\\s+\\1"`` | ``r"\w+\s+\1"`` | ++-------------------+------------------+ + + +Performing Matches +------------------ + +Once you have an object representing a compiled regular expression, what do you +do with it? Pattern objects have several methods and attributes. +Only the most significant ones will be covered here; consult the :mod:`re` docs +for a complete listing. + ++------------------+-----------------------------------------------+ +| Method/Attribute | Purpose | ++==================+===============================================+ +| ``match()`` | Determine if the RE matches at the beginning | +| | of the string. | ++------------------+-----------------------------------------------+ +| ``search()`` | Scan through a string, looking for any | +| | location where this RE matches. | ++------------------+-----------------------------------------------+ +| ``findall()`` | Find all substrings where the RE matches, and | +| | returns them as a list. | ++------------------+-----------------------------------------------+ +| ``finditer()`` | Find all substrings where the RE matches, and | +| | returns them as an :term:`iterator`. | ++------------------+-----------------------------------------------+ + +:meth:`~re.Pattern.match` and :meth:`~re.Pattern.search` return ``None`` if no match can be found. If +they're successful, a :ref:`match object <match-objects>` instance is returned, +containing information about the match: where it starts and ends, the substring +it matched, and more. + +You can learn about this by interactively experimenting with the :mod:`re` +module. If you have :mod:`tkinter` available, you may also want to look at +:source:`Tools/demo/redemo.py`, a demonstration program included with the +Python distribution. It allows you to enter REs and strings, and displays +whether the RE matches or fails. :file:`redemo.py` can be quite useful when +trying to debug a complicated RE. + +This HOWTO uses the standard Python interpreter for its examples. First, run the +Python interpreter, import the :mod:`re` module, and compile a RE:: + + >>> import re + >>> p = re.compile('[a-z]+') + >>> p + re.compile('[a-z]+') + +Now, you can try matching various strings against the RE ``[a-z]+``. An empty +string shouldn't match at all, since ``+`` means 'one or more repetitions'. +:meth:`~re.Pattern.match` should return ``None`` in this case, which will cause the +interpreter to print no output. You can explicitly print the result of +:meth:`!match` to make this clear. :: + + >>> p.match("") + >>> print(p.match("")) + None + +Now, let's try it on a string that it should match, such as ``tempo``. In this +case, :meth:`~re.Pattern.match` will return a :ref:`match object <match-objects>`, so you +should store the result in a variable for later use. :: + + >>> m = p.match('tempo') + >>> m + <re.Match object; span=(0, 5), match='tempo'> + +Now you can query the :ref:`match object <match-objects>` for information +about the matching string. Match object instances +also have several methods and attributes; the most important ones are: + ++------------------+--------------------------------------------+ +| Method/Attribute | Purpose | ++==================+============================================+ +| ``group()`` | Return the string matched by the RE | ++------------------+--------------------------------------------+ +| ``start()`` | Return the starting position of the match | ++------------------+--------------------------------------------+ +| ``end()`` | Return the ending position of the match | ++------------------+--------------------------------------------+ +| ``span()`` | Return a tuple containing the (start, end) | +| | positions of the match | ++------------------+--------------------------------------------+ + +Trying these methods will soon clarify their meaning:: + + >>> m.group() + 'tempo' + >>> m.start(), m.end() + (0, 5) + >>> m.span() + (0, 5) + +:meth:`~re.Match.group` returns the substring that was matched by the RE. :meth:`~re.Match.start` +and :meth:`~re.Match.end` return the starting and ending index of the match. :meth:`~re.Match.span` +returns both start and end indexes in a single tuple. Since the :meth:`~re.Pattern.match` +method only checks if the RE matches at the start of a string, :meth:`!start` +will always be zero. However, the :meth:`~re.Pattern.search` method of patterns +scans through the string, so the match may not start at zero in that +case. :: + + >>> print(p.match('::: message')) + None + >>> m = p.search('::: message'); print(m) + <re.Match object; span=(4, 11), match='message'> + >>> m.group() + 'message' + >>> m.span() + (4, 11) + +In actual programs, the most common style is to store the +:ref:`match object <match-objects>` in a variable, and then check if it was +``None``. This usually looks like:: + + p = re.compile( ... ) + m = p.match( 'string goes here' ) + if m: + print('Match found: ', m.group()) + else: + print('No match') + +Two pattern methods return all of the matches for a pattern. +:meth:`~re.Pattern.findall` returns a list of matching strings:: + + >>> p = re.compile(r'\d+') + >>> p.findall('12 drummers drumming, 11 pipers piping, 10 lords a-leaping') + ['12', '11', '10'] + +The ``r`` prefix, making the literal a raw string literal, is needed in this +example because escape sequences in a normal "cooked" string literal that are +not recognized by Python, as opposed to regular expressions, now result in a +:exc:`DeprecationWarning` and will eventually become a :exc:`SyntaxError`. See +:ref:`the-backslash-plague`. + +:meth:`~re.Pattern.findall` has to create the entire list before it can be returned as the +result. The :meth:`~re.Pattern.finditer` method returns a sequence of +:ref:`match object <match-objects>` instances as an :term:`iterator`:: + + >>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...') + >>> iterator #doctest: +ELLIPSIS + <callable_iterator object at 0x...> + >>> for match in iterator: + ... print(match.span()) + ... + (0, 2) + (22, 24) + (29, 31) + + +Module-Level Functions +---------------------- + +You don't have to create a pattern object and call its methods; the +:mod:`re` module also provides top-level functions called :func:`~re.match`, +:func:`~re.search`, :func:`~re.findall`, :func:`~re.sub`, and so forth. These functions +take the same arguments as the corresponding pattern method with +the RE string added as the first argument, and still return either ``None`` or a +:ref:`match object <match-objects>` instance. :: + + >>> print(re.match(r'From\s+', 'Fromage amk')) + None + >>> re.match(r'From\s+', 'From amk Thu May 14 19:12:10 1998') #doctest: +ELLIPSIS + <re.Match object; span=(0, 5), match='From '> + +Under the hood, these functions simply create a pattern object for you +and call the appropriate method on it. They also store the compiled +object in a cache, so future calls using the same RE won't need to +parse the pattern again and again. + +Should you use these module-level functions, or should you get the +pattern and call its methods yourself? If you're accessing a regex +within a loop, pre-compiling it will save a few function calls. +Outside of loops, there's not much difference thanks to the internal +cache. + + +Compilation Flags +----------------- + +Compilation flags let you modify some aspects of how regular expressions work. +Flags are available in the :mod:`re` module under two names, a long name such as +:const:`IGNORECASE` and a short, one-letter form such as :const:`I`. (If you're +familiar with Perl's pattern modifiers, the one-letter forms use the same +letters; the short form of :const:`re.VERBOSE` is :const:`re.X`, for example.) +Multiple flags can be specified by bitwise OR-ing them; ``re.I | re.M`` sets +both the :const:`I` and :const:`M` flags, for example. + +Here's a table of the available flags, followed by a more detailed explanation +of each one. + ++---------------------------------+--------------------------------------------+ +| Flag | Meaning | ++=================================+============================================+ +| :const:`ASCII`, :const:`A` | Makes several escapes like ``\w``, ``\b``, | +| | ``\s`` and ``\d`` match only on ASCII | +| | characters with the respective property. | ++---------------------------------+--------------------------------------------+ +| :const:`DOTALL`, :const:`S` | Make ``.`` match any character, including | +| | newlines. | ++---------------------------------+--------------------------------------------+ +| :const:`IGNORECASE`, :const:`I` | Do case-insensitive matches. | ++---------------------------------+--------------------------------------------+ +| :const:`LOCALE`, :const:`L` | Do a locale-aware match. | ++---------------------------------+--------------------------------------------+ +| :const:`MULTILINE`, :const:`M` | Multi-line matching, affecting ``^`` and | +| | ``$``. | ++---------------------------------+--------------------------------------------+ +| :const:`VERBOSE`, :const:`X` | Enable verbose REs, which can be organized | +| (for 'extended') | more cleanly and understandably. | ++---------------------------------+--------------------------------------------+ + + +.. data:: I + IGNORECASE + :noindex: + + Perform case-insensitive matching; character class and literal strings will + match letters by ignoring case. For example, ``[A-Z]`` will match lowercase + letters, too. Full Unicode matching also works unless the :const:`ASCII` + flag is used to disable non-ASCII matches. When the Unicode patterns + ``[a-z]`` or ``[A-Z]`` are used in combination with the :const:`IGNORECASE` + flag, they will match the 52 ASCII letters and 4 additional non-ASCII + letters: 'İ' (U+0130, Latin capital letter I with dot above), 'ı' (U+0131, + Latin small letter dotless i), 'ſ' (U+017F, Latin small letter long s) and + 'K' (U+212A, Kelvin sign). ``Spam`` will match ``'Spam'``, ``'spam'``, + ``'spAM'``, or ``'ſpam'`` (the latter is matched only in Unicode mode). + This lowercasing doesn't take the current locale into account; + it will if you also set the :const:`LOCALE` flag. + + +.. data:: L + LOCALE + :noindex: + + Make ``\w``, ``\W``, ``\b``, ``\B`` and case-insensitive matching dependent + on the current locale instead of the Unicode database. + + Locales are a feature of the C library intended to help in writing programs + that take account of language differences. For example, if you're + processing encoded French text, you'd want to be able to write ``\w+`` to + match words, but ``\w`` only matches the character class ``[A-Za-z]`` in + bytes patterns; it won't match bytes corresponding to ``é`` or ``ç``. + If your system is configured properly and a French locale is selected, + certain C functions will tell the program that the byte corresponding to + ``é`` should also be considered a letter. + Setting the :const:`LOCALE` flag when compiling a regular expression will cause + the resulting compiled object to use these C functions for ``\w``; this is + slower, but also enables ``\w+`` to match French words as you'd expect. + The use of this flag is discouraged in Python 3 as the locale mechanism + is very unreliable, it only handles one "culture" at a time, and it only + works with 8-bit locales. Unicode matching is already enabled by default + in Python 3 for Unicode (str) patterns, and it is able to handle different + locales/languages. + + +.. data:: M + MULTILINE + :noindex: + + (``^`` and ``$`` haven't been explained yet; they'll be introduced in section + :ref:`more-metacharacters`.) + + Usually ``^`` matches only at the beginning of the string, and ``$`` matches + only at the end of the string and immediately before the newline (if any) at the + end of the string. When this flag is specified, ``^`` matches at the beginning + of the string and at the beginning of each line within the string, immediately + following each newline. Similarly, the ``$`` metacharacter matches either at + the end of the string and at the end of each line (immediately preceding each + newline). + + +.. data:: S + DOTALL + :noindex: + + Makes the ``'.'`` special character match any character at all, including a + newline; without this flag, ``'.'`` will match anything *except* a newline. + + +.. data:: A + ASCII + :noindex: + + Make ``\w``, ``\W``, ``\b``, ``\B``, ``\s`` and ``\S`` perform ASCII-only + matching instead of full Unicode matching. This is only meaningful for + Unicode patterns, and is ignored for byte patterns. + + +.. data:: X + VERBOSE + :noindex: + + This flag allows you to write regular expressions that are more readable by + granting you more flexibility in how you can format them. When this flag has + been specified, whitespace within the RE string is ignored, except when the + whitespace is in a character class or preceded by an unescaped backslash; this + lets you organize and indent the RE more clearly. This flag also lets you put + comments within a RE that will be ignored by the engine; comments are marked by + a ``'#'`` that's neither in a character class or preceded by an unescaped + backslash. + + For example, here's a RE that uses :const:`re.VERBOSE`; see how much easier it + is to read? :: + + charref = re.compile(r""" + &[#] # Start of a numeric entity reference + ( + 0[0-7]+ # Octal form + | [0-9]+ # Decimal form + | x[0-9a-fA-F]+ # Hexadecimal form + ) + ; # Trailing semicolon + """, re.VERBOSE) + + Without the verbose setting, the RE would look like this:: + + charref = re.compile("&#(0[0-7]+" + "|[0-9]+" + "|x[0-9a-fA-F]+);") + + In the above example, Python's automatic concatenation of string literals has + been used to break up the RE into smaller pieces, but it's still more difficult + to understand than the version using :const:`re.VERBOSE`. + + +More Pattern Power +================== + +So far we've only covered a part of the features of regular expressions. In +this section, we'll cover some new metacharacters, and how to use groups to +retrieve portions of the text that was matched. + + +.. _more-metacharacters: + +More Metacharacters +------------------- + +There are some metacharacters that we haven't covered yet. Most of them will be +covered in this section. + +Some of the remaining metacharacters to be discussed are :dfn:`zero-width +assertions`. They don't cause the engine to advance through the string; +instead, they consume no characters at all, and simply succeed or fail. For +example, ``\b`` is an assertion that the current position is located at a word +boundary; the position isn't changed by the ``\b`` at all. This means that +zero-width assertions should never be repeated, because if they match once at a +given location, they can obviously be matched an infinite number of times. + +``|`` + Alternation, or the "or" operator. If *A* and *B* are regular expressions, + ``A|B`` will match any string that matches either *A* or *B*. ``|`` has very + low precedence in order to make it work reasonably when you're alternating + multi-character strings. ``Crow|Servo`` will match either ``'Crow'`` or ``'Servo'``, + not ``'Cro'``, a ``'w'`` or an ``'S'``, and ``'ervo'``. + + To match a literal ``'|'``, use ``\|``, or enclose it inside a character class, + as in ``[|]``. + +``^`` + Matches at the beginning of lines. Unless the :const:`MULTILINE` flag has been + set, this will only match at the beginning of the string. In :const:`MULTILINE` + mode, this also matches immediately after each newline within the string. + + For example, if you wish to match the word ``From`` only at the beginning of a + line, the RE to use is ``^From``. :: + + >>> print(re.search('^From', 'From Here to Eternity')) #doctest: +ELLIPSIS + <re.Match object; span=(0, 4), match='From'> + >>> print(re.search('^From', 'Reciting From Memory')) + None + + To match a literal ``'^'``, use ``\^``. + +``$`` + Matches at the end of a line, which is defined as either the end of the string, + or any location followed by a newline character. :: + + >>> print(re.search('}$', '{block}')) #doctest: +ELLIPSIS + <re.Match object; span=(6, 7), match='}'> + >>> print(re.search('}$', '{block} ')) + None + >>> print(re.search('}$', '{block}\n')) #doctest: +ELLIPSIS + <re.Match object; span=(6, 7), match='}'> + + To match a literal ``'$'``, use ``\$`` or enclose it inside a character class, + as in ``[$]``. + +``\A`` + Matches only at the start of the string. When not in :const:`MULTILINE` mode, + ``\A`` and ``^`` are effectively the same. In :const:`MULTILINE` mode, they're + different: ``\A`` still matches only at the beginning of the string, but ``^`` + may match at any location inside the string that follows a newline character. + +``\Z`` + Matches only at the end of the string. + +``\b`` + Word boundary. This is a zero-width assertion that matches only at the + beginning or end of a word. A word is defined as a sequence of alphanumeric + characters, so the end of a word is indicated by whitespace or a + non-alphanumeric character. + + The following example matches ``class`` only when it's a complete word; it won't + match when it's contained inside another word. :: + + >>> p = re.compile(r'\bclass\b') + >>> print(p.search('no class at all')) + <re.Match object; span=(3, 8), match='class'> + >>> print(p.search('the declassified algorithm')) + None + >>> print(p.search('one subclass is')) + None + + There are two subtleties you should remember when using this special sequence. + First, this is the worst collision between Python's string literals and regular + expression sequences. In Python's string literals, ``\b`` is the backspace + character, ASCII value 8. If you're not using raw strings, then Python will + convert the ``\b`` to a backspace, and your RE won't match as you expect it to. + The following example looks the same as our previous RE, but omits the ``'r'`` + in front of the RE string. :: + + >>> p = re.compile('\bclass\b') + >>> print(p.search('no class at all')) + None + >>> print(p.search('\b' + 'class' + '\b')) + <re.Match object; span=(0, 7), match='\x08class\x08'> + + Second, inside a character class, where there's no use for this assertion, + ``\b`` represents the backspace character, for compatibility with Python's + string literals. + +``\B`` + Another zero-width assertion, this is the opposite of ``\b``, only matching when + the current position is not at a word boundary. + + +Grouping +-------- + +Frequently you need to obtain more information than just whether the RE matched +or not. Regular expressions are often used to dissect strings by writing a RE +divided into several subgroups which match different components of interest. +For example, an RFC-822 header line is divided into a header name and a value, +separated by a ``':'``, like this: + +.. code-block:: none + + From: author@example.com + User-Agent: Thunderbird 1.5.0.9 (X11/20061227) + MIME-Version: 1.0 + To: editor@example.com + +This can be handled by writing a regular expression which matches an entire +header line, and has one group which matches the header name, and another group +which matches the header's value. + +Groups are marked by the ``'('``, ``')'`` metacharacters. ``'('`` and ``')'`` +have much the same meaning as they do in mathematical expressions; they group +together the expressions contained inside them, and you can repeat the contents +of a group with a repeating qualifier, such as ``*``, ``+``, ``?``, or +``{m,n}``. For example, ``(ab)*`` will match zero or more repetitions of +``ab``. :: + + >>> p = re.compile('(ab)*') + >>> print(p.match('ababababab').span()) + (0, 10) + +Groups indicated with ``'('``, ``')'`` also capture the starting and ending +index of the text that they match; this can be retrieved by passing an argument +to :meth:`~re.Match.group`, :meth:`~re.Match.start`, :meth:`~re.Match.end`, and +:meth:`~re.Match.span`. Groups are +numbered starting with 0. Group 0 is always present; it's the whole RE, so +:ref:`match object <match-objects>` methods all have group 0 as their default +argument. Later we'll see how to express groups that don't capture the span +of text that they match. :: + + >>> p = re.compile('(a)b') + >>> m = p.match('ab') + >>> m.group() + 'ab' + >>> m.group(0) + 'ab' + +Subgroups are numbered from left to right, from 1 upward. Groups can be nested; +to determine the number, just count the opening parenthesis characters, going +from left to right. :: + + >>> p = re.compile('(a(b)c)d') + >>> m = p.match('abcd') + >>> m.group(0) + 'abcd' + >>> m.group(1) + 'abc' + >>> m.group(2) + 'b' + +:meth:`~re.Match.group` can be passed multiple group numbers at a time, in which case it +will return a tuple containing the corresponding values for those groups. :: + + >>> m.group(2,1,2) + ('b', 'abc', 'b') + +The :meth:`~re.Match.groups` method returns a tuple containing the strings for all the +subgroups, from 1 up to however many there are. :: + + >>> m.groups() + ('abc', 'b') + +Backreferences in a pattern allow you to specify that the contents of an earlier +capturing group must also be found at the current location in the string. For +example, ``\1`` will succeed if the exact contents of group 1 can be found at +the current position, and fails otherwise. Remember that Python's string +literals also use a backslash followed by numbers to allow including arbitrary +characters in a string, so be sure to use a raw string when incorporating +backreferences in a RE. + +For example, the following RE detects doubled words in a string. :: + + >>> p = re.compile(r'\b(\w+)\s+\1\b') + >>> p.search('Paris in the the spring').group() + 'the the' + +Backreferences like this aren't often useful for just searching through a string +--- there are few text formats which repeat data in this way --- but you'll soon +find out that they're *very* useful when performing string substitutions. + + +Non-capturing and Named Groups +------------------------------ + +Elaborate REs may use many groups, both to capture substrings of interest, and +to group and structure the RE itself. In complex REs, it becomes difficult to +keep track of the group numbers. There are two features which help with this +problem. Both of them use a common syntax for regular expression extensions, so +we'll look at that first. + +Perl 5 is well known for its powerful additions to standard regular expressions. +For these new features the Perl developers couldn't choose new single-keystroke metacharacters +or new special sequences beginning with ``\`` without making Perl's regular +expressions confusingly different from standard REs. If they chose ``&`` as a +new metacharacter, for example, old expressions would be assuming that ``&`` was +a regular character and wouldn't have escaped it by writing ``\&`` or ``[&]``. + +The solution chosen by the Perl developers was to use ``(?...)`` as the +extension syntax. ``?`` immediately after a parenthesis was a syntax error +because the ``?`` would have nothing to repeat, so this didn't introduce any +compatibility problems. The characters immediately after the ``?`` indicate +what extension is being used, so ``(?=foo)`` is one thing (a positive lookahead +assertion) and ``(?:foo)`` is something else (a non-capturing group containing +the subexpression ``foo``). + +Python supports several of Perl's extensions and adds an extension +syntax to Perl's extension syntax. If the first character after the +question mark is a ``P``, you know that it's an extension that's +specific to Python. + +Now that we've looked at the general extension syntax, we can return +to the features that simplify working with groups in complex REs. + +Sometimes you'll want to use a group to denote a part of a regular expression, +but aren't interested in retrieving the group's contents. You can make this fact +explicit by using a non-capturing group: ``(?:...)``, where you can replace the +``...`` with any other regular expression. :: + + >>> m = re.match("([abc])+", "abc") + >>> m.groups() + ('c',) + >>> m = re.match("(?:[abc])+", "abc") + >>> m.groups() + () + +Except for the fact that you can't retrieve the contents of what the group +matched, a non-capturing group behaves exactly the same as a capturing group; +you can put anything inside it, repeat it with a repetition metacharacter such +as ``*``, and nest it within other groups (capturing or non-capturing). +``(?:...)`` is particularly useful when modifying an existing pattern, since you +can add new groups without changing how all the other groups are numbered. It +should be mentioned that there's no performance difference in searching between +capturing and non-capturing groups; neither form is any faster than the other. + +A more significant feature is named groups: instead of referring to them by +numbers, groups can be referenced by a name. + +The syntax for a named group is one of the Python-specific extensions: +``(?P<name>...)``. *name* is, obviously, the name of the group. Named groups +behave exactly like capturing groups, and additionally associate a name +with a group. The :ref:`match object <match-objects>` methods that deal with +capturing groups all accept either integers that refer to the group by number +or strings that contain the desired group's name. Named groups are still +given numbers, so you can retrieve information about a group in two ways:: + + >>> p = re.compile(r'(?P<word>\b\w+\b)') + >>> m = p.search( '(((( Lots of punctuation )))' ) + >>> m.group('word') + 'Lots' + >>> m.group(1) + 'Lots' + +Additionally, you can retrieve named groups as a dictionary with +:meth:`~re.Match.groupdict`:: + + >>> m = re.match(r'(?P<first>\w+) (?P<last>\w+)', 'Jane Doe') + >>> m.groupdict() + {'first': 'Jane', 'last': 'Doe'} + +Named groups are handy because they let you use easily-remembered names, instead +of having to remember numbers. Here's an example RE from the :mod:`imaplib` +module:: + + InternalDate = re.compile(r'INTERNALDATE "' + r'(?P<day>[ 123][0-9])-(?P<mon>[A-Z][a-z][a-z])-' + r'(?P<year>[0-9][0-9][0-9][0-9])' + r' (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9])' + r' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])' + r'"') + +It's obviously much easier to retrieve ``m.group('zonem')``, instead of having +to remember to retrieve group 9. + +The syntax for backreferences in an expression such as ``(...)\1`` refers to the +number of the group. There's naturally a variant that uses the group name +instead of the number. This is another Python extension: ``(?P=name)`` indicates +that the contents of the group called *name* should again be matched at the +current point. The regular expression for finding doubled words, +``\b(\w+)\s+\1\b`` can also be written as ``\b(?P<word>\w+)\s+(?P=word)\b``:: + + >>> p = re.compile(r'\b(?P<word>\w+)\s+(?P=word)\b') + >>> p.search('Paris in the the spring').group() + 'the the' + + +Lookahead Assertions +-------------------- + +Another zero-width assertion is the lookahead assertion. Lookahead assertions +are available in both positive and negative form, and look like this: + +``(?=...)`` + Positive lookahead assertion. This succeeds if the contained regular + expression, represented here by ``...``, successfully matches at the current + location, and fails otherwise. But, once the contained expression has been + tried, the matching engine doesn't advance at all; the rest of the pattern is + tried right where the assertion started. + +``(?!...)`` + Negative lookahead assertion. This is the opposite of the positive assertion; + it succeeds if the contained expression *doesn't* match at the current position + in the string. + +To make this concrete, let's look at a case where a lookahead is useful. +Consider a simple pattern to match a filename and split it apart into a base +name and an extension, separated by a ``.``. For example, in ``news.rc``, +``news`` is the base name, and ``rc`` is the filename's extension. + +The pattern to match this is quite simple: + +``.*[.].*$`` + +Notice that the ``.`` needs to be treated specially because it's a +metacharacter, so it's inside a character class to only match that +specific character. Also notice the trailing ``$``; this is added to +ensure that all the rest of the string must be included in the +extension. This regular expression matches ``foo.bar`` and +``autoexec.bat`` and ``sendmail.cf`` and ``printers.conf``. + +Now, consider complicating the problem a bit; what if you want to match +filenames where the extension is not ``bat``? Some incorrect attempts: + +``.*[.][^b].*$`` The first attempt above tries to exclude ``bat`` by requiring +that the first character of the extension is not a ``b``. This is wrong, +because the pattern also doesn't match ``foo.bar``. + +``.*[.]([^b]..|.[^a].|..[^t])$`` + +The expression gets messier when you try to patch up the first solution by +requiring one of the following cases to match: the first character of the +extension isn't ``b``; the second character isn't ``a``; or the third character +isn't ``t``. This accepts ``foo.bar`` and rejects ``autoexec.bat``, but it +requires a three-letter extension and won't accept a filename with a two-letter +extension such as ``sendmail.cf``. We'll complicate the pattern again in an +effort to fix it. + +``.*[.]([^b].?.?|.[^a]?.?|..?[^t]?)$`` + +In the third attempt, the second and third letters are all made optional in +order to allow matching extensions shorter than three characters, such as +``sendmail.cf``. + +The pattern's getting really complicated now, which makes it hard to read and +understand. Worse, if the problem changes and you want to exclude both ``bat`` +and ``exe`` as extensions, the pattern would get even more complicated and +confusing. + +A negative lookahead cuts through all this confusion: + +``.*[.](?!bat$)[^.]*$`` The negative lookahead means: if the expression ``bat`` +doesn't match at this point, try the rest of the pattern; if ``bat$`` does +match, the whole pattern will fail. The trailing ``$`` is required to ensure +that something like ``sample.batch``, where the extension only starts with +``bat``, will be allowed. The ``[^.]*`` makes sure that the pattern works +when there are multiple dots in the filename. + +Excluding another filename extension is now easy; simply add it as an +alternative inside the assertion. The following pattern excludes filenames that +end in either ``bat`` or ``exe``: + +``.*[.](?!bat$|exe$)[^.]*$`` + + +Modifying Strings +================= + +Up to this point, we've simply performed searches against a static string. +Regular expressions are also commonly used to modify strings in various ways, +using the following pattern methods: + ++------------------+-----------------------------------------------+ +| Method/Attribute | Purpose | ++==================+===============================================+ +| ``split()`` | Split the string into a list, splitting it | +| | wherever the RE matches | ++------------------+-----------------------------------------------+ +| ``sub()`` | Find all substrings where the RE matches, and | +| | replace them with a different string | ++------------------+-----------------------------------------------+ +| ``subn()`` | Does the same thing as :meth:`!sub`, but | +| | returns the new string and the number of | +| | replacements | ++------------------+-----------------------------------------------+ + + +Splitting Strings +----------------- + +The :meth:`~re.Pattern.split` method of a pattern splits a string apart +wherever the RE matches, returning a list of the pieces. It's similar to the +:meth:`~str.split` method of strings but provides much more generality in the +delimiters that you can split by; string :meth:`!split` only supports splitting by +whitespace or by a fixed string. As you'd expect, there's a module-level +:func:`re.split` function, too. + + +.. method:: .split(string [, maxsplit=0]) + :noindex: + + Split *string* by the matches of the regular expression. If capturing + parentheses are used in the RE, then their contents will also be returned as + part of the resulting list. If *maxsplit* is nonzero, at most *maxsplit* splits + are performed. + +You can limit the number of splits made, by passing a value for *maxsplit*. +When *maxsplit* is nonzero, at most *maxsplit* splits will be made, and the +remainder of the string is returned as the final element of the list. In the +following example, the delimiter is any sequence of non-alphanumeric characters. +:: + + >>> p = re.compile(r'\W+') + >>> p.split('This is a test, short and sweet, of split().') + ['This', 'is', 'a', 'test', 'short', 'and', 'sweet', 'of', 'split', ''] + >>> p.split('This is a test, short and sweet, of split().', 3) + ['This', 'is', 'a', 'test, short and sweet, of split().'] + +Sometimes you're not only interested in what the text between delimiters is, but +also need to know what the delimiter was. If capturing parentheses are used in +the RE, then their values are also returned as part of the list. Compare the +following calls:: + + >>> p = re.compile(r'\W+') + >>> p2 = re.compile(r'(\W+)') + >>> p.split('This... is a test.') + ['This', 'is', 'a', 'test', ''] + >>> p2.split('This... is a test.') + ['This', '... ', 'is', ' ', 'a', ' ', 'test', '.', ''] + +The module-level function :func:`re.split` adds the RE to be used as the first +argument, but is otherwise the same. :: + + >>> re.split(r'[\W]+', 'Words, words, words.') + ['Words', 'words', 'words', ''] + >>> re.split(r'([\W]+)', 'Words, words, words.') + ['Words', ', ', 'words', ', ', 'words', '.', ''] + >>> re.split(r'[\W]+', 'Words, words, words.', 1) + ['Words', 'words, words.'] + + +Search and Replace +------------------ + +Another common task is to find all the matches for a pattern, and replace them +with a different string. The :meth:`~re.Pattern.sub` method takes a replacement value, +which can be either a string or a function, and the string to be processed. + +.. method:: .sub(replacement, string[, count=0]) + :noindex: + + Returns the string obtained by replacing the leftmost non-overlapping + occurrences of the RE in *string* by the replacement *replacement*. If the + pattern isn't found, *string* is returned unchanged. + + The optional argument *count* is the maximum number of pattern occurrences to be + replaced; *count* must be a non-negative integer. The default value of 0 means + to replace all occurrences. + +Here's a simple example of using the :meth:`~re.Pattern.sub` method. It replaces colour +names with the word ``colour``:: + + >>> p = re.compile('(blue|white|red)') + >>> p.sub('colour', 'blue socks and red shoes') + 'colour socks and colour shoes' + >>> p.sub('colour', 'blue socks and red shoes', count=1) + 'colour socks and red shoes' + +The :meth:`~re.Pattern.subn` method does the same work, but returns a 2-tuple containing the +new string value and the number of replacements that were performed:: + + >>> p = re.compile('(blue|white|red)') + >>> p.subn('colour', 'blue socks and red shoes') + ('colour socks and colour shoes', 2) + >>> p.subn('colour', 'no colours at all') + ('no colours at all', 0) + +Empty matches are replaced only when they're not adjacent to a previous empty match. +:: + + >>> p = re.compile('x*') + >>> p.sub('-', 'abxd') + '-a-b--d-' + +If *replacement* is a string, any backslash escapes in it are processed. That +is, ``\n`` is converted to a single newline character, ``\r`` is converted to a +carriage return, and so forth. Unknown escapes such as ``\&`` are left alone. +Backreferences, such as ``\6``, are replaced with the substring matched by the +corresponding group in the RE. This lets you incorporate portions of the +original text in the resulting replacement string. + +This example matches the word ``section`` followed by a string enclosed in +``{``, ``}``, and changes ``section`` to ``subsection``:: + + >>> p = re.compile('section{ ( [^}]* ) }', re.VERBOSE) + >>> p.sub(r'subsection{\1}','section{First} section{second}') + 'subsection{First} subsection{second}' + +There's also a syntax for referring to named groups as defined by the +``(?P<name>...)`` syntax. ``\g<name>`` will use the substring matched by the +group named ``name``, and ``\g<number>`` uses the corresponding group number. +``\g<2>`` is therefore equivalent to ``\2``, but isn't ambiguous in a +replacement string such as ``\g<2>0``. (``\20`` would be interpreted as a +reference to group 20, not a reference to group 2 followed by the literal +character ``'0'``.) The following substitutions are all equivalent, but use all +three variations of the replacement string. :: + + >>> p = re.compile('section{ (?P<name> [^}]* ) }', re.VERBOSE) + >>> p.sub(r'subsection{\1}','section{First}') + 'subsection{First}' + >>> p.sub(r'subsection{\g<1>}','section{First}') + 'subsection{First}' + >>> p.sub(r'subsection{\g<name>}','section{First}') + 'subsection{First}' + +*replacement* can also be a function, which gives you even more control. If +*replacement* is a function, the function is called for every non-overlapping +occurrence of *pattern*. On each call, the function is passed a +:ref:`match object <match-objects>` argument for the match and can use this +information to compute the desired replacement string and return it. + +In the following example, the replacement function translates decimals into +hexadecimal:: + + >>> def hexrepl(match): + ... "Return the hex string for a decimal number" + ... value = int(match.group()) + ... return hex(value) + ... + >>> p = re.compile(r'\d+') + >>> p.sub(hexrepl, 'Call 65490 for printing, 49152 for user code.') + 'Call 0xffd2 for printing, 0xc000 for user code.' + +When using the module-level :func:`re.sub` function, the pattern is passed as +the first argument. The pattern may be provided as an object or as a string; if +you need to specify regular expression flags, you must either use a +pattern object as the first parameter, or use embedded modifiers in the +pattern string, e.g. ``sub("(?i)b+", "x", "bbbb BBBB")`` returns ``'x x'``. + + +Common Problems +=============== + +Regular expressions are a powerful tool for some applications, but in some ways +their behaviour isn't intuitive and at times they don't behave the way you may +expect them to. This section will point out some of the most common pitfalls. + + +Use String Methods +------------------ + +Sometimes using the :mod:`re` module is a mistake. If you're matching a fixed +string, or a single character class, and you're not using any :mod:`re` features +such as the :const:`~re.IGNORECASE` flag, then the full power of regular expressions +may not be required. Strings have several methods for performing operations with +fixed strings and they're usually much faster, because the implementation is a +single small C loop that's been optimized for the purpose, instead of the large, +more generalized regular expression engine. + +One example might be replacing a single fixed string with another one; for +example, you might replace ``word`` with ``deed``. :func:`re.sub` seems like the +function to use for this, but consider the :meth:`~str.replace` method. Note that +:meth:`!replace` will also replace ``word`` inside words, turning ``swordfish`` +into ``sdeedfish``, but the naive RE ``word`` would have done that, too. (To +avoid performing the substitution on parts of words, the pattern would have to +be ``\bword\b``, in order to require that ``word`` have a word boundary on +either side. This takes the job beyond :meth:`!replace`'s abilities.) + +Another common task is deleting every occurrence of a single character from a +string or replacing it with another single character. You might do this with +something like ``re.sub('\n', ' ', S)``, but :meth:`~str.translate` is capable of +doing both tasks and will be faster than any regular expression operation can +be. + +In short, before turning to the :mod:`re` module, consider whether your problem +can be solved with a faster and simpler string method. + + +match() versus search() +----------------------- + +The :func:`~re.match` function only checks if the RE matches at the beginning of the +string while :func:`~re.search` will scan forward through the string for a match. +It's important to keep this distinction in mind. Remember, :func:`!match` will +only report a successful match which will start at 0; if the match wouldn't +start at zero, :func:`!match` will *not* report it. :: + + >>> print(re.match('super', 'superstition').span()) + (0, 5) + >>> print(re.match('super', 'insuperable')) + None + +On the other hand, :func:`~re.search` will scan forward through the string, +reporting the first match it finds. :: + + >>> print(re.search('super', 'superstition').span()) + (0, 5) + >>> print(re.search('super', 'insuperable').span()) + (2, 7) + +Sometimes you'll be tempted to keep using :func:`re.match`, and just add ``.*`` +to the front of your RE. Resist this temptation and use :func:`re.search` +instead. The regular expression compiler does some analysis of REs in order to +speed up the process of looking for a match. One such analysis figures out what +the first character of a match must be; for example, a pattern starting with +``Crow`` must match starting with a ``'C'``. The analysis lets the engine +quickly scan through the string looking for the starting character, only trying +the full match if a ``'C'`` is found. + +Adding ``.*`` defeats this optimization, requiring scanning to the end of the +string and then backtracking to find a match for the rest of the RE. Use +:func:`re.search` instead. + + +Greedy versus Non-Greedy +------------------------ + +When repeating a regular expression, as in ``a*``, the resulting action is to +consume as much of the pattern as possible. This fact often bites you when +you're trying to match a pair of balanced delimiters, such as the angle brackets +surrounding an HTML tag. The naive pattern for matching a single HTML tag +doesn't work because of the greedy nature of ``.*``. :: + + >>> s = '<html><head><title>Title' + >>> len(s) + 32 + >>> print(re.match('<.*>', s).span()) + (0, 32) + >>> print(re.match('<.*>', s).group()) + Title + +The RE matches the ``'<'`` in ``''``, and the ``.*`` consumes the rest of +the string. There's still more left in the RE, though, and the ``>`` can't +match at the end of the string, so the regular expression engine has to +backtrack character by character until it finds a match for the ``>``. The +final match extends from the ``'<'`` in ``''`` to the ``'>'`` in +``''``, which isn't what you want. + +In this case, the solution is to use the non-greedy qualifiers ``*?``, ``+?``, +``??``, or ``{m,n}?``, which match as *little* text as possible. In the above +example, the ``'>'`` is tried immediately after the first ``'<'`` matches, and +when it fails, the engine advances a character at a time, retrying the ``'>'`` +at every step. This produces just the right result:: + + >>> print(re.match('<.*?>', s).group()) + + +(Note that parsing HTML or XML with regular expressions is painful. +Quick-and-dirty patterns will handle common cases, but HTML and XML have special +cases that will break the obvious regular expression; by the time you've written +a regular expression that handles all of the possible cases, the patterns will +be *very* complicated. Use an HTML or XML parser module for such tasks.) + + +Using re.VERBOSE +---------------- + +By now you've probably noticed that regular expressions are a very compact +notation, but they're not terribly readable. REs of moderate complexity can +become lengthy collections of backslashes, parentheses, and metacharacters, +making them difficult to read and understand. + +For such REs, specifying the :const:`re.VERBOSE` flag when compiling the regular +expression can be helpful, because it allows you to format the regular +expression more clearly. + +The ``re.VERBOSE`` flag has several effects. Whitespace in the regular +expression that *isn't* inside a character class is ignored. This means that an +expression such as ``dog | cat`` is equivalent to the less readable ``dog|cat``, +but ``[a b]`` will still match the characters ``'a'``, ``'b'``, or a space. In +addition, you can also put comments inside a RE; comments extend from a ``#`` +character to the next newline. When used with triple-quoted strings, this +enables REs to be formatted more neatly:: + + pat = re.compile(r""" + \s* # Skip leading whitespace + (?P
[^:]+) # Header name + \s* : # Whitespace, and a colon + (?P.*?) # The header's value -- *? used to + # lose the following trailing whitespace + \s*$ # Trailing whitespace to end-of-line + """, re.VERBOSE) + +This is far more readable than:: + + pat = re.compile(r"\s*(?P
[^:]+)\s*:(?P.*?)\s*$") + + +Feedback +======== + +Regular expressions are a complicated topic. Did this document help you +understand them? Were there parts that were unclear, or Problems you +encountered that weren't covered here? If so, please send suggestions for +improvements to the author. + +The most complete book on regular expressions is almost certainly Jeffrey +Friedl's Mastering Regular Expressions, published by O'Reilly. Unfortunately, +it exclusively concentrates on Perl and Java's flavours of regular expressions, +and doesn't contain any Python material at all, so it won't be useful as a +reference for programming in Python. (The first edition covered Python's +now-removed :mod:`!regex` module, which won't help you much.) Consider checking +it out from your library. diff --git a/cpython_2/environment/repo/Doc/howto/sockets.rst b/cpython_2/environment/repo/Doc/howto/sockets.rst new file mode 100644 index 0000000000000000000000000000000000000000..4655f2806089608c3c26379f2c6b97f91e4430f6 --- /dev/null +++ b/cpython_2/environment/repo/Doc/howto/sockets.rst @@ -0,0 +1,383 @@ +.. _socket-howto: + +**************************** + Socket Programming HOWTO +**************************** + +:Author: Gordon McMillan + + +.. topic:: Abstract + + Sockets are used nearly everywhere, but are one of the most severely + misunderstood technologies around. This is a 10,000 foot overview of sockets. + It's not really a tutorial - you'll still have work to do in getting things + operational. It doesn't cover the fine points (and there are a lot of them), but + I hope it will give you enough background to begin using them decently. + + +Sockets +======= + +I'm only going to talk about INET (i.e. IPv4) sockets, but they account for at least 99% of +the sockets in use. And I'll only talk about STREAM (i.e. TCP) sockets - unless you really +know what you're doing (in which case this HOWTO isn't for you!), you'll get +better behavior and performance from a STREAM socket than anything else. I will +try to clear up the mystery of what a socket is, as well as some hints on how to +work with blocking and non-blocking sockets. But I'll start by talking about +blocking sockets. You'll need to know how they work before dealing with +non-blocking sockets. + +Part of the trouble with understanding these things is that "socket" can mean a +number of subtly different things, depending on context. So first, let's make a +distinction between a "client" socket - an endpoint of a conversation, and a +"server" socket, which is more like a switchboard operator. The client +application (your browser, for example) uses "client" sockets exclusively; the +web server it's talking to uses both "server" sockets and "client" sockets. + + +History +------- + +Of the various forms of :abbr:`IPC (Inter Process Communication)`, +sockets are by far the most popular. On any given platform, there are +likely to be other forms of IPC that are faster, but for +cross-platform communication, sockets are about the only game in town. + +They were invented in Berkeley as part of the BSD flavor of Unix. They spread +like wildfire with the Internet. With good reason --- the combination of sockets +with INET makes talking to arbitrary machines around the world unbelievably easy +(at least compared to other schemes). + + +Creating a Socket +================= + +Roughly speaking, when you clicked on the link that brought you to this page, +your browser did something like the following:: + + # create an INET, STREAMing socket + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + # now connect to the web server on port 80 - the normal http port + s.connect(("www.python.org", 80)) + +When the ``connect`` completes, the socket ``s`` can be used to send +in a request for the text of the page. The same socket will read the +reply, and then be destroyed. That's right, destroyed. Client sockets +are normally only used for one exchange (or a small set of sequential +exchanges). + +What happens in the web server is a bit more complex. First, the web server +creates a "server socket":: + + # create an INET, STREAMing socket + serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + # bind the socket to a public host, and a well-known port + serversocket.bind((socket.gethostname(), 80)) + # become a server socket + serversocket.listen(5) + +A couple things to notice: we used ``socket.gethostname()`` so that the socket +would be visible to the outside world. If we had used ``s.bind(('localhost', +80))`` or ``s.bind(('127.0.0.1', 80))`` we would still have a "server" socket, +but one that was only visible within the same machine. ``s.bind(('', 80))`` +specifies that the socket is reachable by any address the machine happens to +have. + +A second thing to note: low number ports are usually reserved for "well known" +services (HTTP, SNMP etc). If you're playing around, use a nice high number (4 +digits). + +Finally, the argument to ``listen`` tells the socket library that we want it to +queue up as many as 5 connect requests (the normal max) before refusing outside +connections. If the rest of the code is written properly, that should be plenty. + +Now that we have a "server" socket, listening on port 80, we can enter the +mainloop of the web server:: + + while True: + # accept connections from outside + (clientsocket, address) = serversocket.accept() + # now do something with the clientsocket + # in this case, we'll pretend this is a threaded server + ct = client_thread(clientsocket) + ct.run() + +There's actually 3 general ways in which this loop could work - dispatching a +thread to handle ``clientsocket``, create a new process to handle +``clientsocket``, or restructure this app to use non-blocking sockets, and +multiplex between our "server" socket and any active ``clientsocket``\ s using +``select``. More about that later. The important thing to understand now is +this: this is *all* a "server" socket does. It doesn't send any data. It doesn't +receive any data. It just produces "client" sockets. Each ``clientsocket`` is +created in response to some *other* "client" socket doing a ``connect()`` to the +host and port we're bound to. As soon as we've created that ``clientsocket``, we +go back to listening for more connections. The two "clients" are free to chat it +up - they are using some dynamically allocated port which will be recycled when +the conversation ends. + + +IPC +--- + +If you need fast IPC between two processes on one machine, you should look into +pipes or shared memory. If you do decide to use AF_INET sockets, bind the +"server" socket to ``'localhost'``. On most platforms, this will take a +shortcut around a couple of layers of network code and be quite a bit faster. + +.. seealso:: + The :mod:`multiprocessing` integrates cross-platform IPC into a higher-level + API. + + +Using a Socket +============== + +The first thing to note, is that the web browser's "client" socket and the web +server's "client" socket are identical beasts. That is, this is a "peer to peer" +conversation. Or to put it another way, *as the designer, you will have to +decide what the rules of etiquette are for a conversation*. Normally, the +``connect``\ ing socket starts the conversation, by sending in a request, or +perhaps a signon. But that's a design decision - it's not a rule of sockets. + +Now there are two sets of verbs to use for communication. You can use ``send`` +and ``recv``, or you can transform your client socket into a file-like beast and +use ``read`` and ``write``. The latter is the way Java presents its sockets. +I'm not going to talk about it here, except to warn you that you need to use +``flush`` on sockets. These are buffered "files", and a common mistake is to +``write`` something, and then ``read`` for a reply. Without a ``flush`` in +there, you may wait forever for the reply, because the request may still be in +your output buffer. + +Now we come to the major stumbling block of sockets - ``send`` and ``recv`` operate +on the network buffers. They do not necessarily handle all the bytes you hand +them (or expect from them), because their major focus is handling the network +buffers. In general, they return when the associated network buffers have been +filled (``send``) or emptied (``recv``). They then tell you how many bytes they +handled. It is *your* responsibility to call them again until your message has +been completely dealt with. + +When a ``recv`` returns 0 bytes, it means the other side has closed (or is in +the process of closing) the connection. You will not receive any more data on +this connection. Ever. You may be able to send data successfully; I'll talk +more about this later. + +A protocol like HTTP uses a socket for only one transfer. The client sends a +request, then reads a reply. That's it. The socket is discarded. This means that +a client can detect the end of the reply by receiving 0 bytes. + +But if you plan to reuse your socket for further transfers, you need to realize +that *there is no* :abbr:`EOT (End of Transfer)` *on a socket.* I repeat: if a socket +``send`` or ``recv`` returns after handling 0 bytes, the connection has been +broken. If the connection has *not* been broken, you may wait on a ``recv`` +forever, because the socket will *not* tell you that there's nothing more to +read (for now). Now if you think about that a bit, you'll come to realize a +fundamental truth of sockets: *messages must either be fixed length* (yuck), *or +be delimited* (shrug), *or indicate how long they are* (much better), *or end by +shutting down the connection*. The choice is entirely yours, (but some ways are +righter than others). + +Assuming you don't want to end the connection, the simplest solution is a fixed +length message:: + + class MySocket: + """demonstration class only + - coded for clarity, not efficiency + """ + + def __init__(self, sock=None): + if sock is None: + self.sock = socket.socket( + socket.AF_INET, socket.SOCK_STREAM) + else: + self.sock = sock + + def connect(self, host, port): + self.sock.connect((host, port)) + + def mysend(self, msg): + totalsent = 0 + while totalsent < MSGLEN: + sent = self.sock.send(msg[totalsent:]) + if sent == 0: + raise RuntimeError("socket connection broken") + totalsent = totalsent + sent + + def myreceive(self): + chunks = [] + bytes_recd = 0 + while bytes_recd < MSGLEN: + chunk = self.sock.recv(min(MSGLEN - bytes_recd, 2048)) + if chunk == b'': + raise RuntimeError("socket connection broken") + chunks.append(chunk) + bytes_recd = bytes_recd + len(chunk) + return b''.join(chunks) + +The sending code here is usable for almost any messaging scheme - in Python you +send strings, and you can use ``len()`` to determine its length (even if it has +embedded ``\0`` characters). It's mostly the receiving code that gets more +complex. (And in C, it's not much worse, except you can't use ``strlen`` if the +message has embedded ``\0``\ s.) + +The easiest enhancement is to make the first character of the message an +indicator of message type, and have the type determine the length. Now you have +two ``recv``\ s - the first to get (at least) that first character so you can +look up the length, and the second in a loop to get the rest. If you decide to +go the delimited route, you'll be receiving in some arbitrary chunk size, (4096 +or 8192 is frequently a good match for network buffer sizes), and scanning what +you've received for a delimiter. + +One complication to be aware of: if your conversational protocol allows multiple +messages to be sent back to back (without some kind of reply), and you pass +``recv`` an arbitrary chunk size, you may end up reading the start of a +following message. You'll need to put that aside and hold onto it, until it's +needed. + +Prefixing the message with its length (say, as 5 numeric characters) gets more +complex, because (believe it or not), you may not get all 5 characters in one +``recv``. In playing around, you'll get away with it; but in high network loads, +your code will very quickly break unless you use two ``recv`` loops - the first +to determine the length, the second to get the data part of the message. Nasty. +This is also when you'll discover that ``send`` does not always manage to get +rid of everything in one pass. And despite having read this, you will eventually +get bit by it! + +In the interests of space, building your character, (and preserving my +competitive position), these enhancements are left as an exercise for the +reader. Lets move on to cleaning up. + + +Binary Data +----------- + +It is perfectly possible to send binary data over a socket. The major problem is +that not all machines use the same formats for binary data. For example, a +Motorola chip will represent a 16 bit integer with the value 1 as the two hex +bytes 00 01. Intel and DEC, however, are byte-reversed - that same 1 is 01 00. +Socket libraries have calls for converting 16 and 32 bit integers - ``ntohl, +htonl, ntohs, htons`` where "n" means *network* and "h" means *host*, "s" means +*short* and "l" means *long*. Where network order is host order, these do +nothing, but where the machine is byte-reversed, these swap the bytes around +appropriately. + +In these days of 32 bit machines, the ascii representation of binary data is +frequently smaller than the binary representation. That's because a surprising +amount of the time, all those longs have the value 0, or maybe 1. The string "0" +would be two bytes, while binary is four. Of course, this doesn't fit well with +fixed-length messages. Decisions, decisions. + + +Disconnecting +============= + +Strictly speaking, you're supposed to use ``shutdown`` on a socket before you +``close`` it. The ``shutdown`` is an advisory to the socket at the other end. +Depending on the argument you pass it, it can mean "I'm not going to send +anymore, but I'll still listen", or "I'm not listening, good riddance!". Most +socket libraries, however, are so used to programmers neglecting to use this +piece of etiquette that normally a ``close`` is the same as ``shutdown(); +close()``. So in most situations, an explicit ``shutdown`` is not needed. + +One way to use ``shutdown`` effectively is in an HTTP-like exchange. The client +sends a request and then does a ``shutdown(1)``. This tells the server "This +client is done sending, but can still receive." The server can detect "EOF" by +a receive of 0 bytes. It can assume it has the complete request. The server +sends a reply. If the ``send`` completes successfully then, indeed, the client +was still receiving. + +Python takes the automatic shutdown a step further, and says that when a socket +is garbage collected, it will automatically do a ``close`` if it's needed. But +relying on this is a very bad habit. If your socket just disappears without +doing a ``close``, the socket at the other end may hang indefinitely, thinking +you're just being slow. *Please* ``close`` your sockets when you're done. + + +When Sockets Die +---------------- + +Probably the worst thing about using blocking sockets is what happens when the +other side comes down hard (without doing a ``close``). Your socket is likely to +hang. TCP is a reliable protocol, and it will wait a long, long time +before giving up on a connection. If you're using threads, the entire thread is +essentially dead. There's not much you can do about it. As long as you aren't +doing something dumb, like holding a lock while doing a blocking read, the +thread isn't really consuming much in the way of resources. Do *not* try to kill +the thread - part of the reason that threads are more efficient than processes +is that they avoid the overhead associated with the automatic recycling of +resources. In other words, if you do manage to kill the thread, your whole +process is likely to be screwed up. + + +Non-blocking Sockets +==================== + +If you've understood the preceding, you already know most of what you need to +know about the mechanics of using sockets. You'll still use the same calls, in +much the same ways. It's just that, if you do it right, your app will be almost +inside-out. + +In Python, you use ``socket.setblocking(False)`` to make it non-blocking. In C, it's +more complex, (for one thing, you'll need to choose between the BSD flavor +``O_NONBLOCK`` and the almost indistinguishable Posix flavor ``O_NDELAY``, which +is completely different from ``TCP_NODELAY``), but it's the exact same idea. You +do this after creating the socket, but before using it. (Actually, if you're +nuts, you can switch back and forth.) + +The major mechanical difference is that ``send``, ``recv``, ``connect`` and +``accept`` can return without having done anything. You have (of course) a +number of choices. You can check return code and error codes and generally drive +yourself crazy. If you don't believe me, try it sometime. Your app will grow +large, buggy and suck CPU. So let's skip the brain-dead solutions and do it +right. + +Use ``select``. + +In C, coding ``select`` is fairly complex. In Python, it's a piece of cake, but +it's close enough to the C version that if you understand ``select`` in Python, +you'll have little trouble with it in C:: + + ready_to_read, ready_to_write, in_error = \ + select.select( + potential_readers, + potential_writers, + potential_errs, + timeout) + +You pass ``select`` three lists: the first contains all sockets that you might +want to try reading; the second all the sockets you might want to try writing +to, and the last (normally left empty) those that you want to check for errors. +You should note that a socket can go into more than one list. The ``select`` +call is blocking, but you can give it a timeout. This is generally a sensible +thing to do - give it a nice long timeout (say a minute) unless you have good +reason to do otherwise. + +In return, you will get three lists. They contain the sockets that are actually +readable, writable and in error. Each of these lists is a subset (possibly +empty) of the corresponding list you passed in. + +If a socket is in the output readable list, you can be +as-close-to-certain-as-we-ever-get-in-this-business that a ``recv`` on that +socket will return *something*. Same idea for the writable list. You'll be able +to send *something*. Maybe not all you want to, but *something* is better than +nothing. (Actually, any reasonably healthy socket will return as writable - it +just means outbound network buffer space is available.) + +If you have a "server" socket, put it in the potential_readers list. If it comes +out in the readable list, your ``accept`` will (almost certainly) work. If you +have created a new socket to ``connect`` to someone else, put it in the +potential_writers list. If it shows up in the writable list, you have a decent +chance that it has connected. + +Actually, ``select`` can be handy even with blocking sockets. It's one way of +determining whether you will block - the socket returns as readable when there's +something in the buffers. However, this still doesn't help with the problem of +determining whether the other end is done, or just busy with something else. + +**Portability alert**: On Unix, ``select`` works both with the sockets and +files. Don't try this on Windows. On Windows, ``select`` works with sockets +only. Also note that in C, many of the more advanced socket options are done +differently on Windows. In fact, on Windows I usually use threads (which work +very, very well) with my sockets. + + diff --git a/cpython_2/environment/repo/Doc/howto/sorting.rst b/cpython_2/environment/repo/Doc/howto/sorting.rst new file mode 100644 index 0000000000000000000000000000000000000000..a8efe65353d6e14b7aa0cb5d4ad7b4aff5245043 --- /dev/null +++ b/cpython_2/environment/repo/Doc/howto/sorting.rst @@ -0,0 +1,306 @@ +.. _sortinghowto: + +Sorting HOW TO +************** + +:Author: Andrew Dalke and Raymond Hettinger +:Release: 0.1 + + +Python lists have a built-in :meth:`list.sort` method that modifies the list +in-place. There is also a :func:`sorted` built-in function that builds a new +sorted list from an iterable. + +In this document, we explore the various techniques for sorting data using Python. + + +Sorting Basics +============== + +A simple ascending sort is very easy: just call the :func:`sorted` function. It +returns a new sorted list:: + + >>> sorted([5, 2, 3, 1, 4]) + [1, 2, 3, 4, 5] + +You can also use the :meth:`list.sort` method. It modifies the list +in-place (and returns ``None`` to avoid confusion). Usually it's less convenient +than :func:`sorted` - but if you don't need the original list, it's slightly +more efficient. + + >>> a = [5, 2, 3, 1, 4] + >>> a.sort() + >>> a + [1, 2, 3, 4, 5] + +Another difference is that the :meth:`list.sort` method is only defined for +lists. In contrast, the :func:`sorted` function accepts any iterable. + + >>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}) + [1, 2, 3, 4, 5] + +Key Functions +============= + +Both :meth:`list.sort` and :func:`sorted` have a *key* parameter to specify a +function (or other callable) to be called on each list element prior to making +comparisons. + +For example, here's a case-insensitive string comparison: + + >>> sorted("This is a test string from Andrew".split(), key=str.lower) + ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This'] + +The value of the *key* parameter should be a function (or other callable) that +takes a single argument and returns a key to use for sorting purposes. This +technique is fast because the key function is called exactly once for each +input record. + +A common pattern is to sort complex objects using some of the object's indices +as keys. For example: + + >>> student_tuples = [ + ... ('john', 'A', 15), + ... ('jane', 'B', 12), + ... ('dave', 'B', 10), + ... ] + >>> sorted(student_tuples, key=lambda student: student[2]) # sort by age + [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] + +The same technique works for objects with named attributes. For example: + + >>> class Student: + ... def __init__(self, name, grade, age): + ... self.name = name + ... self.grade = grade + ... self.age = age + ... def __repr__(self): + ... return repr((self.name, self.grade, self.age)) + + >>> student_objects = [ + ... Student('john', 'A', 15), + ... Student('jane', 'B', 12), + ... Student('dave', 'B', 10), + ... ] + >>> sorted(student_objects, key=lambda student: student.age) # sort by age + [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] + +Operator Module Functions +========================= + +The key-function patterns shown above are very common, so Python provides +convenience functions to make accessor functions easier and faster. The +:mod:`operator` module has :func:`~operator.itemgetter`, +:func:`~operator.attrgetter`, and a :func:`~operator.methodcaller` function. + +Using those functions, the above examples become simpler and faster: + + >>> from operator import itemgetter, attrgetter + + >>> sorted(student_tuples, key=itemgetter(2)) + [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] + + >>> sorted(student_objects, key=attrgetter('age')) + [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] + +The operator module functions allow multiple levels of sorting. For example, to +sort by *grade* then by *age*: + + >>> sorted(student_tuples, key=itemgetter(1,2)) + [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)] + + >>> sorted(student_objects, key=attrgetter('grade', 'age')) + [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)] + +Ascending and Descending +======================== + +Both :meth:`list.sort` and :func:`sorted` accept a *reverse* parameter with a +boolean value. This is used to flag descending sorts. For example, to get the +student data in reverse *age* order: + + >>> sorted(student_tuples, key=itemgetter(2), reverse=True) + [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] + + >>> sorted(student_objects, key=attrgetter('age'), reverse=True) + [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] + +Sort Stability and Complex Sorts +================================ + +Sorts are guaranteed to be `stable +`_\. That means that +when multiple records have the same key, their original order is preserved. + + >>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)] + >>> sorted(data, key=itemgetter(0)) + [('blue', 1), ('blue', 2), ('red', 1), ('red', 2)] + +Notice how the two records for *blue* retain their original order so that +``('blue', 1)`` is guaranteed to precede ``('blue', 2)``. + +This wonderful property lets you build complex sorts in a series of sorting +steps. For example, to sort the student data by descending *grade* and then +ascending *age*, do the *age* sort first and then sort again using *grade*: + + >>> s = sorted(student_objects, key=attrgetter('age')) # sort on secondary key + >>> sorted(s, key=attrgetter('grade'), reverse=True) # now sort on primary key, descending + [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] + +This can be abstracted out into a wrapper function that can take a list and +tuples of field and order to sort them on multiple passes. + + >>> def multisort(xs, specs): + ... for key, reverse in reversed(specs): + ... xs.sort(key=attrgetter(key), reverse=reverse) + ... return xs + + >>> multisort(list(student_objects), (('grade', True), ('age', False))) + [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] + +The `Timsort `_ algorithm used in Python +does multiple sorts efficiently because it can take advantage of any ordering +already present in a dataset. + +The Old Way Using Decorate-Sort-Undecorate +========================================== + +This idiom is called Decorate-Sort-Undecorate after its three steps: + +* First, the initial list is decorated with new values that control the sort order. + +* Second, the decorated list is sorted. + +* Finally, the decorations are removed, creating a list that contains only the + initial values in the new order. + +For example, to sort the student data by *grade* using the DSU approach: + + >>> decorated = [(student.grade, i, student) for i, student in enumerate(student_objects)] + >>> decorated.sort() + >>> [student for grade, i, student in decorated] # undecorate + [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] + +This idiom works because tuples are compared lexicographically; the first items +are compared; if they are the same then the second items are compared, and so +on. + +It is not strictly necessary in all cases to include the index *i* in the +decorated list, but including it gives two benefits: + +* The sort is stable -- if two items have the same key, their order will be + preserved in the sorted list. + +* The original items do not have to be comparable because the ordering of the + decorated tuples will be determined by at most the first two items. So for + example the original list could contain complex numbers which cannot be sorted + directly. + +Another name for this idiom is +`Schwartzian transform `_\, +after Randal L. Schwartz, who popularized it among Perl programmers. + +Now that Python sorting provides key-functions, this technique is not often needed. + + +The Old Way Using the *cmp* Parameter +===================================== + +Many constructs given in this HOWTO assume Python 2.4 or later. Before that, +there was no :func:`sorted` builtin and :meth:`list.sort` took no keyword +arguments. Instead, all of the Py2.x versions supported a *cmp* parameter to +handle user specified comparison functions. + +In Py3.0, the *cmp* parameter was removed entirely (as part of a larger effort to +simplify and unify the language, eliminating the conflict between rich +comparisons and the :meth:`__cmp__` magic method). + +In Py2.x, sort allowed an optional function which can be called for doing the +comparisons. That function should take two arguments to be compared and then +return a negative value for less-than, return zero if they are equal, or return +a positive value for greater-than. For example, we can do: + + >>> def numeric_compare(x, y): + ... return x - y + >>> sorted([5, 2, 4, 1, 3], cmp=numeric_compare) # doctest: +SKIP + [1, 2, 3, 4, 5] + +Or you can reverse the order of comparison with: + + >>> def reverse_numeric(x, y): + ... return y - x + >>> sorted([5, 2, 4, 1, 3], cmp=reverse_numeric) # doctest: +SKIP + [5, 4, 3, 2, 1] + +When porting code from Python 2.x to 3.x, the situation can arise when you have +the user supplying a comparison function and you need to convert that to a key +function. The following wrapper makes that easy to do:: + + def cmp_to_key(mycmp): + 'Convert a cmp= function into a key= function' + class K: + def __init__(self, obj, *args): + self.obj = obj + def __lt__(self, other): + return mycmp(self.obj, other.obj) < 0 + def __gt__(self, other): + return mycmp(self.obj, other.obj) > 0 + def __eq__(self, other): + return mycmp(self.obj, other.obj) == 0 + def __le__(self, other): + return mycmp(self.obj, other.obj) <= 0 + def __ge__(self, other): + return mycmp(self.obj, other.obj) >= 0 + def __ne__(self, other): + return mycmp(self.obj, other.obj) != 0 + return K + +To convert to a key function, just wrap the old comparison function: + +.. testsetup:: + + from functools import cmp_to_key + +.. doctest:: + + >>> sorted([5, 2, 4, 1, 3], key=cmp_to_key(reverse_numeric)) + [5, 4, 3, 2, 1] + +In Python 3.2, the :func:`functools.cmp_to_key` function was added to the +:mod:`functools` module in the standard library. + +Odd and Ends +============ + +* For locale aware sorting, use :func:`locale.strxfrm` for a key function or + :func:`locale.strcoll` for a comparison function. + +* The *reverse* parameter still maintains sort stability (so that records with + equal keys retain the original order). Interestingly, that effect can be + simulated without the parameter by using the builtin :func:`reversed` function + twice: + + >>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)] + >>> standard_way = sorted(data, key=itemgetter(0), reverse=True) + >>> double_reversed = list(reversed(sorted(reversed(data), key=itemgetter(0)))) + >>> assert standard_way == double_reversed + >>> standard_way + [('red', 1), ('red', 2), ('blue', 1), ('blue', 2)] + +* The sort routines are guaranteed to use :meth:`__lt__` when making comparisons + between two objects. So, it is easy to add a standard sort order to a class by + defining an :meth:`__lt__` method:: + + >>> Student.__lt__ = lambda self, other: self.age < other.age + >>> sorted(student_objects) + [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] + +* Key functions need not depend directly on the objects being sorted. A key + function can also access external resources. For instance, if the student grades + are stored in a dictionary, they can be used to sort a separate list of student + names: + + >>> students = ['dave', 'john', 'jane'] + >>> newgrades = {'john': 'F', 'jane':'A', 'dave': 'C'} + >>> sorted(students, key=newgrades.__getitem__) + ['jane', 'dave', 'john'] diff --git a/cpython_2/environment/repo/Doc/howto/unicode.rst b/cpython_2/environment/repo/Doc/howto/unicode.rst new file mode 100644 index 0000000000000000000000000000000000000000..e948c1e3c662d6b201dc534e9a0de56fe3eb9acd --- /dev/null +++ b/cpython_2/environment/repo/Doc/howto/unicode.rst @@ -0,0 +1,764 @@ +.. _unicode-howto: + +***************** + Unicode HOWTO +***************** + +:Release: 1.12 + +This HOWTO discusses Python's support for the Unicode specification +for representing textual data, and explains various problems that +people commonly encounter when trying to work with Unicode. + + +Introduction to Unicode +======================= + +Definitions +----------- + +Today's programs need to be able to handle a wide variety of +characters. Applications are often internationalized to display +messages and output in a variety of user-selectable languages; the +same program might need to output an error message in English, French, +Japanese, Hebrew, or Russian. Web content can be written in any of +these languages and can also include a variety of emoji symbols. +Python's string type uses the Unicode Standard for representing +characters, which lets Python programs work with all these different +possible characters. + +Unicode (https://www.unicode.org/) is a specification that aims to +list every character used by human languages and give each character +its own unique code. The Unicode specifications are continually +revised and updated to add new languages and symbols. + +A **character** is the smallest possible component of a text. 'A', 'B', 'C', +etc., are all different characters. So are 'È' and 'Í'. Characters vary +depending on the language or context you're talking +about. For example, there's a character for "Roman Numeral One", 'Ⅰ', that's +separate from the uppercase letter 'I'. They'll usually look the same, +but these are two different characters that have different meanings. + +The Unicode standard describes how characters are represented by +**code points**. A code point value is an integer in the range 0 to +0x10FFFF (about 1.1 million values, the +`actual number assigned `_ +is less than that). In the standard and in this document, a code point is written +using the notation ``U+265E`` to mean the character with value +``0x265e`` (9,822 in decimal). + +The Unicode standard contains a lot of tables listing characters and +their corresponding code points: + +.. code-block:: none + + 0061 'a'; LATIN SMALL LETTER A + 0062 'b'; LATIN SMALL LETTER B + 0063 'c'; LATIN SMALL LETTER C + ... + 007B '{'; LEFT CURLY BRACKET + ... + 2167 'Ⅷ'; ROMAN NUMERAL EIGHT + 2168 'Ⅸ'; ROMAN NUMERAL NINE + ... + 265E '♞'; BLACK CHESS KNIGHT + 265F '♟'; BLACK CHESS PAWN + ... + 1F600 '😀'; GRINNING FACE + 1F609 '😉'; WINKING FACE + ... + +Strictly, these definitions imply that it's meaningless to say 'this is +character ``U+265E``'. ``U+265E`` is a code point, which represents some particular +character; in this case, it represents the character 'BLACK CHESS KNIGHT', +'♞'. In +informal contexts, this distinction between code points and characters will +sometimes be forgotten. + +A character is represented on a screen or on paper by a set of graphical +elements that's called a **glyph**. The glyph for an uppercase A, for example, +is two diagonal strokes and a horizontal stroke, though the exact details will +depend on the font being used. Most Python code doesn't need to worry about +glyphs; figuring out the correct glyph to display is generally the job of a GUI +toolkit or a terminal's font renderer. + + +Encodings +--------- + +To summarize the previous section: a Unicode string is a sequence of +code points, which are numbers from 0 through ``0x10FFFF`` (1,114,111 +decimal). This sequence of code points needs to be represented in +memory as a set of **code units**, and **code units** are then mapped +to 8-bit bytes. The rules for translating a Unicode string into a +sequence of bytes are called a **character encoding**, or just +an **encoding**. + +The first encoding you might think of is using 32-bit integers as the +code unit, and then using the CPU's representation of 32-bit integers. +In this representation, the string "Python" might look like this: + +.. code-block:: none + + P y t h o n + 0x50 00 00 00 79 00 00 00 74 00 00 00 68 00 00 00 6f 00 00 00 6e 00 00 00 + 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 + +This representation is straightforward but using it presents a number of +problems. + +1. It's not portable; different processors order the bytes differently. + +2. It's very wasteful of space. In most texts, the majority of the code points + are less than 127, or less than 255, so a lot of space is occupied by ``0x00`` + bytes. The above string takes 24 bytes compared to the 6 bytes needed for an + ASCII representation. Increased RAM usage doesn't matter too much (desktop + computers have gigabytes of RAM, and strings aren't usually that large), but + expanding our usage of disk and network bandwidth by a factor of 4 is + intolerable. + +3. It's not compatible with existing C functions such as ``strlen()``, so a new + family of wide string functions would need to be used. + +Therefore this encoding isn't used very much, and people instead choose other +encodings that are more efficient and convenient, such as UTF-8. + +UTF-8 is one of the most commonly used encodings, and Python often +defaults to using it. UTF stands for "Unicode Transformation Format", +and the '8' means that 8-bit values are used in the encoding. (There +are also UTF-16 and UTF-32 encodings, but they are less frequently +used than UTF-8.) UTF-8 uses the following rules: + +1. If the code point is < 128, it's represented by the corresponding byte value. +2. If the code point is >= 128, it's turned into a sequence of two, three, or + four bytes, where each byte of the sequence is between 128 and 255. + +UTF-8 has several convenient properties: + +1. It can handle any Unicode code point. +2. A Unicode string is turned into a sequence of bytes that contains embedded + zero bytes only where they represent the null character (U+0000). This means + that UTF-8 strings can be processed by C functions such as ``strcpy()`` and sent + through protocols that can't handle zero bytes for anything other than + end-of-string markers. +3. A string of ASCII text is also valid UTF-8 text. +4. UTF-8 is fairly compact; the majority of commonly used characters can be + represented with one or two bytes. +5. If bytes are corrupted or lost, it's possible to determine the start of the + next UTF-8-encoded code point and resynchronize. It's also unlikely that + random 8-bit data will look like valid UTF-8. +6. UTF-8 is a byte oriented encoding. The encoding specifies that each + character is represented by a specific sequence of one or more bytes. This + avoids the byte-ordering issues that can occur with integer and word oriented + encodings, like UTF-16 and UTF-32, where the sequence of bytes varies depending + on the hardware on which the string was encoded. + + +References +---------- + +The `Unicode Consortium site `_ has character charts, a +glossary, and PDF versions of the Unicode specification. Be prepared for some +difficult reading. `A chronology `_ of the +origin and development of Unicode is also available on the site. + +On the Computerphile Youtube channel, Tom Scott briefly +`discusses the history of Unicode and UTF-8 `_ +(9 minutes 36 seconds). + +To help understand the standard, Jukka Korpela has written `an introductory +guide `_ to reading the +Unicode character tables. + +Another `good introductory article `_ +was written by Joel Spolsky. +If this introduction didn't make things clear to you, you should try +reading this alternate article before continuing. + +Wikipedia entries are often helpful; see the entries for "`character encoding +`_" and `UTF-8 +`_, for example. + + +Python's Unicode Support +======================== + +Now that you've learned the rudiments of Unicode, we can look at Python's +Unicode features. + +The String Type +--------------- + +Since Python 3.0, the language's :class:`str` type contains Unicode +characters, meaning any string created using ``"unicode rocks!"``, ``'unicode +rocks!'``, or the triple-quoted string syntax is stored as Unicode. + +The default encoding for Python source code is UTF-8, so you can simply +include a Unicode character in a string literal:: + + try: + with open('/tmp/input.txt', 'r') as f: + ... + except OSError: + # 'File not found' error message. + print("Fichier non trouvé") + +Side note: Python 3 also supports using Unicode characters in identifiers:: + + répertoire = "/tmp/records.log" + with open(répertoire, "w") as f: + f.write("test\n") + +If you can't enter a particular character in your editor or want to +keep the source code ASCII-only for some reason, you can also use +escape sequences in string literals. (Depending on your system, +you may see the actual capital-delta glyph instead of a \u escape.) :: + + >>> "\N{GREEK CAPITAL LETTER DELTA}" # Using the character name + '\u0394' + >>> "\u0394" # Using a 16-bit hex value + '\u0394' + >>> "\U00000394" # Using a 32-bit hex value + '\u0394' + +In addition, one can create a string using the :func:`~bytes.decode` method of +:class:`bytes`. This method takes an *encoding* argument, such as ``UTF-8``, +and optionally an *errors* argument. + +The *errors* argument specifies the response when the input string can't be +converted according to the encoding's rules. Legal values for this argument are +``'strict'`` (raise a :exc:`UnicodeDecodeError` exception), ``'replace'`` (use +``U+FFFD``, ``REPLACEMENT CHARACTER``), ``'ignore'`` (just leave the +character out of the Unicode result), or ``'backslashreplace'`` (inserts a +``\xNN`` escape sequence). +The following examples show the differences:: + + >>> b'\x80abc'.decode("utf-8", "strict") #doctest: +NORMALIZE_WHITESPACE + Traceback (most recent call last): + ... + UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: + invalid start byte + >>> b'\x80abc'.decode("utf-8", "replace") + '\ufffdabc' + >>> b'\x80abc'.decode("utf-8", "backslashreplace") + '\\x80abc' + >>> b'\x80abc'.decode("utf-8", "ignore") + 'abc' + +Encodings are specified as strings containing the encoding's name. Python +comes with roughly 100 different encodings; see the Python Library Reference at +:ref:`standard-encodings` for a list. Some encodings have multiple names; for +example, ``'latin-1'``, ``'iso_8859_1'`` and ``'8859``' are all synonyms for +the same encoding. + +One-character Unicode strings can also be created with the :func:`chr` +built-in function, which takes integers and returns a Unicode string of length 1 +that contains the corresponding code point. The reverse operation is the +built-in :func:`ord` function that takes a one-character Unicode string and +returns the code point value:: + + >>> chr(57344) + '\ue000' + >>> ord('\ue000') + 57344 + +Converting to Bytes +------------------- + +The opposite method of :meth:`bytes.decode` is :meth:`str.encode`, +which returns a :class:`bytes` representation of the Unicode string, encoded in the +requested *encoding*. + +The *errors* parameter is the same as the parameter of the +:meth:`~bytes.decode` method but supports a few more possible handlers. As well as +``'strict'``, ``'ignore'``, and ``'replace'`` (which in this case +inserts a question mark instead of the unencodable character), there is +also ``'xmlcharrefreplace'`` (inserts an XML character reference), +``backslashreplace`` (inserts a ``\uNNNN`` escape sequence) and +``namereplace`` (inserts a ``\N{...}`` escape sequence). + +The following example shows the different results:: + + >>> u = chr(40960) + 'abcd' + chr(1972) + >>> u.encode('utf-8') + b'\xea\x80\x80abcd\xde\xb4' + >>> u.encode('ascii') #doctest: +NORMALIZE_WHITESPACE + Traceback (most recent call last): + ... + UnicodeEncodeError: 'ascii' codec can't encode character '\ua000' in + position 0: ordinal not in range(128) + >>> u.encode('ascii', 'ignore') + b'abcd' + >>> u.encode('ascii', 'replace') + b'?abcd?' + >>> u.encode('ascii', 'xmlcharrefreplace') + b'ꀀabcd޴' + >>> u.encode('ascii', 'backslashreplace') + b'\\ua000abcd\\u07b4' + >>> u.encode('ascii', 'namereplace') + b'\\N{YI SYLLABLE IT}abcd\\u07b4' + +The low-level routines for registering and accessing the available +encodings are found in the :mod:`codecs` module. Implementing new +encodings also requires understanding the :mod:`codecs` module. +However, the encoding and decoding functions returned by this module +are usually more low-level than is comfortable, and writing new encodings +is a specialized task, so the module won't be covered in this HOWTO. + + +Unicode Literals in Python Source Code +-------------------------------------- + +In Python source code, specific Unicode code points can be written using the +``\u`` escape sequence, which is followed by four hex digits giving the code +point. The ``\U`` escape sequence is similar, but expects eight hex digits, +not four:: + + >>> s = "a\xac\u1234\u20ac\U00008000" + ... # ^^^^ two-digit hex escape + ... # ^^^^^^ four-digit Unicode escape + ... # ^^^^^^^^^^ eight-digit Unicode escape + >>> [ord(c) for c in s] + [97, 172, 4660, 8364, 32768] + +Using escape sequences for code points greater than 127 is fine in small doses, +but becomes an annoyance if you're using many accented characters, as you would +in a program with messages in French or some other accent-using language. You +can also assemble strings using the :func:`chr` built-in function, but this is +even more tedious. + +Ideally, you'd want to be able to write literals in your language's natural +encoding. You could then edit Python source code with your favorite editor +which would display the accented characters naturally, and have the right +characters used at runtime. + +Python supports writing source code in UTF-8 by default, but you can use almost +any encoding if you declare the encoding being used. This is done by including +a special comment as either the first or second line of the source file:: + + #!/usr/bin/env python + # -*- coding: latin-1 -*- + + u = 'abcdé' + print(ord(u[-1])) + +The syntax is inspired by Emacs's notation for specifying variables local to a +file. Emacs supports many different variables, but Python only supports +'coding'. The ``-*-`` symbols indicate to Emacs that the comment is special; +they have no significance to Python but are a convention. Python looks for +``coding: name`` or ``coding=name`` in the comment. + +If you don't include such a comment, the default encoding used will be UTF-8 as +already mentioned. See also :pep:`263` for more information. + + +Unicode Properties +------------------ + +The Unicode specification includes a database of information about +code points. For each defined code point, the information includes +the character's name, its category, the numeric value if applicable +(for characters representing numeric concepts such as the Roman +numerals, fractions such as one-third and four-fifths, etc.). There +are also display-related properties, such as how to use the code point +in bidirectional text. + +The following program displays some information about several characters, and +prints the numeric value of one particular character:: + + import unicodedata + + u = chr(233) + chr(0x0bf2) + chr(3972) + chr(6000) + chr(13231) + + for i, c in enumerate(u): + print(i, '%04x' % ord(c), unicodedata.category(c), end=" ") + print(unicodedata.name(c)) + + # Get numeric value of second character + print(unicodedata.numeric(u[1])) + +When run, this prints: + +.. code-block:: none + + 0 00e9 Ll LATIN SMALL LETTER E WITH ACUTE + 1 0bf2 No TAMIL NUMBER ONE THOUSAND + 2 0f84 Mn TIBETAN MARK HALANTA + 3 1770 Lo TAGBANWA LETTER SA + 4 33af So SQUARE RAD OVER S SQUARED + 1000.0 + +The category codes are abbreviations describing the nature of the character. +These are grouped into categories such as "Letter", "Number", "Punctuation", or +"Symbol", which in turn are broken up into subcategories. To take the codes +from the above output, ``'Ll'`` means 'Letter, lowercase', ``'No'`` means +"Number, other", ``'Mn'`` is "Mark, nonspacing", and ``'So'`` is "Symbol, +other". See +`the General Category Values section of the Unicode Character Database documentation `_ for a +list of category codes. + + +Comparing Strings +----------------- + +Unicode adds some complication to comparing strings, because the same +set of characters can be represented by different sequences of code +points. For example, a letter like 'ê' can be represented as a single +code point U+00EA, or as U+0065 U+0302, which is the code point for +'e' followed by a code point for 'COMBINING CIRCUMFLEX ACCENT'. These +will produce the same output when printed, but one is a string of +length 1 and the other is of length 2. + +One tool for a case-insensitive comparison is the +:meth:`~str.casefold` string method that converts a string to a +case-insensitive form following an algorithm described by the Unicode +Standard. This algorithm has special handling for characters such as +the German letter 'ß' (code point U+00DF), which becomes the pair of +lowercase letters 'ss'. + +:: + + >>> street = 'Gürzenichstraße' + >>> street.casefold() + 'gürzenichstrasse' + +A second tool is the :mod:`unicodedata` module's +:func:`~unicodedata.normalize` function that converts strings to one +of several normal forms, where letters followed by a combining +character are replaced with single characters. :func:`normalize` can +be used to perform string comparisons that won't falsely report +inequality if two strings use combining characters differently: + +:: + + import unicodedata + + def compare_strs(s1, s2): + def NFD(s): + return unicodedata.normalize('NFD', s) + + return NFD(s1) == NFD(s2) + + single_char = 'ê' + multiple_chars = '\N{LATIN SMALL LETTER E}\N{COMBINING CIRCUMFLEX ACCENT}' + print('length of first string=', len(single_char)) + print('length of second string=', len(multiple_chars)) + print(compare_strs(single_char, multiple_chars)) + +When run, this outputs: + +.. code-block:: shell-session + + $ python3 compare-strs.py + length of first string= 1 + length of second string= 2 + True + +The first argument to the :func:`~unicodedata.normalize` function is a +string giving the desired normalization form, which can be one of +'NFC', 'NFKC', 'NFD', and 'NFKD'. + +The Unicode Standard also specifies how to do caseless comparisons:: + + import unicodedata + + def compare_caseless(s1, s2): + def NFD(s): + return unicodedata.normalize('NFD', s) + + return NFD(NFD(s1).casefold()) == NFD(NFD(s2).casefold()) + + # Example usage + single_char = 'ê' + multiple_chars = '\N{LATIN CAPITAL LETTER E}\N{COMBINING CIRCUMFLEX ACCENT}' + + print(compare_caseless(single_char, multiple_chars)) + +This will print ``True``. (Why is :func:`NFD` invoked twice? Because +there are a few characters that make :meth:`casefold` return a +non-normalized string, so the result needs to be normalized again. See +section 3.13 of the Unicode Standard for a discussion and an example.) + + +Unicode Regular Expressions +--------------------------- + +The regular expressions supported by the :mod:`re` module can be provided +either as bytes or strings. Some of the special character sequences such as +``\d`` and ``\w`` have different meanings depending on whether +the pattern is supplied as bytes or a string. For example, +``\d`` will match the characters ``[0-9]`` in bytes but +in strings will match any character that's in the ``'Nd'`` category. + +The string in this example has the number 57 written in both Thai and +Arabic numerals:: + + import re + p = re.compile(r'\d+') + + s = "Over \u0e55\u0e57 57 flavours" + m = p.search(s) + print(repr(m.group())) + +When executed, ``\d+`` will match the Thai numerals and print them +out. If you supply the :const:`re.ASCII` flag to +:func:`~re.compile`, ``\d+`` will match the substring "57" instead. + +Similarly, ``\w`` matches a wide variety of Unicode characters but +only ``[a-zA-Z0-9_]`` in bytes or if :const:`re.ASCII` is supplied, +and ``\s`` will match either Unicode whitespace characters or +``[ \t\n\r\f\v]``. + + +References +---------- + +.. comment should these be mentioned earlier, e.g. at the start of the "introduction to Unicode" first section? + +Some good alternative discussions of Python's Unicode support are: + +* `Processing Text Files in Python 3 `_, by Nick Coghlan. +* `Pragmatic Unicode `_, a PyCon 2012 presentation by Ned Batchelder. + +The :class:`str` type is described in the Python library reference at +:ref:`textseq`. + +The documentation for the :mod:`unicodedata` module. + +The documentation for the :mod:`codecs` module. + +Marc-André Lemburg gave `a presentation titled "Python and Unicode" (PDF slides) +`_ at +EuroPython 2002. The slides are an excellent overview of the design of Python +2's Unicode features (where the Unicode string type is called ``unicode`` and +literals start with ``u``). + + +Reading and Writing Unicode Data +================================ + +Once you've written some code that works with Unicode data, the next problem is +input/output. How do you get Unicode strings into your program, and how do you +convert Unicode into a form suitable for storage or transmission? + +It's possible that you may not need to do anything depending on your input +sources and output destinations; you should check whether the libraries used in +your application support Unicode natively. XML parsers often return Unicode +data, for example. Many relational databases also support Unicode-valued +columns and can return Unicode values from an SQL query. + +Unicode data is usually converted to a particular encoding before it gets +written to disk or sent over a socket. It's possible to do all the work +yourself: open a file, read an 8-bit bytes object from it, and convert the bytes +with ``bytes.decode(encoding)``. However, the manual approach is not recommended. + +One problem is the multi-byte nature of encodings; one Unicode character can be +represented by several bytes. If you want to read the file in arbitrary-sized +chunks (say, 1024 or 4096 bytes), you need to write error-handling code to catch the case +where only part of the bytes encoding a single Unicode character are read at the +end of a chunk. One solution would be to read the entire file into memory and +then perform the decoding, but that prevents you from working with files that +are extremely large; if you need to read a 2 GiB file, you need 2 GiB of RAM. +(More, really, since for at least a moment you'd need to have both the encoded +string and its Unicode version in memory.) + +The solution would be to use the low-level decoding interface to catch the case +of partial coding sequences. The work of implementing this has already been +done for you: the built-in :func:`open` function can return a file-like object +that assumes the file's contents are in a specified encoding and accepts Unicode +parameters for methods such as :meth:`~io.TextIOBase.read` and +:meth:`~io.TextIOBase.write`. This works through :func:`open`\'s *encoding* and +*errors* parameters which are interpreted just like those in :meth:`str.encode` +and :meth:`bytes.decode`. + +Reading Unicode from a file is therefore simple:: + + with open('unicode.txt', encoding='utf-8') as f: + for line in f: + print(repr(line)) + +It's also possible to open files in update mode, allowing both reading and +writing:: + + with open('test', encoding='utf-8', mode='w+') as f: + f.write('\u4500 blah blah blah\n') + f.seek(0) + print(repr(f.readline()[:1])) + +The Unicode character ``U+FEFF`` is used as a byte-order mark (BOM), and is often +written as the first character of a file in order to assist with autodetection +of the file's byte ordering. Some encodings, such as UTF-16, expect a BOM to be +present at the start of a file; when such an encoding is used, the BOM will be +automatically written as the first character and will be silently dropped when +the file is read. There are variants of these encodings, such as 'utf-16-le' +and 'utf-16-be' for little-endian and big-endian encodings, that specify one +particular byte ordering and don't skip the BOM. + +In some areas, it is also convention to use a "BOM" at the start of UTF-8 +encoded files; the name is misleading since UTF-8 is not byte-order dependent. +The mark simply announces that the file is encoded in UTF-8. For reading such +files, use the 'utf-8-sig' codec to automatically skip the mark if present. + + +Unicode filenames +----------------- + +Most of the operating systems in common use today support filenames +that contain arbitrary Unicode characters. Usually this is +implemented by converting the Unicode string into some encoding that +varies depending on the system. Today Python is converging on using +UTF-8: Python on MacOS has used UTF-8 for several versions, and Python +3.6 switched to using UTF-8 on Windows as well. On Unix systems, +there will only be a filesystem encoding if you've set the ``LANG`` or +``LC_CTYPE`` environment variables; if you haven't, the default +encoding is again UTF-8. + +The :func:`sys.getfilesystemencoding` function returns the encoding to use on +your current system, in case you want to do the encoding manually, but there's +not much reason to bother. When opening a file for reading or writing, you can +usually just provide the Unicode string as the filename, and it will be +automatically converted to the right encoding for you:: + + filename = 'filename\u4500abc' + with open(filename, 'w') as f: + f.write('blah\n') + +Functions in the :mod:`os` module such as :func:`os.stat` will also accept Unicode +filenames. + +The :func:`os.listdir` function returns filenames, which raises an issue: should it return +the Unicode version of filenames, or should it return bytes containing +the encoded versions? :func:`os.listdir` can do both, depending on whether you +provided the directory path as bytes or a Unicode string. If you pass a +Unicode string as the path, filenames will be decoded using the filesystem's +encoding and a list of Unicode strings will be returned, while passing a byte +path will return the filenames as bytes. For example, +assuming the default filesystem encoding is UTF-8, running the following +program:: + + fn = 'filename\u4500abc' + f = open(fn, 'w') + f.close() + + import os + print(os.listdir(b'.')) + print(os.listdir('.')) + +will produce the following output: + +.. code-block:: shell-session + + $ python listdir-test.py + [b'filename\xe4\x94\x80abc', ...] + ['filename\u4500abc', ...] + +The first list contains UTF-8-encoded filenames, and the second list contains +the Unicode versions. + +Note that on most occasions, you should can just stick with using +Unicode with these APIs. The bytes APIs should only be used on +systems where undecodable file names can be present; that's +pretty much only Unix systems now. + + +Tips for Writing Unicode-aware Programs +--------------------------------------- + +This section provides some suggestions on writing software that deals with +Unicode. + +The most important tip is: + + Software should only work with Unicode strings internally, decoding the input + data as soon as possible and encoding the output only at the end. + +If you attempt to write processing functions that accept both Unicode and byte +strings, you will find your program vulnerable to bugs wherever you combine the +two different kinds of strings. There is no automatic encoding or decoding: if +you do e.g. ``str + bytes``, a :exc:`TypeError` will be raised. + +When using data coming from a web browser or some other untrusted source, a +common technique is to check for illegal characters in a string before using the +string in a generated command line or storing it in a database. If you're doing +this, be careful to check the decoded string, not the encoded bytes data; +some encodings may have interesting properties, such as not being bijective +or not being fully ASCII-compatible. This is especially true if the input +data also specifies the encoding, since the attacker can then choose a +clever way to hide malicious text in the encoded bytestream. + + +Converting Between File Encodings +''''''''''''''''''''''''''''''''' + +The :class:`~codecs.StreamRecoder` class can transparently convert between +encodings, taking a stream that returns data in encoding #1 +and behaving like a stream returning data in encoding #2. + +For example, if you have an input file *f* that's in Latin-1, you +can wrap it with a :class:`~codecs.StreamRecoder` to return bytes encoded in +UTF-8:: + + new_f = codecs.StreamRecoder(f, + # en/decoder: used by read() to encode its results and + # by write() to decode its input. + codecs.getencoder('utf-8'), codecs.getdecoder('utf-8'), + + # reader/writer: used to read and write to the stream. + codecs.getreader('latin-1'), codecs.getwriter('latin-1') ) + + +Files in an Unknown Encoding +'''''''''''''''''''''''''''' + +What can you do if you need to make a change to a file, but don't know +the file's encoding? If you know the encoding is ASCII-compatible and +only want to examine or modify the ASCII parts, you can open the file +with the ``surrogateescape`` error handler:: + + with open(fname, 'r', encoding="ascii", errors="surrogateescape") as f: + data = f.read() + + # make changes to the string 'data' + + with open(fname + '.new', 'w', + encoding="ascii", errors="surrogateescape") as f: + f.write(data) + +The ``surrogateescape`` error handler will decode any non-ASCII bytes +as code points in a special range running from U+DC80 to +U+DCFF. These code points will then turn back into the +same bytes when the ``surrogateescape`` error handler is used to +encode the data and write it back out. + + +References +---------- + +One section of `Mastering Python 3 Input/Output +`_, +a PyCon 2010 talk by David Beazley, discusses text processing and binary data handling. + +The `PDF slides for Marc-André Lemburg's presentation "Writing Unicode-aware +Applications in Python" +`_ +discuss questions of character encodings as well as how to internationalize +and localize an application. These slides cover Python 2.x only. + +`The Guts of Unicode in Python +`_ +is a PyCon 2013 talk by Benjamin Peterson that discusses the internal Unicode +representation in Python 3.3. + + +Acknowledgements +================ + +The initial draft of this document was written by Andrew Kuchling. +It has since been revised further by Alexander Belopolsky, Georg Brandl, +Andrew Kuchling, and Ezio Melotti. + +Thanks to the following people who have noted errors or offered +suggestions on this article: Éric Araujo, Nicholas Bastin, Nick +Coghlan, Marius Gedminas, Kent Johnson, Ken Krugler, Marc-André +Lemburg, Martin von Löwis, Terry J. Reedy, Serhiy Storchaka, +Eryk Sun, Chad Whitacre, Graham Wideman. diff --git a/cpython_2/environment/repo/Doc/howto/urllib2.rst b/cpython_2/environment/repo/Doc/howto/urllib2.rst new file mode 100644 index 0000000000000000000000000000000000000000..046a88af62f0b3e31ddb2ce9cfc69642cc9cf366 --- /dev/null +++ b/cpython_2/environment/repo/Doc/howto/urllib2.rst @@ -0,0 +1,605 @@ +.. _urllib-howto: + +*********************************************************** + HOWTO Fetch Internet Resources Using The urllib Package +*********************************************************** + +:Author: `Michael Foord `_ + +.. note:: + + There is a French translation of an earlier revision of this + HOWTO, available at `urllib2 - Le Manuel manquant + `_. + + + +Introduction +============ + +.. sidebar:: Related Articles + + You may also find useful the following article on fetching web resources + with Python: + + * `Basic Authentication `_ + + A tutorial on *Basic Authentication*, with examples in Python. + +**urllib.request** is a Python module for fetching URLs +(Uniform Resource Locators). It offers a very simple interface, in the form of +the *urlopen* function. This is capable of fetching URLs using a variety of +different protocols. It also offers a slightly more complex interface for +handling common situations - like basic authentication, cookies, proxies and so +on. These are provided by objects called handlers and openers. + +urllib.request supports fetching URLs for many "URL schemes" (identified by the string +before the ``":"`` in URL - for example ``"ftp"`` is the URL scheme of +``"ftp://python.org/"``) using their associated network protocols (e.g. FTP, HTTP). +This tutorial focuses on the most common case, HTTP. + +For straightforward situations *urlopen* is very easy to use. But as soon as you +encounter errors or non-trivial cases when opening HTTP URLs, you will need some +understanding of the HyperText Transfer Protocol. The most comprehensive and +authoritative reference to HTTP is :rfc:`2616`. This is a technical document and +not intended to be easy to read. This HOWTO aims to illustrate using *urllib*, +with enough detail about HTTP to help you through. It is not intended to replace +the :mod:`urllib.request` docs, but is supplementary to them. + + +Fetching URLs +============= + +The simplest way to use urllib.request is as follows:: + + import urllib.request + with urllib.request.urlopen('http://python.org/') as response: + html = response.read() + +If you wish to retrieve a resource via URL and store it in a temporary +location, you can do so via the :func:`shutil.copyfileobj` and +:func:`tempfile.NamedTemporaryFile` functions:: + + import shutil + import tempfile + import urllib.request + + with urllib.request.urlopen('http://python.org/') as response: + with tempfile.NamedTemporaryFile(delete=False) as tmp_file: + shutil.copyfileobj(response, tmp_file) + + with open(tmp_file.name) as html: + pass + +Many uses of urllib will be that simple (note that instead of an 'http:' URL we +could have used a URL starting with 'ftp:', 'file:', etc.). However, it's the +purpose of this tutorial to explain the more complicated cases, concentrating on +HTTP. + +HTTP is based on requests and responses - the client makes requests and servers +send responses. urllib.request mirrors this with a ``Request`` object which represents +the HTTP request you are making. In its simplest form you create a Request +object that specifies the URL you want to fetch. Calling ``urlopen`` with this +Request object returns a response object for the URL requested. This response is +a file-like object, which means you can for example call ``.read()`` on the +response:: + + import urllib.request + + req = urllib.request.Request('http://www.voidspace.org.uk') + with urllib.request.urlopen(req) as response: + the_page = response.read() + +Note that urllib.request makes use of the same Request interface to handle all URL +schemes. For example, you can make an FTP request like so:: + + req = urllib.request.Request('ftp://example.com/') + +In the case of HTTP, there are two extra things that Request objects allow you +to do: First, you can pass data to be sent to the server. Second, you can pass +extra information ("metadata") *about* the data or the about request itself, to +the server - this information is sent as HTTP "headers". Let's look at each of +these in turn. + +Data +---- + +Sometimes you want to send data to a URL (often the URL will refer to a CGI +(Common Gateway Interface) script or other web application). With HTTP, +this is often done using what's known as a **POST** request. This is often what +your browser does when you submit a HTML form that you filled in on the web. Not +all POSTs have to come from forms: you can use a POST to transmit arbitrary data +to your own application. In the common case of HTML forms, the data needs to be +encoded in a standard way, and then passed to the Request object as the ``data`` +argument. The encoding is done using a function from the :mod:`urllib.parse` +library. :: + + import urllib.parse + import urllib.request + + url = 'http://www.someserver.com/cgi-bin/register.cgi' + values = {'name' : 'Michael Foord', + 'location' : 'Northampton', + 'language' : 'Python' } + + data = urllib.parse.urlencode(values) + data = data.encode('ascii') # data should be bytes + req = urllib.request.Request(url, data) + with urllib.request.urlopen(req) as response: + the_page = response.read() + +Note that other encodings are sometimes required (e.g. for file upload from HTML +forms - see `HTML Specification, Form Submission +`_ for more +details). + +If you do not pass the ``data`` argument, urllib uses a **GET** request. One +way in which GET and POST requests differ is that POST requests often have +"side-effects": they change the state of the system in some way (for example by +placing an order with the website for a hundredweight of tinned spam to be +delivered to your door). Though the HTTP standard makes it clear that POSTs are +intended to *always* cause side-effects, and GET requests *never* to cause +side-effects, nothing prevents a GET request from having side-effects, nor a +POST requests from having no side-effects. Data can also be passed in an HTTP +GET request by encoding it in the URL itself. + +This is done as follows:: + + >>> import urllib.request + >>> import urllib.parse + >>> data = {} + >>> data['name'] = 'Somebody Here' + >>> data['location'] = 'Northampton' + >>> data['language'] = 'Python' + >>> url_values = urllib.parse.urlencode(data) + >>> print(url_values) # The order may differ from below. #doctest: +SKIP + name=Somebody+Here&language=Python&location=Northampton + >>> url = 'http://www.example.com/example.cgi' + >>> full_url = url + '?' + url_values + >>> data = urllib.request.urlopen(full_url) + +Notice that the full URL is created by adding a ``?`` to the URL, followed by +the encoded values. + +Headers +------- + +We'll discuss here one particular HTTP header, to illustrate how to add headers +to your HTTP request. + +Some websites [#]_ dislike being browsed by programs, or send different versions +to different browsers [#]_. By default urllib identifies itself as +``Python-urllib/x.y`` (where ``x`` and ``y`` are the major and minor version +numbers of the Python release, +e.g. ``Python-urllib/2.5``), which may confuse the site, or just plain +not work. The way a browser identifies itself is through the +``User-Agent`` header [#]_. When you create a Request object you can +pass a dictionary of headers in. The following example makes the same +request as above, but identifies itself as a version of Internet +Explorer [#]_. :: + + import urllib.parse + import urllib.request + + url = 'http://www.someserver.com/cgi-bin/register.cgi' + user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)' + values = {'name': 'Michael Foord', + 'location': 'Northampton', + 'language': 'Python' } + headers = {'User-Agent': user_agent} + + data = urllib.parse.urlencode(values) + data = data.encode('ascii') + req = urllib.request.Request(url, data, headers) + with urllib.request.urlopen(req) as response: + the_page = response.read() + +The response also has two useful methods. See the section on `info and geturl`_ +which comes after we have a look at what happens when things go wrong. + + +Handling Exceptions +=================== + +*urlopen* raises :exc:`URLError` when it cannot handle a response (though as +usual with Python APIs, built-in exceptions such as :exc:`ValueError`, +:exc:`TypeError` etc. may also be raised). + +:exc:`HTTPError` is the subclass of :exc:`URLError` raised in the specific case of +HTTP URLs. + +The exception classes are exported from the :mod:`urllib.error` module. + +URLError +-------- + +Often, URLError is raised because there is no network connection (no route to +the specified server), or the specified server doesn't exist. In this case, the +exception raised will have a 'reason' attribute, which is a tuple containing an +error code and a text error message. + +e.g. :: + + >>> req = urllib.request.Request('http://www.pretend_server.org') + >>> try: urllib.request.urlopen(req) + ... except urllib.error.URLError as e: + ... print(e.reason) #doctest: +SKIP + ... + (4, 'getaddrinfo failed') + + +HTTPError +--------- + +Every HTTP response from the server contains a numeric "status code". Sometimes +the status code indicates that the server is unable to fulfil the request. The +default handlers will handle some of these responses for you (for example, if +the response is a "redirection" that requests the client fetch the document from +a different URL, urllib will handle that for you). For those it can't handle, +urlopen will raise an :exc:`HTTPError`. Typical errors include '404' (page not +found), '403' (request forbidden), and '401' (authentication required). + +See section 10 of :rfc:`2616` for a reference on all the HTTP error codes. + +The :exc:`HTTPError` instance raised will have an integer 'code' attribute, which +corresponds to the error sent by the server. + +Error Codes +~~~~~~~~~~~ + +Because the default handlers handle redirects (codes in the 300 range), and +codes in the 100--299 range indicate success, you will usually only see error +codes in the 400--599 range. + +:attr:`http.server.BaseHTTPRequestHandler.responses` is a useful dictionary of +response codes in that shows all the response codes used by :rfc:`2616`. The +dictionary is reproduced here for convenience :: + + # Table mapping response codes to messages; entries have the + # form {code: (shortmessage, longmessage)}. + responses = { + 100: ('Continue', 'Request received, please continue'), + 101: ('Switching Protocols', + 'Switching to new protocol; obey Upgrade header'), + + 200: ('OK', 'Request fulfilled, document follows'), + 201: ('Created', 'Document created, URL follows'), + 202: ('Accepted', + 'Request accepted, processing continues off-line'), + 203: ('Non-Authoritative Information', 'Request fulfilled from cache'), + 204: ('No Content', 'Request fulfilled, nothing follows'), + 205: ('Reset Content', 'Clear input form for further input.'), + 206: ('Partial Content', 'Partial content follows.'), + + 300: ('Multiple Choices', + 'Object has several resources -- see URI list'), + 301: ('Moved Permanently', 'Object moved permanently -- see URI list'), + 302: ('Found', 'Object moved temporarily -- see URI list'), + 303: ('See Other', 'Object moved -- see Method and URL list'), + 304: ('Not Modified', + 'Document has not changed since given time'), + 305: ('Use Proxy', + 'You must use proxy specified in Location to access this ' + 'resource.'), + 307: ('Temporary Redirect', + 'Object moved temporarily -- see URI list'), + + 400: ('Bad Request', + 'Bad request syntax or unsupported method'), + 401: ('Unauthorized', + 'No permission -- see authorization schemes'), + 402: ('Payment Required', + 'No payment -- see charging schemes'), + 403: ('Forbidden', + 'Request forbidden -- authorization will not help'), + 404: ('Not Found', 'Nothing matches the given URI'), + 405: ('Method Not Allowed', + 'Specified method is invalid for this server.'), + 406: ('Not Acceptable', 'URI not available in preferred format.'), + 407: ('Proxy Authentication Required', 'You must authenticate with ' + 'this proxy before proceeding.'), + 408: ('Request Timeout', 'Request timed out; try again later.'), + 409: ('Conflict', 'Request conflict.'), + 410: ('Gone', + 'URI no longer exists and has been permanently removed.'), + 411: ('Length Required', 'Client must specify Content-Length.'), + 412: ('Precondition Failed', 'Precondition in headers is false.'), + 413: ('Request Entity Too Large', 'Entity is too large.'), + 414: ('Request-URI Too Long', 'URI is too long.'), + 415: ('Unsupported Media Type', 'Entity body in unsupported format.'), + 416: ('Requested Range Not Satisfiable', + 'Cannot satisfy request range.'), + 417: ('Expectation Failed', + 'Expect condition could not be satisfied.'), + + 500: ('Internal Server Error', 'Server got itself in trouble'), + 501: ('Not Implemented', + 'Server does not support this operation'), + 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'), + 503: ('Service Unavailable', + 'The server cannot process the request due to a high load'), + 504: ('Gateway Timeout', + 'The gateway server did not receive a timely response'), + 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'), + } + +When an error is raised the server responds by returning an HTTP error code +*and* an error page. You can use the :exc:`HTTPError` instance as a response on the +page returned. This means that as well as the code attribute, it also has read, +geturl, and info, methods as returned by the ``urllib.response`` module:: + + >>> req = urllib.request.Request('http://www.python.org/fish.html') + >>> try: + ... urllib.request.urlopen(req) + ... except urllib.error.HTTPError as e: + ... print(e.code) + ... print(e.read()) #doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE + ... + 404 + b'\n\n\nPage Not Found\n + ... + +Wrapping it Up +-------------- + +So if you want to be prepared for :exc:`HTTPError` *or* :exc:`URLError` there are two +basic approaches. I prefer the second approach. + +Number 1 +~~~~~~~~ + +:: + + + from urllib.request import Request, urlopen + from urllib.error import URLError, HTTPError + req = Request(someurl) + try: + response = urlopen(req) + except HTTPError as e: + print('The server couldn\'t fulfill the request.') + print('Error code: ', e.code) + except URLError as e: + print('We failed to reach a server.') + print('Reason: ', e.reason) + else: + # everything is fine + + +.. note:: + + The ``except HTTPError`` *must* come first, otherwise ``except URLError`` + will *also* catch an :exc:`HTTPError`. + +Number 2 +~~~~~~~~ + +:: + + from urllib.request import Request, urlopen + from urllib.error import URLError + req = Request(someurl) + try: + response = urlopen(req) + except URLError as e: + if hasattr(e, 'reason'): + print('We failed to reach a server.') + print('Reason: ', e.reason) + elif hasattr(e, 'code'): + print('The server couldn\'t fulfill the request.') + print('Error code: ', e.code) + else: + # everything is fine + + +info and geturl +=============== + +The response returned by urlopen (or the :exc:`HTTPError` instance) has two +useful methods :meth:`info` and :meth:`geturl` and is defined in the module +:mod:`urllib.response`.. + +**geturl** - this returns the real URL of the page fetched. This is useful +because ``urlopen`` (or the opener object used) may have followed a +redirect. The URL of the page fetched may not be the same as the URL requested. + +**info** - this returns a dictionary-like object that describes the page +fetched, particularly the headers sent by the server. It is currently an +:class:`http.client.HTTPMessage` instance. + +Typical headers include 'Content-length', 'Content-type', and so on. See the +`Quick Reference to HTTP Headers `_ +for a useful listing of HTTP headers with brief explanations of their meaning +and use. + + +Openers and Handlers +==================== + +When you fetch a URL you use an opener (an instance of the perhaps +confusingly-named :class:`urllib.request.OpenerDirector`). Normally we have been using +the default opener - via ``urlopen`` - but you can create custom +openers. Openers use handlers. All the "heavy lifting" is done by the +handlers. Each handler knows how to open URLs for a particular URL scheme (http, +ftp, etc.), or how to handle an aspect of URL opening, for example HTTP +redirections or HTTP cookies. + +You will want to create openers if you want to fetch URLs with specific handlers +installed, for example to get an opener that handles cookies, or to get an +opener that does not handle redirections. + +To create an opener, instantiate an ``OpenerDirector``, and then call +``.add_handler(some_handler_instance)`` repeatedly. + +Alternatively, you can use ``build_opener``, which is a convenience function for +creating opener objects with a single function call. ``build_opener`` adds +several handlers by default, but provides a quick way to add more and/or +override the default handlers. + +Other sorts of handlers you might want to can handle proxies, authentication, +and other common but slightly specialised situations. + +``install_opener`` can be used to make an ``opener`` object the (global) default +opener. This means that calls to ``urlopen`` will use the opener you have +installed. + +Opener objects have an ``open`` method, which can be called directly to fetch +urls in the same way as the ``urlopen`` function: there's no need to call +``install_opener``, except as a convenience. + + +Basic Authentication +==================== + +To illustrate creating and installing a handler we will use the +``HTTPBasicAuthHandler``. For a more detailed discussion of this subject -- +including an explanation of how Basic Authentication works - see the `Basic +Authentication Tutorial +`_. + +When authentication is required, the server sends a header (as well as the 401 +error code) requesting authentication. This specifies the authentication scheme +and a 'realm'. The header looks like: ``WWW-Authenticate: SCHEME +realm="REALM"``. + +e.g. + +.. code-block:: none + + WWW-Authenticate: Basic realm="cPanel Users" + + +The client should then retry the request with the appropriate name and password +for the realm included as a header in the request. This is 'basic +authentication'. In order to simplify this process we can create an instance of +``HTTPBasicAuthHandler`` and an opener to use this handler. + +The ``HTTPBasicAuthHandler`` uses an object called a password manager to handle +the mapping of URLs and realms to passwords and usernames. If you know what the +realm is (from the authentication header sent by the server), then you can use a +``HTTPPasswordMgr``. Frequently one doesn't care what the realm is. In that +case, it is convenient to use ``HTTPPasswordMgrWithDefaultRealm``. This allows +you to specify a default username and password for a URL. This will be supplied +in the absence of you providing an alternative combination for a specific +realm. We indicate this by providing ``None`` as the realm argument to the +``add_password`` method. + +The top-level URL is the first URL that requires authentication. URLs "deeper" +than the URL you pass to .add_password() will also match. :: + + # create a password manager + password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm() + + # Add the username and password. + # If we knew the realm, we could use it instead of None. + top_level_url = "http://example.com/foo/" + password_mgr.add_password(None, top_level_url, username, password) + + handler = urllib.request.HTTPBasicAuthHandler(password_mgr) + + # create "opener" (OpenerDirector instance) + opener = urllib.request.build_opener(handler) + + # use the opener to fetch a URL + opener.open(a_url) + + # Install the opener. + # Now all calls to urllib.request.urlopen use our opener. + urllib.request.install_opener(opener) + +.. note:: + + In the above example we only supplied our ``HTTPBasicAuthHandler`` to + ``build_opener``. By default openers have the handlers for normal situations + -- ``ProxyHandler`` (if a proxy setting such as an :envvar:`http_proxy` + environment variable is set), ``UnknownHandler``, ``HTTPHandler``, + ``HTTPDefaultErrorHandler``, ``HTTPRedirectHandler``, ``FTPHandler``, + ``FileHandler``, ``DataHandler``, ``HTTPErrorProcessor``. + +``top_level_url`` is in fact *either* a full URL (including the 'http:' scheme +component and the hostname and optionally the port number) +e.g. ``"http://example.com/"`` *or* an "authority" (i.e. the hostname, +optionally including the port number) e.g. ``"example.com"`` or ``"example.com:8080"`` +(the latter example includes a port number). The authority, if present, must +NOT contain the "userinfo" component - for example ``"joe:password@example.com"`` is +not correct. + + +Proxies +======= + +**urllib** will auto-detect your proxy settings and use those. This is through +the ``ProxyHandler``, which is part of the normal handler chain when a proxy +setting is detected. Normally that's a good thing, but there are occasions +when it may not be helpful [#]_. One way to do this is to setup our own +``ProxyHandler``, with no proxies defined. This is done using similar steps to +setting up a `Basic Authentication`_ handler: :: + + >>> proxy_support = urllib.request.ProxyHandler({}) + >>> opener = urllib.request.build_opener(proxy_support) + >>> urllib.request.install_opener(opener) + +.. note:: + + Currently ``urllib.request`` *does not* support fetching of ``https`` locations + through a proxy. However, this can be enabled by extending urllib.request as + shown in the recipe [#]_. + +.. note:: + + ``HTTP_PROXY`` will be ignored if a variable ``REQUEST_METHOD`` is set; see + the documentation on :func:`~urllib.request.getproxies`. + + +Sockets and Layers +================== + +The Python support for fetching resources from the web is layered. urllib uses +the :mod:`http.client` library, which in turn uses the socket library. + +As of Python 2.3 you can specify how long a socket should wait for a response +before timing out. This can be useful in applications which have to fetch web +pages. By default the socket module has *no timeout* and can hang. Currently, +the socket timeout is not exposed at the http.client or urllib.request levels. +However, you can set the default timeout globally for all sockets using :: + + import socket + import urllib.request + + # timeout in seconds + timeout = 10 + socket.setdefaulttimeout(timeout) + + # this call to urllib.request.urlopen now uses the default timeout + # we have set in the socket module + req = urllib.request.Request('http://www.voidspace.org.uk') + response = urllib.request.urlopen(req) + + +------- + + +Footnotes +========= + +This document was reviewed and revised by John Lee. + +.. [#] Google for example. +.. [#] Browser sniffing is a very bad practice for website design - building + sites using web standards is much more sensible. Unfortunately a lot of + sites still send different versions to different browsers. +.. [#] The user agent for MSIE 6 is + *'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)'* +.. [#] For details of more HTTP request headers, see + `Quick Reference to HTTP Headers`_. +.. [#] In my case I have to use a proxy to access the internet at work. If you + attempt to fetch *localhost* URLs through this proxy it blocks them. IE + is set to use the proxy, which urllib picks up on. In order to test + scripts with a localhost server, I have to prevent urllib from using + the proxy. +.. [#] urllib opener for SSL proxy (CONNECT method): `ASPN Cookbook Recipe + `_. + diff --git a/cpython_2/environment/repo/Doc/includes/custom.c b/cpython_2/environment/repo/Doc/includes/custom.c new file mode 100644 index 0000000000000000000000000000000000000000..f361baf830dd1b3c9a0b644479683b4f884affd5 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/custom.c @@ -0,0 +1,45 @@ +#define PY_SSIZE_T_CLEAN +#include + +typedef struct { + PyObject_HEAD + /* Type-specific fields go here. */ +} CustomObject; + +static PyTypeObject CustomType = { + PyVarObject_HEAD_INIT(NULL, 0) + .tp_name = "custom.Custom", + .tp_doc = "Custom objects", + .tp_basicsize = sizeof(CustomObject), + .tp_itemsize = 0, + .tp_flags = Py_TPFLAGS_DEFAULT, + .tp_new = PyType_GenericNew, +}; + +static PyModuleDef custommodule = { + PyModuleDef_HEAD_INIT, + .m_name = "custom", + .m_doc = "Example module that creates an extension type.", + .m_size = -1, +}; + +PyMODINIT_FUNC +PyInit_custom(void) +{ + PyObject *m; + if (PyType_Ready(&CustomType) < 0) + return NULL; + + m = PyModule_Create(&custommodule); + if (m == NULL) + return NULL; + + Py_INCREF(&CustomType); + if (PyModule_AddObject(m, "Custom", (PyObject *) &CustomType) < 0) { + Py_DECREF(&CustomType); + Py_DECREF(m); + return NULL; + } + + return m; +} diff --git a/cpython_2/environment/repo/Doc/includes/custom2.c b/cpython_2/environment/repo/Doc/includes/custom2.c new file mode 100644 index 0000000000000000000000000000000000000000..5bacab7a2a9714c1cfb52bf6c6891c8983e346ac --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/custom2.c @@ -0,0 +1,138 @@ +#define PY_SSIZE_T_CLEAN +#include +#include "structmember.h" + +typedef struct { + PyObject_HEAD + PyObject *first; /* first name */ + PyObject *last; /* last name */ + int number; +} CustomObject; + +static void +Custom_dealloc(CustomObject *self) +{ + Py_XDECREF(self->first); + Py_XDECREF(self->last); + Py_TYPE(self)->tp_free((PyObject *) self); +} + +static PyObject * +Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +{ + CustomObject *self; + self = (CustomObject *) type->tp_alloc(type, 0); + if (self != NULL) { + self->first = PyUnicode_FromString(""); + if (self->first == NULL) { + Py_DECREF(self); + return NULL; + } + self->last = PyUnicode_FromString(""); + if (self->last == NULL) { + Py_DECREF(self); + return NULL; + } + self->number = 0; + } + return (PyObject *) self; +} + +static int +Custom_init(CustomObject *self, PyObject *args, PyObject *kwds) +{ + static char *kwlist[] = {"first", "last", "number", NULL}; + PyObject *first = NULL, *last = NULL, *tmp; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi", kwlist, + &first, &last, + &self->number)) + return -1; + + if (first) { + tmp = self->first; + Py_INCREF(first); + self->first = first; + Py_XDECREF(tmp); + } + if (last) { + tmp = self->last; + Py_INCREF(last); + self->last = last; + Py_XDECREF(tmp); + } + return 0; +} + +static PyMemberDef Custom_members[] = { + {"first", T_OBJECT_EX, offsetof(CustomObject, first), 0, + "first name"}, + {"last", T_OBJECT_EX, offsetof(CustomObject, last), 0, + "last name"}, + {"number", T_INT, offsetof(CustomObject, number), 0, + "custom number"}, + {NULL} /* Sentinel */ +}; + +static PyObject * +Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored)) +{ + if (self->first == NULL) { + PyErr_SetString(PyExc_AttributeError, "first"); + return NULL; + } + if (self->last == NULL) { + PyErr_SetString(PyExc_AttributeError, "last"); + return NULL; + } + return PyUnicode_FromFormat("%S %S", self->first, self->last); +} + +static PyMethodDef Custom_methods[] = { + {"name", (PyCFunction) Custom_name, METH_NOARGS, + "Return the name, combining the first and last name" + }, + {NULL} /* Sentinel */ +}; + +static PyTypeObject CustomType = { + PyVarObject_HEAD_INIT(NULL, 0) + .tp_name = "custom2.Custom", + .tp_doc = "Custom objects", + .tp_basicsize = sizeof(CustomObject), + .tp_itemsize = 0, + .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, + .tp_new = Custom_new, + .tp_init = (initproc) Custom_init, + .tp_dealloc = (destructor) Custom_dealloc, + .tp_members = Custom_members, + .tp_methods = Custom_methods, +}; + +static PyModuleDef custommodule = { + PyModuleDef_HEAD_INIT, + .m_name = "custom2", + .m_doc = "Example module that creates an extension type.", + .m_size = -1, +}; + +PyMODINIT_FUNC +PyInit_custom2(void) +{ + PyObject *m; + if (PyType_Ready(&CustomType) < 0) + return NULL; + + m = PyModule_Create(&custommodule); + if (m == NULL) + return NULL; + + Py_INCREF(&CustomType); + if (PyModule_AddObject(m, "Custom", (PyObject *) &CustomType) < 0) { + Py_DECREF(&CustomType); + Py_DECREF(m); + return NULL; + } + + return m; +} diff --git a/cpython_2/environment/repo/Doc/includes/custom3.c b/cpython_2/environment/repo/Doc/includes/custom3.c new file mode 100644 index 0000000000000000000000000000000000000000..2b7a99ecf96c76be835db308ace6a5d7cd2a35a0 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/custom3.c @@ -0,0 +1,189 @@ +#define PY_SSIZE_T_CLEAN +#include +#include "structmember.h" + +typedef struct { + PyObject_HEAD + PyObject *first; /* first name */ + PyObject *last; /* last name */ + int number; +} CustomObject; + +static void +Custom_dealloc(CustomObject *self) +{ + Py_XDECREF(self->first); + Py_XDECREF(self->last); + Py_TYPE(self)->tp_free((PyObject *) self); +} + +static PyObject * +Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +{ + CustomObject *self; + self = (CustomObject *) type->tp_alloc(type, 0); + if (self != NULL) { + self->first = PyUnicode_FromString(""); + if (self->first == NULL) { + Py_DECREF(self); + return NULL; + } + self->last = PyUnicode_FromString(""); + if (self->last == NULL) { + Py_DECREF(self); + return NULL; + } + self->number = 0; + } + return (PyObject *) self; +} + +static int +Custom_init(CustomObject *self, PyObject *args, PyObject *kwds) +{ + static char *kwlist[] = {"first", "last", "number", NULL}; + PyObject *first = NULL, *last = NULL, *tmp; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|UUi", kwlist, + &first, &last, + &self->number)) + return -1; + + if (first) { + tmp = self->first; + Py_INCREF(first); + self->first = first; + Py_DECREF(tmp); + } + if (last) { + tmp = self->last; + Py_INCREF(last); + self->last = last; + Py_DECREF(tmp); + } + return 0; +} + +static PyMemberDef Custom_members[] = { + {"number", T_INT, offsetof(CustomObject, number), 0, + "custom number"}, + {NULL} /* Sentinel */ +}; + +static PyObject * +Custom_getfirst(CustomObject *self, void *closure) +{ + Py_INCREF(self->first); + return self->first; +} + +static int +Custom_setfirst(CustomObject *self, PyObject *value, void *closure) +{ + PyObject *tmp; + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, "Cannot delete the first attribute"); + return -1; + } + if (!PyUnicode_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "The first attribute value must be a string"); + return -1; + } + tmp = self->first; + Py_INCREF(value); + self->first = value; + Py_DECREF(tmp); + return 0; +} + +static PyObject * +Custom_getlast(CustomObject *self, void *closure) +{ + Py_INCREF(self->last); + return self->last; +} + +static int +Custom_setlast(CustomObject *self, PyObject *value, void *closure) +{ + PyObject *tmp; + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, "Cannot delete the last attribute"); + return -1; + } + if (!PyUnicode_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "The last attribute value must be a string"); + return -1; + } + tmp = self->last; + Py_INCREF(value); + self->last = value; + Py_DECREF(tmp); + return 0; +} + +static PyGetSetDef Custom_getsetters[] = { + {"first", (getter) Custom_getfirst, (setter) Custom_setfirst, + "first name", NULL}, + {"last", (getter) Custom_getlast, (setter) Custom_setlast, + "last name", NULL}, + {NULL} /* Sentinel */ +}; + +static PyObject * +Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored)) +{ + return PyUnicode_FromFormat("%S %S", self->first, self->last); +} + +static PyMethodDef Custom_methods[] = { + {"name", (PyCFunction) Custom_name, METH_NOARGS, + "Return the name, combining the first and last name" + }, + {NULL} /* Sentinel */ +}; + +static PyTypeObject CustomType = { + PyVarObject_HEAD_INIT(NULL, 0) + .tp_name = "custom3.Custom", + .tp_doc = "Custom objects", + .tp_basicsize = sizeof(CustomObject), + .tp_itemsize = 0, + .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, + .tp_new = Custom_new, + .tp_init = (initproc) Custom_init, + .tp_dealloc = (destructor) Custom_dealloc, + .tp_members = Custom_members, + .tp_methods = Custom_methods, + .tp_getset = Custom_getsetters, +}; + +static PyModuleDef custommodule = { + PyModuleDef_HEAD_INIT, + .m_name = "custom3", + .m_doc = "Example module that creates an extension type.", + .m_size = -1, +}; + +PyMODINIT_FUNC +PyInit_custom3(void) +{ + PyObject *m; + if (PyType_Ready(&CustomType) < 0) + return NULL; + + m = PyModule_Create(&custommodule); + if (m == NULL) + return NULL; + + Py_INCREF(&CustomType); + if (PyModule_AddObject(m, "Custom", (PyObject *) &CustomType) < 0) { + Py_DECREF(&CustomType); + Py_DECREF(m); + return NULL; + } + + return m; +} diff --git a/cpython_2/environment/repo/Doc/includes/custom4.c b/cpython_2/environment/repo/Doc/includes/custom4.c new file mode 100644 index 0000000000000000000000000000000000000000..584992fc5f1a8a7a69585ff64f7252b5d5cee6b4 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/custom4.c @@ -0,0 +1,203 @@ +#define PY_SSIZE_T_CLEAN +#include +#include "structmember.h" + +typedef struct { + PyObject_HEAD + PyObject *first; /* first name */ + PyObject *last; /* last name */ + int number; +} CustomObject; + +static int +Custom_traverse(CustomObject *self, visitproc visit, void *arg) +{ + Py_VISIT(self->first); + Py_VISIT(self->last); + return 0; +} + +static int +Custom_clear(CustomObject *self) +{ + Py_CLEAR(self->first); + Py_CLEAR(self->last); + return 0; +} + +static void +Custom_dealloc(CustomObject *self) +{ + PyObject_GC_UnTrack(self); + Custom_clear(self); + Py_TYPE(self)->tp_free((PyObject *) self); +} + +static PyObject * +Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +{ + CustomObject *self; + self = (CustomObject *) type->tp_alloc(type, 0); + if (self != NULL) { + self->first = PyUnicode_FromString(""); + if (self->first == NULL) { + Py_DECREF(self); + return NULL; + } + self->last = PyUnicode_FromString(""); + if (self->last == NULL) { + Py_DECREF(self); + return NULL; + } + self->number = 0; + } + return (PyObject *) self; +} + +static int +Custom_init(CustomObject *self, PyObject *args, PyObject *kwds) +{ + static char *kwlist[] = {"first", "last", "number", NULL}; + PyObject *first = NULL, *last = NULL, *tmp; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|UUi", kwlist, + &first, &last, + &self->number)) + return -1; + + if (first) { + tmp = self->first; + Py_INCREF(first); + self->first = first; + Py_DECREF(tmp); + } + if (last) { + tmp = self->last; + Py_INCREF(last); + self->last = last; + Py_DECREF(tmp); + } + return 0; +} + +static PyMemberDef Custom_members[] = { + {"number", T_INT, offsetof(CustomObject, number), 0, + "custom number"}, + {NULL} /* Sentinel */ +}; + +static PyObject * +Custom_getfirst(CustomObject *self, void *closure) +{ + Py_INCREF(self->first); + return self->first; +} + +static int +Custom_setfirst(CustomObject *self, PyObject *value, void *closure) +{ + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, "Cannot delete the first attribute"); + return -1; + } + if (!PyUnicode_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "The first attribute value must be a string"); + return -1; + } + Py_INCREF(value); + Py_CLEAR(self->first); + self->first = value; + return 0; +} + +static PyObject * +Custom_getlast(CustomObject *self, void *closure) +{ + Py_INCREF(self->last); + return self->last; +} + +static int +Custom_setlast(CustomObject *self, PyObject *value, void *closure) +{ + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, "Cannot delete the last attribute"); + return -1; + } + if (!PyUnicode_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "The last attribute value must be a string"); + return -1; + } + Py_INCREF(value); + Py_CLEAR(self->last); + self->last = value; + return 0; +} + +static PyGetSetDef Custom_getsetters[] = { + {"first", (getter) Custom_getfirst, (setter) Custom_setfirst, + "first name", NULL}, + {"last", (getter) Custom_getlast, (setter) Custom_setlast, + "last name", NULL}, + {NULL} /* Sentinel */ +}; + +static PyObject * +Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored)) +{ + return PyUnicode_FromFormat("%S %S", self->first, self->last); +} + +static PyMethodDef Custom_methods[] = { + {"name", (PyCFunction) Custom_name, METH_NOARGS, + "Return the name, combining the first and last name" + }, + {NULL} /* Sentinel */ +}; + +static PyTypeObject CustomType = { + PyVarObject_HEAD_INIT(NULL, 0) + .tp_name = "custom4.Custom", + .tp_doc = "Custom objects", + .tp_basicsize = sizeof(CustomObject), + .tp_itemsize = 0, + .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, + .tp_new = Custom_new, + .tp_init = (initproc) Custom_init, + .tp_dealloc = (destructor) Custom_dealloc, + .tp_traverse = (traverseproc) Custom_traverse, + .tp_clear = (inquiry) Custom_clear, + .tp_members = Custom_members, + .tp_methods = Custom_methods, + .tp_getset = Custom_getsetters, +}; + +static PyModuleDef custommodule = { + PyModuleDef_HEAD_INIT, + .m_name = "custom4", + .m_doc = "Example module that creates an extension type.", + .m_size = -1, +}; + +PyMODINIT_FUNC +PyInit_custom4(void) +{ + PyObject *m; + if (PyType_Ready(&CustomType) < 0) + return NULL; + + m = PyModule_Create(&custommodule); + if (m == NULL) + return NULL; + + Py_INCREF(&CustomType); + if (PyModule_AddObject(m, "Custom", (PyObject *) &CustomType) < 0) { + Py_DECREF(&CustomType); + Py_DECREF(m); + return NULL; + } + + return m; +} diff --git a/cpython_2/environment/repo/Doc/includes/dbpickle.py b/cpython_2/environment/repo/Doc/includes/dbpickle.py new file mode 100644 index 0000000000000000000000000000000000000000..b88ee87d872ab4580500c7d132a372f5dbb61183 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/dbpickle.py @@ -0,0 +1,87 @@ +# Simple example presenting how persistent ID can be used to pickle +# external objects by reference. + +import pickle +import sqlite3 +from collections import namedtuple + +# Simple class representing a record in our database. +MemoRecord = namedtuple("MemoRecord", "key, task") + +class DBPickler(pickle.Pickler): + + def persistent_id(self, obj): + # Instead of pickling MemoRecord as a regular class instance, we emit a + # persistent ID. + if isinstance(obj, MemoRecord): + # Here, our persistent ID is simply a tuple, containing a tag and a + # key, which refers to a specific record in the database. + return ("MemoRecord", obj.key) + else: + # If obj does not have a persistent ID, return None. This means obj + # needs to be pickled as usual. + return None + + +class DBUnpickler(pickle.Unpickler): + + def __init__(self, file, connection): + super().__init__(file) + self.connection = connection + + def persistent_load(self, pid): + # This method is invoked whenever a persistent ID is encountered. + # Here, pid is the tuple returned by DBPickler. + cursor = self.connection.cursor() + type_tag, key_id = pid + if type_tag == "MemoRecord": + # Fetch the referenced record from the database and return it. + cursor.execute("SELECT * FROM memos WHERE key=?", (str(key_id),)) + key, task = cursor.fetchone() + return MemoRecord(key, task) + else: + # Always raises an error if you cannot return the correct object. + # Otherwise, the unpickler will think None is the object referenced + # by the persistent ID. + raise pickle.UnpicklingError("unsupported persistent object") + + +def main(): + import io + import pprint + + # Initialize and populate our database. + conn = sqlite3.connect(":memory:") + cursor = conn.cursor() + cursor.execute("CREATE TABLE memos(key INTEGER PRIMARY KEY, task TEXT)") + tasks = ( + 'give food to fish', + 'prepare group meeting', + 'fight with a zebra', + ) + for task in tasks: + cursor.execute("INSERT INTO memos VALUES(NULL, ?)", (task,)) + + # Fetch the records to be pickled. + cursor.execute("SELECT * FROM memos") + memos = [MemoRecord(key, task) for key, task in cursor] + # Save the records using our custom DBPickler. + file = io.BytesIO() + DBPickler(file).dump(memos) + + print("Pickled records:") + pprint.pprint(memos) + + # Update a record, just for good measure. + cursor.execute("UPDATE memos SET task='learn italian' WHERE key=1") + + # Load the records from the pickle data stream. + file.seek(0) + memos = DBUnpickler(file, conn).load() + + print("Unpickled records:") + pprint.pprint(memos) + + +if __name__ == '__main__': + main() diff --git a/cpython_2/environment/repo/Doc/includes/email-alternative.py b/cpython_2/environment/repo/Doc/includes/email-alternative.py new file mode 100644 index 0000000000000000000000000000000000000000..df7ca6f3faa332cbf28f1bcd5e82870477300bae --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/email-alternative.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python3 + +import smtplib + +from email.message import EmailMessage +from email.headerregistry import Address +from email.utils import make_msgid + +# Create the base text message. +msg = EmailMessage() +msg['Subject'] = "Ayons asperges pour le déjeuner" +msg['From'] = Address("Pepé Le Pew", "pepe", "example.com") +msg['To'] = (Address("Penelope Pussycat", "penelope", "example.com"), + Address("Fabrette Pussycat", "fabrette", "example.com")) +msg.set_content("""\ +Salut! + +Cela ressemble à un excellent recipie[1] déjeuner. + +[1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718 + +--Pepé +""") + +# Add the html version. This converts the message into a multipart/alternative +# container, with the original text message as the first part and the new html +# message as the second part. +asparagus_cid = make_msgid() +msg.add_alternative("""\ + + + +

Salut!

+

Cela ressemble à un excellent + + recipie + déjeuner. +

+ + + +""".format(asparagus_cid=asparagus_cid[1:-1]), subtype='html') +# note that we needed to peel the <> off the msgid for use in the html. + +# Now add the related image to the html part. +with open("roasted-asparagus.jpg", 'rb') as img: + msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg', + cid=asparagus_cid) + +# Make a local copy of what we are going to send. +with open('outgoing.msg', 'wb') as f: + f.write(bytes(msg)) + +# Send the message via local SMTP server. +with smtplib.SMTP('localhost') as s: + s.send_message(msg) diff --git a/cpython_2/environment/repo/Doc/includes/email-dir.py b/cpython_2/environment/repo/Doc/includes/email-dir.py new file mode 100644 index 0000000000000000000000000000000000000000..2fc1570e654db6ab5650f7b8857c2570aaebdbdb --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/email-dir.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 + +"""Send the contents of a directory as a MIME message.""" + +import os +import smtplib +# For guessing MIME type based on file name extension +import mimetypes + +from argparse import ArgumentParser + +from email.message import EmailMessage +from email.policy import SMTP + + +def main(): + parser = ArgumentParser(description="""\ +Send the contents of a directory as a MIME message. +Unless the -o option is given, the email is sent by forwarding to your local +SMTP server, which then does the normal delivery process. Your local machine +must be running an SMTP server. +""") + parser.add_argument('-d', '--directory', + help="""Mail the contents of the specified directory, + otherwise use the current directory. Only the regular + files in the directory are sent, and we don't recurse to + subdirectories.""") + parser.add_argument('-o', '--output', + metavar='FILE', + help="""Print the composed message to FILE instead of + sending the message to the SMTP server.""") + parser.add_argument('-s', '--sender', required=True, + help='The value of the From: header (required)') + parser.add_argument('-r', '--recipient', required=True, + action='append', metavar='RECIPIENT', + default=[], dest='recipients', + help='A To: header value (at least one required)') + args = parser.parse_args() + directory = args.directory + if not directory: + directory = '.' + # Create the message + msg = EmailMessage() + msg['Subject'] = f'Contents of directory {os.path.abspath(directory)}' + msg['To'] = ', '.join(args.recipients) + msg['From'] = args.sender + msg.preamble = 'You will not see this in a MIME-aware mail reader.\n' + + for filename in os.listdir(directory): + path = os.path.join(directory, filename) + if not os.path.isfile(path): + continue + # Guess the content type based on the file's extension. Encoding + # will be ignored, although we should check for simple things like + # gzip'd or compressed files. + ctype, encoding = mimetypes.guess_type(path) + if ctype is None or encoding is not None: + # No guess could be made, or the file is encoded (compressed), so + # use a generic bag-of-bits type. + ctype = 'application/octet-stream' + maintype, subtype = ctype.split('/', 1) + with open(path, 'rb') as fp: + msg.add_attachment(fp.read(), + maintype=maintype, + subtype=subtype, + filename=filename) + # Now send or store the message + if args.output: + with open(args.output, 'wb') as fp: + fp.write(msg.as_bytes(policy=SMTP)) + else: + with smtplib.SMTP('localhost') as s: + s.send_message(msg) + + +if __name__ == '__main__': + main() diff --git a/cpython_2/environment/repo/Doc/includes/email-headers.py b/cpython_2/environment/repo/Doc/includes/email-headers.py new file mode 100644 index 0000000000000000000000000000000000000000..2c421451a8e5a8d2b90ba4dd489f68240728543d --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/email-headers.py @@ -0,0 +1,24 @@ +# Import the email modules we'll need +from email.parser import BytesParser, Parser +from email.policy import default + +# If the e-mail headers are in a file, uncomment these two lines: +# with open(messagefile, 'rb') as fp: +# headers = BytesParser(policy=default).parse(fp) + +# Or for parsing headers in a string (this is an uncommon operation), use: +headers = Parser(policy=default).parsestr( + 'From: Foo Bar \n' + 'To: \n' + 'Subject: Test message\n' + '\n' + 'Body would go here\n') + +# Now the header items can be accessed as a dictionary: +print('To: {}'.format(headers['to'])) +print('From: {}'.format(headers['from'])) +print('Subject: {}'.format(headers['subject'])) + +# You can also access the parts of the addresses: +print('Recipient username: {}'.format(headers['to'].addresses[0].username)) +print('Sender name: {}'.format(headers['from'].addresses[0].display_name)) diff --git a/cpython_2/environment/repo/Doc/includes/email-mime.py b/cpython_2/environment/repo/Doc/includes/email-mime.py new file mode 100644 index 0000000000000000000000000000000000000000..6af2be0b08a48da3dc0508eecf6f20ef5df1e103 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/email-mime.py @@ -0,0 +1,29 @@ +# Import smtplib for the actual sending function +import smtplib + +# And imghdr to find the types of our images +import imghdr + +# Here are the email package modules we'll need +from email.message import EmailMessage + +# Create the container email message. +msg = EmailMessage() +msg['Subject'] = 'Our family reunion' +# me == the sender's email address +# family = the list of all recipients' email addresses +msg['From'] = me +msg['To'] = ', '.join(family) +msg.preamble = 'You will not see this in a MIME-aware mail reader.\n' + +# Open the files in binary mode. Use imghdr to figure out the +# MIME subtype for each specific image. +for file in pngfiles: + with open(file, 'rb') as fp: + img_data = fp.read() + msg.add_attachment(img_data, maintype='image', + subtype=imghdr.what(None, img_data)) + +# Send the email via our own SMTP server. +with smtplib.SMTP('localhost') as s: + s.send_message(msg) diff --git a/cpython_2/environment/repo/Doc/includes/email-read-alternative.py b/cpython_2/environment/repo/Doc/includes/email-read-alternative.py new file mode 100644 index 0000000000000000000000000000000000000000..5ea84e62584a465abfad1ec470ada087b1c80283 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/email-read-alternative.py @@ -0,0 +1,75 @@ +import os +import sys +import tempfile +import mimetypes +import webbrowser + +# Import the email modules we'll need +from email import policy +from email.parser import BytesParser + +# An imaginary module that would make this work and be safe. +from imaginary import magic_html_parser + +# In a real program you'd get the filename from the arguments. +with open('outgoing.msg', 'rb') as fp: + msg = BytesParser(policy=policy.default).parse(fp) + +# Now the header items can be accessed as a dictionary, and any non-ASCII will +# be converted to unicode: +print('To:', msg['to']) +print('From:', msg['from']) +print('Subject:', msg['subject']) + +# If we want to print a preview of the message content, we can extract whatever +# the least formatted payload is and print the first three lines. Of course, +# if the message has no plain text part printing the first three lines of html +# is probably useless, but this is just a conceptual example. +simplest = msg.get_body(preferencelist=('plain', 'html')) +print() +print(''.join(simplest.get_content().splitlines(keepends=True)[:3])) + +ans = input("View full message?") +if ans.lower()[0] == 'n': + sys.exit() + +# We can extract the richest alternative in order to display it: +richest = msg.get_body() +partfiles = {} +if richest['content-type'].maintype == 'text': + if richest['content-type'].subtype == 'plain': + for line in richest.get_content().splitlines(): + print(line) + sys.exit() + elif richest['content-type'].subtype == 'html': + body = richest + else: + print("Don't know how to display {}".format(richest.get_content_type())) + sys.exit() +elif richest['content-type'].content_type == 'multipart/related': + body = richest.get_body(preferencelist=('html')) + for part in richest.iter_attachments(): + fn = part.get_filename() + if fn: + extension = os.path.splitext(part.get_filename())[1] + else: + extension = mimetypes.guess_extension(part.get_content_type()) + with tempfile.NamedTemporaryFile(suffix=extension, delete=False) as f: + f.write(part.get_content()) + # again strip the <> to go from email form of cid to html form. + partfiles[part['content-id'][1:-1]] = f.name +else: + print("Don't know how to display {}".format(richest.get_content_type())) + sys.exit() +with tempfile.NamedTemporaryFile(mode='w', delete=False) as f: + # The magic_html_parser has to rewrite the href="cid:...." attributes to + # point to the filenames in partfiles. It also has to do a safety-sanitize + # of the html. It could be written using html.parser. + f.write(magic_html_parser(body.get_content(), partfiles)) +webbrowser.open(f.name) +os.remove(f.name) +for fn in partfiles.values(): + os.remove(fn) + +# Of course, there are lots of email messages that could break this simple +# minded program, but it will handle the most common ones. diff --git a/cpython_2/environment/repo/Doc/includes/email-simple.py b/cpython_2/environment/repo/Doc/includes/email-simple.py new file mode 100644 index 0000000000000000000000000000000000000000..07dc30fd066eace9063de73d99c24723b230bf6b --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/email-simple.py @@ -0,0 +1,22 @@ +# Import smtplib for the actual sending function +import smtplib + +# Import the email modules we'll need +from email.message import EmailMessage + +# Open the plain text file whose name is in textfile for reading. +with open(textfile) as fp: + # Create a text/plain message + msg = EmailMessage() + msg.set_content(fp.read()) + +# me == the sender's email address +# you == the recipient's email address +msg['Subject'] = f'The contents of {textfile}' +msg['From'] = me +msg['To'] = you + +# Send the message via our own SMTP server. +s = smtplib.SMTP('localhost') +s.send_message(msg) +s.quit() diff --git a/cpython_2/environment/repo/Doc/includes/email-unpack.py b/cpython_2/environment/repo/Doc/includes/email-unpack.py new file mode 100644 index 0000000000000000000000000000000000000000..c8cb0be45608308616328960460a761a7f8757ab --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/email-unpack.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 + +"""Unpack a MIME message into a directory of files.""" + +import os +import email +import mimetypes + +from email.policy import default + +from argparse import ArgumentParser + + +def main(): + parser = ArgumentParser(description="""\ +Unpack a MIME message into a directory of files. +""") + parser.add_argument('-d', '--directory', required=True, + help="""Unpack the MIME message into the named + directory, which will be created if it doesn't already + exist.""") + parser.add_argument('msgfile') + args = parser.parse_args() + + with open(args.msgfile, 'rb') as fp: + msg = email.message_from_binary_file(fp, policy=default) + + try: + os.mkdir(args.directory) + except FileExistsError: + pass + + counter = 1 + for part in msg.walk(): + # multipart/* are just containers + if part.get_content_maintype() == 'multipart': + continue + # Applications should really sanitize the given filename so that an + # email message can't be used to overwrite important files + filename = part.get_filename() + if not filename: + ext = mimetypes.guess_extension(part.get_content_type()) + if not ext: + # Use a generic bag-of-bits extension + ext = '.bin' + filename = f'part-{counter:03d}{ext}' + counter += 1 + with open(os.path.join(args.directory, filename), 'wb') as fp: + fp.write(part.get_payload(decode=True)) + + +if __name__ == '__main__': + main() diff --git a/cpython_2/environment/repo/Doc/includes/minidom-example.py b/cpython_2/environment/repo/Doc/includes/minidom-example.py new file mode 100644 index 0000000000000000000000000000000000000000..5ee7682c1927124fba3cfea51a21c02bd3b2e870 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/minidom-example.py @@ -0,0 +1,64 @@ +import xml.dom.minidom + +document = """\ + +Demo slideshow +Slide title +This is a demo +Of a program for processing slides + + +Another demo slide +It is important +To have more than +one slide + + +""" + +dom = xml.dom.minidom.parseString(document) + +def getText(nodelist): + rc = [] + for node in nodelist: + if node.nodeType == node.TEXT_NODE: + rc.append(node.data) + return ''.join(rc) + +def handleSlideshow(slideshow): + print("") + handleSlideshowTitle(slideshow.getElementsByTagName("title")[0]) + slides = slideshow.getElementsByTagName("slide") + handleToc(slides) + handleSlides(slides) + print("") + +def handleSlides(slides): + for slide in slides: + handleSlide(slide) + +def handleSlide(slide): + handleSlideTitle(slide.getElementsByTagName("title")[0]) + handlePoints(slide.getElementsByTagName("point")) + +def handleSlideshowTitle(title): + print("%s" % getText(title.childNodes)) + +def handleSlideTitle(title): + print("

%s

" % getText(title.childNodes)) + +def handlePoints(points): + print("
    ") + for point in points: + handlePoint(point) + print("
") + +def handlePoint(point): + print("
  • %s
  • " % getText(point.childNodes)) + +def handleToc(slides): + for slide in slides: + title = slide.getElementsByTagName("title")[0] + print("

    %s

    " % getText(title.childNodes)) + +handleSlideshow(dom) diff --git a/cpython_2/environment/repo/Doc/includes/mp_newtype.py b/cpython_2/environment/repo/Doc/includes/mp_newtype.py new file mode 100644 index 0000000000000000000000000000000000000000..1c796a564049ad8c39ceca56be0ccf47bcab5a48 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/mp_newtype.py @@ -0,0 +1,89 @@ +from multiprocessing import freeze_support +from multiprocessing.managers import BaseManager, BaseProxy +import operator + +## + +class Foo: + def f(self): + print('you called Foo.f()') + def g(self): + print('you called Foo.g()') + def _h(self): + print('you called Foo._h()') + +# A simple generator function +def baz(): + for i in range(10): + yield i*i + +# Proxy type for generator objects +class GeneratorProxy(BaseProxy): + _exposed_ = ['__next__'] + def __iter__(self): + return self + def __next__(self): + return self._callmethod('__next__') + +# Function to return the operator module +def get_operator_module(): + return operator + +## + +class MyManager(BaseManager): + pass + +# register the Foo class; make `f()` and `g()` accessible via proxy +MyManager.register('Foo1', Foo) + +# register the Foo class; make `g()` and `_h()` accessible via proxy +MyManager.register('Foo2', Foo, exposed=('g', '_h')) + +# register the generator function baz; use `GeneratorProxy` to make proxies +MyManager.register('baz', baz, proxytype=GeneratorProxy) + +# register get_operator_module(); make public functions accessible via proxy +MyManager.register('operator', get_operator_module) + +## + +def test(): + manager = MyManager() + manager.start() + + print('-' * 20) + + f1 = manager.Foo1() + f1.f() + f1.g() + assert not hasattr(f1, '_h') + assert sorted(f1._exposed_) == sorted(['f', 'g']) + + print('-' * 20) + + f2 = manager.Foo2() + f2.g() + f2._h() + assert not hasattr(f2, 'f') + assert sorted(f2._exposed_) == sorted(['g', '_h']) + + print('-' * 20) + + it = manager.baz() + for i in it: + print('<%d>' % i, end=' ') + print() + + print('-' * 20) + + op = manager.operator() + print('op.add(23, 45) =', op.add(23, 45)) + print('op.pow(2, 94) =', op.pow(2, 94)) + print('op._exposed_ =', op._exposed_) + +## + +if __name__ == '__main__': + freeze_support() + test() diff --git a/cpython_2/environment/repo/Doc/includes/mp_pool.py b/cpython_2/environment/repo/Doc/includes/mp_pool.py new file mode 100644 index 0000000000000000000000000000000000000000..11101e1a90954e8a2cced8ac609844db6cf8acaa --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/mp_pool.py @@ -0,0 +1,153 @@ +import multiprocessing +import time +import random +import sys + +# +# Functions used by test code +# + +def calculate(func, args): + result = func(*args) + return '%s says that %s%s = %s' % ( + multiprocessing.current_process().name, + func.__name__, args, result + ) + +def calculatestar(args): + return calculate(*args) + +def mul(a, b): + time.sleep(0.5 * random.random()) + return a * b + +def plus(a, b): + time.sleep(0.5 * random.random()) + return a + b + +def f(x): + return 1.0 / (x - 5.0) + +def pow3(x): + return x ** 3 + +def noop(x): + pass + +# +# Test code +# + +def test(): + PROCESSES = 4 + print('Creating pool with %d processes\n' % PROCESSES) + + with multiprocessing.Pool(PROCESSES) as pool: + # + # Tests + # + + TASKS = [(mul, (i, 7)) for i in range(10)] + \ + [(plus, (i, 8)) for i in range(10)] + + results = [pool.apply_async(calculate, t) for t in TASKS] + imap_it = pool.imap(calculatestar, TASKS) + imap_unordered_it = pool.imap_unordered(calculatestar, TASKS) + + print('Ordered results using pool.apply_async():') + for r in results: + print('\t', r.get()) + print() + + print('Ordered results using pool.imap():') + for x in imap_it: + print('\t', x) + print() + + print('Unordered results using pool.imap_unordered():') + for x in imap_unordered_it: + print('\t', x) + print() + + print('Ordered results using pool.map() --- will block till complete:') + for x in pool.map(calculatestar, TASKS): + print('\t', x) + print() + + # + # Test error handling + # + + print('Testing error handling:') + + try: + print(pool.apply(f, (5,))) + except ZeroDivisionError: + print('\tGot ZeroDivisionError as expected from pool.apply()') + else: + raise AssertionError('expected ZeroDivisionError') + + try: + print(pool.map(f, list(range(10)))) + except ZeroDivisionError: + print('\tGot ZeroDivisionError as expected from pool.map()') + else: + raise AssertionError('expected ZeroDivisionError') + + try: + print(list(pool.imap(f, list(range(10))))) + except ZeroDivisionError: + print('\tGot ZeroDivisionError as expected from list(pool.imap())') + else: + raise AssertionError('expected ZeroDivisionError') + + it = pool.imap(f, list(range(10))) + for i in range(10): + try: + x = next(it) + except ZeroDivisionError: + if i == 5: + pass + except StopIteration: + break + else: + if i == 5: + raise AssertionError('expected ZeroDivisionError') + + assert i == 9 + print('\tGot ZeroDivisionError as expected from IMapIterator.next()') + print() + + # + # Testing timeouts + # + + print('Testing ApplyResult.get() with timeout:', end=' ') + res = pool.apply_async(calculate, TASKS[0]) + while 1: + sys.stdout.flush() + try: + sys.stdout.write('\n\t%s' % res.get(0.02)) + break + except multiprocessing.TimeoutError: + sys.stdout.write('.') + print() + print() + + print('Testing IMapIterator.next() with timeout:', end=' ') + it = pool.imap(calculatestar, TASKS) + while 1: + sys.stdout.flush() + try: + sys.stdout.write('\n\t%s' % it.next(0.02)) + except StopIteration: + break + except multiprocessing.TimeoutError: + sys.stdout.write('.') + print() + print() + + +if __name__ == '__main__': + multiprocessing.freeze_support() + test() diff --git a/cpython_2/environment/repo/Doc/includes/mp_workers.py b/cpython_2/environment/repo/Doc/includes/mp_workers.py new file mode 100644 index 0000000000000000000000000000000000000000..3b92269f897e932d4daef417ae3a3c094933ec26 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/mp_workers.py @@ -0,0 +1,77 @@ +import time +import random + +from multiprocessing import Process, Queue, current_process, freeze_support + +# +# Function run by worker processes +# + +def worker(input, output): + for func, args in iter(input.get, 'STOP'): + result = calculate(func, args) + output.put(result) + +# +# Function used to calculate result +# + +def calculate(func, args): + result = func(*args) + return '%s says that %s%s = %s' % \ + (current_process().name, func.__name__, args, result) + +# +# Functions referenced by tasks +# + +def mul(a, b): + time.sleep(0.5*random.random()) + return a * b + +def plus(a, b): + time.sleep(0.5*random.random()) + return a + b + +# +# +# + +def test(): + NUMBER_OF_PROCESSES = 4 + TASKS1 = [(mul, (i, 7)) for i in range(20)] + TASKS2 = [(plus, (i, 8)) for i in range(10)] + + # Create queues + task_queue = Queue() + done_queue = Queue() + + # Submit tasks + for task in TASKS1: + task_queue.put(task) + + # Start worker processes + for i in range(NUMBER_OF_PROCESSES): + Process(target=worker, args=(task_queue, done_queue)).start() + + # Get and print results + print('Unordered results:') + for i in range(len(TASKS1)): + print('\t', done_queue.get()) + + # Add more tasks using `put()` + for task in TASKS2: + task_queue.put(task) + + # Get and print some more results + for i in range(len(TASKS2)): + print('\t', done_queue.get()) + + # Tell child processes to stop + for i in range(NUMBER_OF_PROCESSES): + task_queue.put('STOP') + + +if __name__ == '__main__': + freeze_support() + test() diff --git a/cpython_2/environment/repo/Doc/includes/run-func.c b/cpython_2/environment/repo/Doc/includes/run-func.c new file mode 100644 index 0000000000000000000000000000000000000000..392f86d65ecc17754f5e0922ed1f0ee2b908408b --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/run-func.c @@ -0,0 +1,71 @@ +#define PY_SSIZE_T_CLEAN +#include + +int +main(int argc, char *argv[]) +{ + PyObject *pName, *pModule, *pFunc; + PyObject *pArgs, *pValue; + int i; + + if (argc < 3) { + fprintf(stderr,"Usage: call pythonfile funcname [args]\n"); + return 1; + } + + Py_Initialize(); + pName = PyUnicode_DecodeFSDefault(argv[1]); + /* Error checking of pName left out */ + + pModule = PyImport_Import(pName); + Py_DECREF(pName); + + if (pModule != NULL) { + pFunc = PyObject_GetAttrString(pModule, argv[2]); + /* pFunc is a new reference */ + + if (pFunc && PyCallable_Check(pFunc)) { + pArgs = PyTuple_New(argc - 3); + for (i = 0; i < argc - 3; ++i) { + pValue = PyLong_FromLong(atoi(argv[i + 3])); + if (!pValue) { + Py_DECREF(pArgs); + Py_DECREF(pModule); + fprintf(stderr, "Cannot convert argument\n"); + return 1; + } + /* pValue reference stolen here: */ + PyTuple_SetItem(pArgs, i, pValue); + } + pValue = PyObject_CallObject(pFunc, pArgs); + Py_DECREF(pArgs); + if (pValue != NULL) { + printf("Result of call: %ld\n", PyLong_AsLong(pValue)); + Py_DECREF(pValue); + } + else { + Py_DECREF(pFunc); + Py_DECREF(pModule); + PyErr_Print(); + fprintf(stderr,"Call failed\n"); + return 1; + } + } + else { + if (PyErr_Occurred()) + PyErr_Print(); + fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]); + } + Py_XDECREF(pFunc); + Py_DECREF(pModule); + } + else { + PyErr_Print(); + fprintf(stderr, "Failed to load \"%s\"\n", argv[1]); + return 1; + } + if (Py_FinalizeEx() < 0) { + return 120; + } + return 0; +} diff --git a/cpython_2/environment/repo/Doc/includes/setup.py b/cpython_2/environment/repo/Doc/includes/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..a38a39de3e7c86c6b9daa2c788ebf45eb9ff3a6f --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/setup.py @@ -0,0 +1,9 @@ +from distutils.core import setup, Extension +setup(name="noddy", version="1.0", + ext_modules=[ + Extension("noddy", ["noddy.c"]), + Extension("noddy2", ["noddy2.c"]), + Extension("noddy3", ["noddy3.c"]), + Extension("noddy4", ["noddy4.c"]), + Extension("shoddy", ["shoddy.c"]), + ]) diff --git a/cpython_2/environment/repo/Doc/includes/sqlite3/adapter_datetime.py b/cpython_2/environment/repo/Doc/includes/sqlite3/adapter_datetime.py new file mode 100644 index 0000000000000000000000000000000000000000..d5221d80c35c8ac4b5928322172b1c11ba41e7ca --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/sqlite3/adapter_datetime.py @@ -0,0 +1,17 @@ +import sqlite3 +import datetime +import time + +def adapt_datetime(ts): + return time.mktime(ts.timetuple()) + +sqlite3.register_adapter(datetime.datetime, adapt_datetime) + +con = sqlite3.connect(":memory:") +cur = con.cursor() + +now = datetime.datetime.now() +cur.execute("select ?", (now,)) +print(cur.fetchone()[0]) + +con.close() diff --git a/cpython_2/environment/repo/Doc/includes/sqlite3/adapter_point_1.py b/cpython_2/environment/repo/Doc/includes/sqlite3/adapter_point_1.py new file mode 100644 index 0000000000000000000000000000000000000000..77daf8f16d227b859271543f9cd61473874c1f87 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/sqlite3/adapter_point_1.py @@ -0,0 +1,18 @@ +import sqlite3 + +class Point: + def __init__(self, x, y): + self.x, self.y = x, y + + def __conform__(self, protocol): + if protocol is sqlite3.PrepareProtocol: + return "%f;%f" % (self.x, self.y) + +con = sqlite3.connect(":memory:") +cur = con.cursor() + +p = Point(4.0, -3.2) +cur.execute("select ?", (p,)) +print(cur.fetchone()[0]) + +con.close() diff --git a/cpython_2/environment/repo/Doc/includes/sqlite3/adapter_point_2.py b/cpython_2/environment/repo/Doc/includes/sqlite3/adapter_point_2.py new file mode 100644 index 0000000000000000000000000000000000000000..cb86331692b61d5b15915b797e85955b1ce6bdaa --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/sqlite3/adapter_point_2.py @@ -0,0 +1,19 @@ +import sqlite3 + +class Point: + def __init__(self, x, y): + self.x, self.y = x, y + +def adapt_point(point): + return "%f;%f" % (point.x, point.y) + +sqlite3.register_adapter(Point, adapt_point) + +con = sqlite3.connect(":memory:") +cur = con.cursor() + +p = Point(4.0, -3.2) +cur.execute("select ?", (p,)) +print(cur.fetchone()[0]) + +con.close() diff --git a/cpython_2/environment/repo/Doc/includes/sqlite3/collation_reverse.py b/cpython_2/environment/repo/Doc/includes/sqlite3/collation_reverse.py new file mode 100644 index 0000000000000000000000000000000000000000..3504a350a04ecb82c093751007514d22b619e565 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/sqlite3/collation_reverse.py @@ -0,0 +1,20 @@ +import sqlite3 + +def collate_reverse(string1, string2): + if string1 == string2: + return 0 + elif string1 < string2: + return 1 + else: + return -1 + +con = sqlite3.connect(":memory:") +con.create_collation("reverse", collate_reverse) + +cur = con.cursor() +cur.execute("create table test(x)") +cur.executemany("insert into test(x) values (?)", [("a",), ("b",)]) +cur.execute("select x from test order by x collate reverse") +for row in cur: + print(row) +con.close() diff --git a/cpython_2/environment/repo/Doc/includes/sqlite3/complete_statement.py b/cpython_2/environment/repo/Doc/includes/sqlite3/complete_statement.py new file mode 100644 index 0000000000000000000000000000000000000000..cd38d7305bb69c33a2b981e7df1c22db13ce50e7 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/sqlite3/complete_statement.py @@ -0,0 +1,30 @@ +# A minimal SQLite shell for experiments + +import sqlite3 + +con = sqlite3.connect(":memory:") +con.isolation_level = None +cur = con.cursor() + +buffer = "" + +print("Enter your SQL commands to execute in sqlite3.") +print("Enter a blank line to exit.") + +while True: + line = input() + if line == "": + break + buffer += line + if sqlite3.complete_statement(buffer): + try: + buffer = buffer.strip() + cur.execute(buffer) + + if buffer.lstrip().upper().startswith("SELECT"): + print(cur.fetchall()) + except sqlite3.Error as e: + print("An error occurred:", e.args[0]) + buffer = "" + +con.close() diff --git a/cpython_2/environment/repo/Doc/includes/sqlite3/converter_point.py b/cpython_2/environment/repo/Doc/includes/sqlite3/converter_point.py new file mode 100644 index 0000000000000000000000000000000000000000..5df828e3361246fb57d5f891d3327fa7c08532e3 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/sqlite3/converter_point.py @@ -0,0 +1,47 @@ +import sqlite3 + +class Point: + def __init__(self, x, y): + self.x, self.y = x, y + + def __repr__(self): + return "(%f;%f)" % (self.x, self.y) + +def adapt_point(point): + return ("%f;%f" % (point.x, point.y)).encode('ascii') + +def convert_point(s): + x, y = list(map(float, s.split(b";"))) + return Point(x, y) + +# Register the adapter +sqlite3.register_adapter(Point, adapt_point) + +# Register the converter +sqlite3.register_converter("point", convert_point) + +p = Point(4.0, -3.2) + +######################### +# 1) Using declared types +con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES) +cur = con.cursor() +cur.execute("create table test(p point)") + +cur.execute("insert into test(p) values (?)", (p,)) +cur.execute("select p from test") +print("with declared types:", cur.fetchone()[0]) +cur.close() +con.close() + +####################### +# 1) Using column names +con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES) +cur = con.cursor() +cur.execute("create table test(p)") + +cur.execute("insert into test(p) values (?)", (p,)) +cur.execute('select p as "p [point]" from test') +print("with column names:", cur.fetchone()[0]) +cur.close() +con.close() diff --git a/cpython_2/environment/repo/Doc/includes/sqlite3/countcursors.py b/cpython_2/environment/repo/Doc/includes/sqlite3/countcursors.py new file mode 100644 index 0000000000000000000000000000000000000000..112f47703a2ff444b851b4b750165af59e2f7699 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/sqlite3/countcursors.py @@ -0,0 +1,17 @@ +import sqlite3 + +class CountCursorsConnection(sqlite3.Connection): + def __init__(self, *args, **kwargs): + sqlite3.Connection.__init__(self, *args, **kwargs) + self.numcursors = 0 + + def cursor(self, *args, **kwargs): + self.numcursors += 1 + return sqlite3.Connection.cursor(self, *args, **kwargs) + +con = sqlite3.connect(":memory:", factory=CountCursorsConnection) +cur1 = con.cursor() +cur2 = con.cursor() +print(con.numcursors) + +con.close() diff --git a/cpython_2/environment/repo/Doc/includes/sqlite3/createdb.py b/cpython_2/environment/repo/Doc/includes/sqlite3/createdb.py new file mode 100644 index 0000000000000000000000000000000000000000..ee2950bdf8164610cb0bc4cb4074b9bc406078c6 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/sqlite3/createdb.py @@ -0,0 +1,28 @@ +# Not referenced from the documentation, but builds the database file the other +# code snippets expect. + +import sqlite3 +import os + +DB_FILE = "mydb" + +if os.path.exists(DB_FILE): + os.remove(DB_FILE) + +con = sqlite3.connect(DB_FILE) +cur = con.cursor() +cur.execute(""" + create table people + ( + name_last varchar(20), + age integer + ) + """) + +cur.execute("insert into people (name_last, age) values ('Yeltsin', 72)") +cur.execute("insert into people (name_last, age) values ('Putin', 51)") + +con.commit() + +cur.close() +con.close() diff --git a/cpython_2/environment/repo/Doc/includes/sqlite3/ctx_manager.py b/cpython_2/environment/repo/Doc/includes/sqlite3/ctx_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..6db77d45046e1f6676eece35b21ee400387bf535 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/sqlite3/ctx_manager.py @@ -0,0 +1,20 @@ +import sqlite3 + +con = sqlite3.connect(":memory:") +con.execute("create table person (id integer primary key, firstname varchar unique)") + +# Successful, con.commit() is called automatically afterwards +with con: + con.execute("insert into person(firstname) values (?)", ("Joe",)) + +# con.rollback() is called after the with block finishes with an exception, the +# exception is still raised and must be caught +try: + with con: + con.execute("insert into person(firstname) values (?)", ("Joe",)) +except sqlite3.IntegrityError: + print("couldn't add Joe twice") + +# Connection object used as context manager only commits or rollbacks transactions, +# so the connection object should be closed manually +con.close() diff --git a/cpython_2/environment/repo/Doc/includes/sqlite3/execsql_fetchonerow.py b/cpython_2/environment/repo/Doc/includes/sqlite3/execsql_fetchonerow.py new file mode 100644 index 0000000000000000000000000000000000000000..115bcb50c7c754ff992ebe5cbf58e266ed8edfed --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/sqlite3/execsql_fetchonerow.py @@ -0,0 +1,19 @@ +import sqlite3 + +con = sqlite3.connect("mydb") + +cur = con.cursor() +SELECT = "select name_last, age from people order by age, name_last" + +# 1. Iterate over the rows available from the cursor, unpacking the +# resulting sequences to yield their elements (name_last, age): +cur.execute(SELECT) +for (name_last, age) in cur: + print('%s is %d years old.' % (name_last, age)) + +# 2. Equivalently: +cur.execute(SELECT) +for row in cur: + print('%s is %d years old.' % (row[0], row[1])) + +con.close() diff --git a/cpython_2/environment/repo/Doc/includes/sqlite3/execsql_printall_1.py b/cpython_2/environment/repo/Doc/includes/sqlite3/execsql_printall_1.py new file mode 100644 index 0000000000000000000000000000000000000000..19306e6e3ca7d1882b67228a76ed3f8c40cf558d --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/sqlite3/execsql_printall_1.py @@ -0,0 +1,15 @@ +import sqlite3 + +# Create a connection to the database file "mydb": +con = sqlite3.connect("mydb") + +# Get a Cursor object that operates in the context of Connection con: +cur = con.cursor() + +# Execute the SELECT statement: +cur.execute("select * from people order by age") + +# Retrieve all rows as a sequence and print that sequence: +print(cur.fetchall()) + +con.close() diff --git a/cpython_2/environment/repo/Doc/includes/sqlite3/execute_1.py b/cpython_2/environment/repo/Doc/includes/sqlite3/execute_1.py new file mode 100644 index 0000000000000000000000000000000000000000..3466b1265a5bf24ef3ad3ce841d8323866edf660 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/sqlite3/execute_1.py @@ -0,0 +1,18 @@ +import sqlite3 + +con = sqlite3.connect(":memory:") +cur = con.cursor() +cur.execute("create table people (name_last, age)") + +who = "Yeltsin" +age = 72 + +# This is the qmark style: +cur.execute("insert into people values (?, ?)", (who, age)) + +# And this is the named style: +cur.execute("select * from people where name_last=:who and age=:age", {"who": who, "age": age}) + +print(cur.fetchone()) + +con.close() diff --git a/cpython_2/environment/repo/Doc/includes/sqlite3/executemany_1.py b/cpython_2/environment/repo/Doc/includes/sqlite3/executemany_1.py new file mode 100644 index 0000000000000000000000000000000000000000..edf6f8b7ebe61a839c187655bc141cbe9f7e57e6 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/sqlite3/executemany_1.py @@ -0,0 +1,26 @@ +import sqlite3 + +class IterChars: + def __init__(self): + self.count = ord('a') + + def __iter__(self): + return self + + def __next__(self): + if self.count > ord('z'): + raise StopIteration + self.count += 1 + return (chr(self.count - 1),) # this is a 1-tuple + +con = sqlite3.connect(":memory:") +cur = con.cursor() +cur.execute("create table characters(c)") + +theIter = IterChars() +cur.executemany("insert into characters(c) values (?)", theIter) + +cur.execute("select c from characters") +print(cur.fetchall()) + +con.close() diff --git a/cpython_2/environment/repo/Doc/includes/sqlite3/executemany_2.py b/cpython_2/environment/repo/Doc/includes/sqlite3/executemany_2.py new file mode 100644 index 0000000000000000000000000000000000000000..02a594c861e15baff439090d811bf3260d61cbc1 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/sqlite3/executemany_2.py @@ -0,0 +1,17 @@ +import sqlite3 +import string + +def char_generator(): + for c in string.ascii_lowercase: + yield (c,) + +con = sqlite3.connect(":memory:") +cur = con.cursor() +cur.execute("create table characters(c)") + +cur.executemany("insert into characters(c) values (?)", char_generator()) + +cur.execute("select c from characters") +print(cur.fetchall()) + +con.close() diff --git a/cpython_2/environment/repo/Doc/includes/sqlite3/executescript.py b/cpython_2/environment/repo/Doc/includes/sqlite3/executescript.py new file mode 100644 index 0000000000000000000000000000000000000000..aea8943fbee598f657cdf4c1e9aec3381335a052 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/sqlite3/executescript.py @@ -0,0 +1,25 @@ +import sqlite3 + +con = sqlite3.connect(":memory:") +cur = con.cursor() +cur.executescript(""" + create table person( + firstname, + lastname, + age + ); + + create table book( + title, + author, + published + ); + + insert into book(title, author, published) + values ( + 'Dirk Gently''s Holistic Detective Agency', + 'Douglas Adams', + 1987 + ); + """) +con.close() diff --git a/cpython_2/environment/repo/Doc/includes/sqlite3/insert_more_people.py b/cpython_2/environment/repo/Doc/includes/sqlite3/insert_more_people.py new file mode 100644 index 0000000000000000000000000000000000000000..10cf937243f6dac5f684e920960e2ab575e5338d --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/sqlite3/insert_more_people.py @@ -0,0 +1,18 @@ +import sqlite3 + +con = sqlite3.connect("mydb") + +cur = con.cursor() + +newPeople = ( + ('Lebed' , 53), + ('Zhirinovsky' , 57), + ) + +for person in newPeople: + cur.execute("insert into people (name_last, age) values (?, ?)", person) + +# The changes will not be saved unless the transaction is committed explicitly: +con.commit() + +con.close() diff --git a/cpython_2/environment/repo/Doc/includes/sqlite3/load_extension.py b/cpython_2/environment/repo/Doc/includes/sqlite3/load_extension.py new file mode 100644 index 0000000000000000000000000000000000000000..624cfe262f38b37e6e46993248d1b62544e8ce17 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/sqlite3/load_extension.py @@ -0,0 +1,28 @@ +import sqlite3 + +con = sqlite3.connect(":memory:") + +# enable extension loading +con.enable_load_extension(True) + +# Load the fulltext search extension +con.execute("select load_extension('./fts3.so')") + +# alternatively you can load the extension using an API call: +# con.load_extension("./fts3.so") + +# disable extension loading again +con.enable_load_extension(False) + +# example from SQLite wiki +con.execute("create virtual table recipe using fts3(name, ingredients)") +con.executescript(""" + insert into recipe (name, ingredients) values ('broccoli stew', 'broccoli peppers cheese tomatoes'); + insert into recipe (name, ingredients) values ('pumpkin stew', 'pumpkin onions garlic celery'); + insert into recipe (name, ingredients) values ('broccoli pie', 'broccoli cheese onions flour'); + insert into recipe (name, ingredients) values ('pumpkin pie', 'pumpkin sugar flour butter'); + """) +for row in con.execute("select rowid, name, ingredients from recipe where name match 'pie'"): + print(row) + +con.close() diff --git a/cpython_2/environment/repo/Doc/includes/sqlite3/md5func.py b/cpython_2/environment/repo/Doc/includes/sqlite3/md5func.py new file mode 100644 index 0000000000000000000000000000000000000000..16dc348bf001e261cdce2a8ca00331609168c498 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/sqlite3/md5func.py @@ -0,0 +1,13 @@ +import sqlite3 +import hashlib + +def md5sum(t): + return hashlib.md5(t).hexdigest() + +con = sqlite3.connect(":memory:") +con.create_function("md5", 1, md5sum) +cur = con.cursor() +cur.execute("select md5(?)", (b"foo",)) +print(cur.fetchone()[0]) + +con.close() diff --git a/cpython_2/environment/repo/Doc/includes/sqlite3/mysumaggr.py b/cpython_2/environment/repo/Doc/includes/sqlite3/mysumaggr.py new file mode 100644 index 0000000000000000000000000000000000000000..11f96395b6c485c2fda9f8aecfd556ff6e5b8201 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/sqlite3/mysumaggr.py @@ -0,0 +1,22 @@ +import sqlite3 + +class MySum: + def __init__(self): + self.count = 0 + + def step(self, value): + self.count += value + + def finalize(self): + return self.count + +con = sqlite3.connect(":memory:") +con.create_aggregate("mysum", 1, MySum) +cur = con.cursor() +cur.execute("create table test(i)") +cur.execute("insert into test(i) values (1)") +cur.execute("insert into test(i) values (2)") +cur.execute("select mysum(i) from test") +print(cur.fetchone()[0]) + +con.close() diff --git a/cpython_2/environment/repo/Doc/includes/sqlite3/parse_colnames.py b/cpython_2/environment/repo/Doc/includes/sqlite3/parse_colnames.py new file mode 100644 index 0000000000000000000000000000000000000000..5f01dbfe1cb524c8aba90a6e565ae805c3da4f03 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/sqlite3/parse_colnames.py @@ -0,0 +1,10 @@ +import sqlite3 +import datetime + +con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES) +cur = con.cursor() +cur.execute('select ? as "x [timestamp]"', (datetime.datetime.now(),)) +dt = cur.fetchone()[0] +print(dt, type(dt)) + +con.close() diff --git a/cpython_2/environment/repo/Doc/includes/sqlite3/pysqlite_datetime.py b/cpython_2/environment/repo/Doc/includes/sqlite3/pysqlite_datetime.py new file mode 100644 index 0000000000000000000000000000000000000000..5d843f906b3062dff450074fcffe8abec65dbd76 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/sqlite3/pysqlite_datetime.py @@ -0,0 +1,22 @@ +import sqlite3 +import datetime + +con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES) +cur = con.cursor() +cur.execute("create table test(d date, ts timestamp)") + +today = datetime.date.today() +now = datetime.datetime.now() + +cur.execute("insert into test(d, ts) values (?, ?)", (today, now)) +cur.execute("select d, ts from test") +row = cur.fetchone() +print(today, "=>", row[0], type(row[0])) +print(now, "=>", row[1], type(row[1])) + +cur.execute('select current_date as "d [date]", current_timestamp as "ts [timestamp]"') +row = cur.fetchone() +print("current_date", row[0], type(row[0])) +print("current_timestamp", row[1], type(row[1])) + +con.close() diff --git a/cpython_2/environment/repo/Doc/includes/sqlite3/row_factory.py b/cpython_2/environment/repo/Doc/includes/sqlite3/row_factory.py new file mode 100644 index 0000000000000000000000000000000000000000..9de6e7b1b9052a394aaaeddd4e6a97a9585b4947 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/sqlite3/row_factory.py @@ -0,0 +1,15 @@ +import sqlite3 + +def dict_factory(cursor, row): + d = {} + for idx, col in enumerate(cursor.description): + d[col[0]] = row[idx] + return d + +con = sqlite3.connect(":memory:") +con.row_factory = dict_factory +cur = con.cursor() +cur.execute("select 1 as a") +print(cur.fetchone()["a"]) + +con.close() diff --git a/cpython_2/environment/repo/Doc/includes/sqlite3/rowclass.py b/cpython_2/environment/repo/Doc/includes/sqlite3/rowclass.py new file mode 100644 index 0000000000000000000000000000000000000000..fc60287069a854de0b0b72329206f976e5f647a5 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/sqlite3/rowclass.py @@ -0,0 +1,14 @@ +import sqlite3 + +con = sqlite3.connect(":memory:") +con.row_factory = sqlite3.Row + +cur = con.cursor() +cur.execute("select 'John' as name, 42 as age") +for row in cur: + assert row[0] == row["name"] + assert row["name"] == row["nAmE"] + assert row[1] == row["age"] + assert row[1] == row["AgE"] + +con.close() diff --git a/cpython_2/environment/repo/Doc/includes/sqlite3/shared_cache.py b/cpython_2/environment/repo/Doc/includes/sqlite3/shared_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..30e71c935ff62eef8231283317551f5de51b278d --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/sqlite3/shared_cache.py @@ -0,0 +1,6 @@ +import sqlite3 + +# The shared cache is only available in SQLite versions 3.3.3 or later +# See the SQLite documentation for details. + +sqlite3.enable_shared_cache(True) diff --git a/cpython_2/environment/repo/Doc/includes/sqlite3/shortcut_methods.py b/cpython_2/environment/repo/Doc/includes/sqlite3/shortcut_methods.py new file mode 100644 index 0000000000000000000000000000000000000000..98a39411495cbac9e55bc8c6adddd0fb69447e51 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/sqlite3/shortcut_methods.py @@ -0,0 +1,24 @@ +import sqlite3 + +persons = [ + ("Hugo", "Boss"), + ("Calvin", "Klein") + ] + +con = sqlite3.connect(":memory:") + +# Create the table +con.execute("create table person(firstname, lastname)") + +# Fill the table +con.executemany("insert into person(firstname, lastname) values (?, ?)", persons) + +# Print the table contents +for row in con.execute("select firstname, lastname from person"): + print(row) + +print("I just deleted", con.execute("delete from person").rowcount, "rows") + +# close is not a shortcut method and it's not called automatically, +# so the connection object should be closed manually +con.close() diff --git a/cpython_2/environment/repo/Doc/includes/sqlite3/simple_tableprinter.py b/cpython_2/environment/repo/Doc/includes/sqlite3/simple_tableprinter.py new file mode 100644 index 0000000000000000000000000000000000000000..148a1707f948bc5013fdb0ec3c4d9f813d6e4ca8 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/sqlite3/simple_tableprinter.py @@ -0,0 +1,28 @@ +import sqlite3 + +FIELD_MAX_WIDTH = 20 +TABLE_NAME = 'people' +SELECT = 'select * from %s order by age, name_last' % TABLE_NAME + +con = sqlite3.connect("mydb") + +cur = con.cursor() +cur.execute(SELECT) + +# Print a header. +for fieldDesc in cur.description: + print(fieldDesc[0].ljust(FIELD_MAX_WIDTH), end=' ') +print() # Finish the header with a newline. +print('-' * 78) + +# For each row, print the value of each field left-justified within +# the maximum possible width of that field. +fieldIndices = range(len(cur.description)) +for row in cur: + for fieldIndex in fieldIndices: + fieldValue = str(row[fieldIndex]) + print(fieldValue.ljust(FIELD_MAX_WIDTH), end=' ') + + print() # Finish the row with a newline. + +con.close() diff --git a/cpython_2/environment/repo/Doc/includes/sqlite3/text_factory.py b/cpython_2/environment/repo/Doc/includes/sqlite3/text_factory.py new file mode 100644 index 0000000000000000000000000000000000000000..a857a155cdd4ff6f3f7793e9d0bd526615d52455 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/sqlite3/text_factory.py @@ -0,0 +1,29 @@ +import sqlite3 + +con = sqlite3.connect(":memory:") +cur = con.cursor() + +AUSTRIA = "\xd6sterreich" + +# by default, rows are returned as Unicode +cur.execute("select ?", (AUSTRIA,)) +row = cur.fetchone() +assert row[0] == AUSTRIA + +# but we can make sqlite3 always return bytestrings ... +con.text_factory = bytes +cur.execute("select ?", (AUSTRIA,)) +row = cur.fetchone() +assert type(row[0]) is bytes +# the bytestrings will be encoded in UTF-8, unless you stored garbage in the +# database ... +assert row[0] == AUSTRIA.encode("utf-8") + +# we can also implement a custom text_factory ... +# here we implement one that appends "foo" to all strings +con.text_factory = lambda x: x.decode("utf-8") + "foo" +cur.execute("select ?", ("bar",)) +row = cur.fetchone() +assert row[0] == "barfoo" + +con.close() diff --git a/cpython_2/environment/repo/Doc/includes/sublist.c b/cpython_2/environment/repo/Doc/includes/sublist.c new file mode 100644 index 0000000000000000000000000000000000000000..b2c26e73ebaf7e32785032ba6d45e00f57ef34f9 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/sublist.c @@ -0,0 +1,69 @@ +#define PY_SSIZE_T_CLEAN +#include + +typedef struct { + PyListObject list; + int state; +} SubListObject; + +static PyObject * +SubList_increment(SubListObject *self, PyObject *unused) +{ + self->state++; + return PyLong_FromLong(self->state); +} + +static PyMethodDef SubList_methods[] = { + {"increment", (PyCFunction) SubList_increment, METH_NOARGS, + PyDoc_STR("increment state counter")}, + {NULL}, +}; + +static int +SubList_init(SubListObject *self, PyObject *args, PyObject *kwds) +{ + if (PyList_Type.tp_init((PyObject *) self, args, kwds) < 0) + return -1; + self->state = 0; + return 0; +} + +static PyTypeObject SubListType = { + PyVarObject_HEAD_INIT(NULL, 0) + .tp_name = "sublist.SubList", + .tp_doc = "SubList objects", + .tp_basicsize = sizeof(SubListObject), + .tp_itemsize = 0, + .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, + .tp_init = (initproc) SubList_init, + .tp_methods = SubList_methods, +}; + +static PyModuleDef sublistmodule = { + PyModuleDef_HEAD_INIT, + .m_name = "sublist", + .m_doc = "Example module that creates an extension type.", + .m_size = -1, +}; + +PyMODINIT_FUNC +PyInit_sublist(void) +{ + PyObject *m; + SubListType.tp_base = &PyList_Type; + if (PyType_Ready(&SubListType) < 0) + return NULL; + + m = PyModule_Create(&sublistmodule); + if (m == NULL) + return NULL; + + Py_INCREF(&SubListType); + if (PyModule_AddObject(m, "SubList", (PyObject *) &SubListType) < 0) { + Py_DECREF(&SubListType); + Py_DECREF(m); + return NULL; + } + + return m; +} diff --git a/cpython_2/environment/repo/Doc/includes/test.py b/cpython_2/environment/repo/Doc/includes/test.py new file mode 100644 index 0000000000000000000000000000000000000000..09ebe3fec0bdbe32c6d113871fc752601fc694dc --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/test.py @@ -0,0 +1,199 @@ +"""Test module for the custom examples + +Custom 1: + +>>> import custom +>>> c1 = custom.Custom() +>>> c2 = custom.Custom() +>>> del c1 +>>> del c2 + + +Custom 2 + +>>> import custom2 +>>> c1 = custom2.Custom('jim', 'fulton', 42) +>>> c1.first +'jim' +>>> c1.last +'fulton' +>>> c1.number +42 +>>> c1.name() +'jim fulton' +>>> c1.first = 'will' +>>> c1.name() +'will fulton' +>>> c1.last = 'tell' +>>> c1.name() +'will tell' +>>> del c1.first +>>> c1.name() +Traceback (most recent call last): +... +AttributeError: first +>>> c1.first +Traceback (most recent call last): +... +AttributeError: first +>>> c1.first = 'drew' +>>> c1.first +'drew' +>>> del c1.number +Traceback (most recent call last): +... +TypeError: can't delete numeric/char attribute +>>> c1.number=2 +>>> c1.number +2 +>>> c1.first = 42 +>>> c1.name() +'42 tell' +>>> c2 = custom2.Custom() +>>> c2.name() +' ' +>>> c2.first +'' +>>> c2.last +'' +>>> del c2.first +>>> c2.first +Traceback (most recent call last): +... +AttributeError: first +>>> c2.first +Traceback (most recent call last): +... +AttributeError: first +>>> c2.name() +Traceback (most recent call last): + File "", line 1, in ? +AttributeError: first +>>> c2.number +0 +>>> n3 = custom2.Custom('jim', 'fulton', 'waaa') +Traceback (most recent call last): + File "", line 1, in ? +TypeError: an integer is required (got type str) +>>> del c1 +>>> del c2 + + +Custom 3 + +>>> import custom3 +>>> c1 = custom3.Custom('jim', 'fulton', 42) +>>> c1 = custom3.Custom('jim', 'fulton', 42) +>>> c1.name() +'jim fulton' +>>> del c1.first +Traceback (most recent call last): + File "", line 1, in ? +TypeError: Cannot delete the first attribute +>>> c1.first = 42 +Traceback (most recent call last): + File "", line 1, in ? +TypeError: The first attribute value must be a string +>>> c1.first = 'will' +>>> c1.name() +'will fulton' +>>> c2 = custom3.Custom() +>>> c2 = custom3.Custom() +>>> c2 = custom3.Custom() +>>> n3 = custom3.Custom('jim', 'fulton', 'waaa') +Traceback (most recent call last): + File "", line 1, in ? +TypeError: an integer is required (got type str) +>>> del c1 +>>> del c2 + +Custom 4 + +>>> import custom4 +>>> c1 = custom4.Custom('jim', 'fulton', 42) +>>> c1.first +'jim' +>>> c1.last +'fulton' +>>> c1.number +42 +>>> c1.name() +'jim fulton' +>>> c1.first = 'will' +>>> c1.name() +'will fulton' +>>> c1.last = 'tell' +>>> c1.name() +'will tell' +>>> del c1.first +Traceback (most recent call last): +... +TypeError: Cannot delete the first attribute +>>> c1.name() +'will tell' +>>> c1.first = 'drew' +>>> c1.first +'drew' +>>> del c1.number +Traceback (most recent call last): +... +TypeError: can't delete numeric/char attribute +>>> c1.number=2 +>>> c1.number +2 +>>> c1.first = 42 +Traceback (most recent call last): +... +TypeError: The first attribute value must be a string +>>> c1.name() +'drew tell' +>>> c2 = custom4.Custom() +>>> c2 = custom4.Custom() +>>> c2 = custom4.Custom() +>>> c2 = custom4.Custom() +>>> c2.name() +' ' +>>> c2.first +'' +>>> c2.last +'' +>>> c2.number +0 +>>> n3 = custom4.Custom('jim', 'fulton', 'waaa') +Traceback (most recent call last): +... +TypeError: an integer is required (got type str) + + +Test cyclic gc(?) + +>>> import gc +>>> gc.disable() + +>>> class Subclass(custom4.Custom): pass +... +>>> s = Subclass() +>>> s.cycle = [s] +>>> s.cycle.append(s.cycle) +>>> x = object() +>>> s.x = x +>>> del s +>>> sys.getrefcount(x) +3 +>>> ignore = gc.collect() +>>> sys.getrefcount(x) +2 + +>>> gc.enable() +""" + +import os +import sys +from distutils.util import get_platform +PLAT_SPEC = "%s-%d.%d" % (get_platform(), *sys.version_info[:2]) +src = os.path.join("build", "lib.%s" % PLAT_SPEC) +sys.path.append(src) + +if __name__ == "__main__": + import doctest, __main__ + doctest.testmod(__main__) diff --git a/cpython_2/environment/repo/Doc/includes/turtle-star.py b/cpython_2/environment/repo/Doc/includes/turtle-star.py new file mode 100644 index 0000000000000000000000000000000000000000..1a5db761b32385d62ee3c67b65df9a36f3b56254 --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/turtle-star.py @@ -0,0 +1,10 @@ +from turtle import * +color('red', 'yellow') +begin_fill() +while True: + forward(200) + left(170) + if abs(pos()) < 1: + break +end_fill() +done() diff --git a/cpython_2/environment/repo/Doc/includes/typestruct.h b/cpython_2/environment/repo/Doc/includes/typestruct.h new file mode 100644 index 0000000000000000000000000000000000000000..9ada03cfc4a4cbef79c2803dacd312f6abe1cbbd --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/typestruct.h @@ -0,0 +1,80 @@ +typedef struct _typeobject { + PyObject_VAR_HEAD + const char *tp_name; /* For printing, in format "." */ + 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 */ + + /* call function for all accessible objects */ + traverseproc tp_traverse; + + /* delete references to contained objects */ + inquiry tp_clear; + + /* rich comparisons */ + richcmpfunc tp_richcompare; + + /* weak reference enabler */ + Py_ssize_t tp_weaklistoffset; + + /* Iterators */ + getiterfunc tp_iter; + iternextfunc tp_iternext; + + /* Attribute descriptor and subclassing stuff */ + struct PyMethodDef *tp_methods; + struct PyMemberDef *tp_members; + struct PyGetSetDef *tp_getset; + 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; + +} PyTypeObject; diff --git a/cpython_2/environment/repo/Doc/includes/tzinfo_examples.py b/cpython_2/environment/repo/Doc/includes/tzinfo_examples.py new file mode 100644 index 0000000000000000000000000000000000000000..9b9e32a553e7d8e82037e9383e22c856a063328e --- /dev/null +++ b/cpython_2/environment/repo/Doc/includes/tzinfo_examples.py @@ -0,0 +1,175 @@ +from datetime import tzinfo, timedelta, datetime + +ZERO = timedelta(0) +HOUR = timedelta(hours=1) +SECOND = timedelta(seconds=1) + +# A class capturing the platform's idea of local time. +# (May result in wrong values on historical times in +# timezones where UTC offset and/or the DST rules had +# changed in the past.) +import time as _time + +STDOFFSET = timedelta(seconds = -_time.timezone) +if _time.daylight: + DSTOFFSET = timedelta(seconds = -_time.altzone) +else: + DSTOFFSET = STDOFFSET + +DSTDIFF = DSTOFFSET - STDOFFSET + +class LocalTimezone(tzinfo): + + def fromutc(self, dt): + assert dt.tzinfo is self + stamp = (dt - datetime(1970, 1, 1, tzinfo=self)) // SECOND + args = _time.localtime(stamp)[:6] + dst_diff = DSTDIFF // SECOND + # Detect fold + fold = (args == _time.localtime(stamp - dst_diff)) + return datetime(*args, microsecond=dt.microsecond, + tzinfo=self, fold=fold) + + def utcoffset(self, dt): + if self._isdst(dt): + return DSTOFFSET + else: + return STDOFFSET + + def dst(self, dt): + if self._isdst(dt): + return DSTDIFF + else: + return ZERO + + def tzname(self, dt): + return _time.tzname[self._isdst(dt)] + + def _isdst(self, dt): + tt = (dt.year, dt.month, dt.day, + dt.hour, dt.minute, dt.second, + dt.weekday(), 0, 0) + stamp = _time.mktime(tt) + tt = _time.localtime(stamp) + return tt.tm_isdst > 0 + +Local = LocalTimezone() + + +# A complete implementation of current DST rules for major US time zones. + +def first_sunday_on_or_after(dt): + days_to_go = 6 - dt.weekday() + if days_to_go: + dt += timedelta(days_to_go) + return dt + + +# US DST Rules +# +# This is a simplified (i.e., wrong for a few cases) set of rules for US +# DST start and end times. For a complete and up-to-date set of DST rules +# and timezone definitions, visit the Olson Database (or try pytz): +# http://www.twinsun.com/tz/tz-link.htm +# http://sourceforge.net/projects/pytz/ (might not be up-to-date) +# +# In the US, since 2007, DST starts at 2am (standard time) on the second +# Sunday in March, which is the first Sunday on or after Mar 8. +DSTSTART_2007 = datetime(1, 3, 8, 2) +# and ends at 2am (DST time) on the first Sunday of Nov. +DSTEND_2007 = datetime(1, 11, 1, 2) +# From 1987 to 2006, DST used to start at 2am (standard time) on the first +# Sunday in April and to end at 2am (DST time) on the last +# Sunday of October, which is the first Sunday on or after Oct 25. +DSTSTART_1987_2006 = datetime(1, 4, 1, 2) +DSTEND_1987_2006 = datetime(1, 10, 25, 2) +# From 1967 to 1986, DST used to start at 2am (standard time) on the last +# Sunday in April (the one on or after April 24) and to end at 2am (DST time) +# on the last Sunday of October, which is the first Sunday +# on or after Oct 25. +DSTSTART_1967_1986 = datetime(1, 4, 24, 2) +DSTEND_1967_1986 = DSTEND_1987_2006 + +def us_dst_range(year): + # Find start and end times for US DST. For years before 1967, return + # start = end for no DST. + if 2006 < year: + dststart, dstend = DSTSTART_2007, DSTEND_2007 + elif 1986 < year < 2007: + dststart, dstend = DSTSTART_1987_2006, DSTEND_1987_2006 + elif 1966 < year < 1987: + dststart, dstend = DSTSTART_1967_1986, DSTEND_1967_1986 + else: + return (datetime(year, 1, 1), ) * 2 + + start = first_sunday_on_or_after(dststart.replace(year=year)) + end = first_sunday_on_or_after(dstend.replace(year=year)) + return start, end + + +class USTimeZone(tzinfo): + + def __init__(self, hours, reprname, stdname, dstname): + self.stdoffset = timedelta(hours=hours) + self.reprname = reprname + self.stdname = stdname + self.dstname = dstname + + def __repr__(self): + return self.reprname + + def tzname(self, dt): + if self.dst(dt): + return self.dstname + else: + return self.stdname + + def utcoffset(self, dt): + return self.stdoffset + self.dst(dt) + + def dst(self, dt): + if dt is None or dt.tzinfo is None: + # An exception may be sensible here, in one or both cases. + # It depends on how you want to treat them. The default + # fromutc() implementation (called by the default astimezone() + # implementation) passes a datetime with dt.tzinfo is self. + return ZERO + assert dt.tzinfo is self + start, end = us_dst_range(dt.year) + # Can't compare naive to aware objects, so strip the timezone from + # dt first. + dt = dt.replace(tzinfo=None) + if start + HOUR <= dt < end - HOUR: + # DST is in effect. + return HOUR + if end - HOUR <= dt < end: + # Fold (an ambiguous hour): use dt.fold to disambiguate. + return ZERO if dt.fold else HOUR + if start <= dt < start + HOUR: + # Gap (a non-existent hour): reverse the fold rule. + return HOUR if dt.fold else ZERO + # DST is off. + return ZERO + + def fromutc(self, dt): + assert dt.tzinfo is self + start, end = us_dst_range(dt.year) + start = start.replace(tzinfo=self) + end = end.replace(tzinfo=self) + std_time = dt + self.stdoffset + dst_time = std_time + HOUR + if end <= dst_time < end + HOUR: + # Repeated hour + return std_time.replace(fold=1) + if std_time < start or dst_time >= end: + # Standard time + return std_time + if start <= std_time < end - HOUR: + # Daylight saving time + return dst_time + + +Eastern = USTimeZone(-5, "Eastern", "EST", "EDT") +Central = USTimeZone(-6, "Central", "CST", "CDT") +Mountain = USTimeZone(-7, "Mountain", "MST", "MDT") +Pacific = USTimeZone(-8, "Pacific", "PST", "PDT") diff --git a/cpython_2/environment/repo/Doc/install/index.rst b/cpython_2/environment/repo/Doc/install/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..e6d5a3e6ebde6031a7e33791daed86885cdc2036 --- /dev/null +++ b/cpython_2/environment/repo/Doc/install/index.rst @@ -0,0 +1,1071 @@ +.. highlight:: none + +.. _install-index: + +******************************************** + Installing Python Modules (Legacy version) +******************************************** + +:Author: Greg Ward + +.. TODO: Fill in XXX comments + +.. seealso:: + + :ref:`installing-index` + The up to date module installation documentation. For regular Python + usage, you almost certainly want that document rather than this one. + +.. include:: ../distutils/_setuptools_disclaimer.rst + +.. note:: + + This guide only covers the basic tools for building and distributing + extensions that are provided as part of this version of Python. Third party + tools offer easier to use and more secure alternatives. Refer to the `quick + recommendations section `__ + in the Python Packaging User Guide for more information. + + +.. _inst-intro: + + +Introduction +============ + +In Python 2.0, the ``distutils`` API was first added to the standard library. +This provided Linux distro maintainers with a standard way of converting +Python projects into Linux distro packages, and system administrators with a +standard way of installing them directly onto target systems. + +In the many years since Python 2.0 was released, tightly coupling the build +system and package installer to the language runtime release cycle has turned +out to be problematic, and it is now recommended that projects use the +``pip`` package installer and the ``setuptools`` build system, rather than +using ``distutils`` directly. + +See :ref:`installing-index` and :ref:`distributing-index` for more details. + +This legacy documentation is being retained only until we're confident that the +``setuptools`` documentation covers everything needed. + +.. _inst-new-standard: + +Distutils based source distributions +------------------------------------ + +If you download a module source distribution, you can tell pretty quickly if it +was packaged and distributed in the standard way, i.e. using the Distutils. +First, the distribution's name and version number will be featured prominently +in the name of the downloaded archive, e.g. :file:`foo-1.0.tar.gz` or +:file:`widget-0.9.7.zip`. Next, the archive will unpack into a similarly-named +directory: :file:`foo-1.0` or :file:`widget-0.9.7`. Additionally, the +distribution will contain a setup script :file:`setup.py`, and a file named +:file:`README.txt` or possibly just :file:`README`, which should explain that +building and installing the module distribution is a simple matter of running +one command from a terminal:: + + python setup.py install + +For Windows, this command should be run from a command prompt window +(:menuselection:`Start --> Accessories`):: + + setup.py install + +If all these things are true, then you already know how to build and install the +modules you've just downloaded: Run the command above. Unless you need to +install things in a non-standard way or customize the build process, you don't +really need this manual. Or rather, the above command is everything you need to +get out of this manual. + + +.. _inst-standard-install: + +Standard Build and Install +========================== + +As described in section :ref:`inst-new-standard`, building and installing a module +distribution using the Distutils is usually one simple command to run from a +terminal:: + + python setup.py install + + +.. _inst-platform-variations: + +Platform variations +------------------- + +You should always run the setup command from the distribution root directory, +i.e. the top-level subdirectory that the module source distribution unpacks +into. For example, if you've just downloaded a module source distribution +:file:`foo-1.0.tar.gz` onto a Unix system, the normal thing to do is:: + + gunzip -c foo-1.0.tar.gz | tar xf - # unpacks into directory foo-1.0 + cd foo-1.0 + python setup.py install + +On Windows, you'd probably download :file:`foo-1.0.zip`. If you downloaded the +archive file to :file:`C:\\Temp`, then it would unpack into +:file:`C:\\Temp\\foo-1.0`; you can use either an archive manipulator with a +graphical user interface (such as WinZip) or a command-line tool (such as +:program:`unzip` or :program:`pkunzip`) to unpack the archive. Then, open a +command prompt window and run:: + + cd c:\Temp\foo-1.0 + python setup.py install + + +.. _inst-splitting-up: + +Splitting the job up +-------------------- + +Running ``setup.py install`` builds and installs all modules in one run. If you +prefer to work incrementally---especially useful if you want to customize the +build process, or if things are going wrong---you can use the setup script to do +one thing at a time. This is particularly helpful when the build and install +will be done by different users---for example, you might want to build a module +distribution and hand it off to a system administrator for installation (or do +it yourself, with super-user privileges). + +For example, you can build everything in one step, and then install everything +in a second step, by invoking the setup script twice:: + + python setup.py build + python setup.py install + +If you do this, you will notice that running the :command:`install` command +first runs the :command:`build` command, which---in this case---quickly notices +that it has nothing to do, since everything in the :file:`build` directory is +up-to-date. + +You may not need this ability to break things down often if all you do is +install modules downloaded off the 'net, but it's very handy for more advanced +tasks. If you get into distributing your own Python modules and extensions, +you'll run lots of individual Distutils commands on their own. + + +.. _inst-how-build-works: + +How building works +------------------ + +As implied above, the :command:`build` command is responsible for putting the +files to install into a *build directory*. By default, this is :file:`build` +under the distribution root; if you're excessively concerned with speed, or want +to keep the source tree pristine, you can change the build directory with the +:option:`!--build-base` option. For example:: + + python setup.py build --build-base=/path/to/pybuild/foo-1.0 + +(Or you could do this permanently with a directive in your system or personal +Distutils configuration file; see section :ref:`inst-config-files`.) Normally, this +isn't necessary. + +The default layout for the build tree is as follows:: + + --- build/ --- lib/ + or + --- build/ --- lib./ + temp./ + +where ```` expands to a brief description of the current OS/hardware +platform and Python version. The first form, with just a :file:`lib` directory, +is used for "pure module distributions"---that is, module distributions that +include only pure Python modules. If a module distribution contains any +extensions (modules written in C/C++), then the second form, with two ```` +directories, is used. In that case, the :file:`temp.{plat}` directory holds +temporary files generated by the compile/link process that don't actually get +installed. In either case, the :file:`lib` (or :file:`lib.{plat}`) directory +contains all Python modules (pure Python and extensions) that will be installed. + +In the future, more directories will be added to handle Python scripts, +documentation, binary executables, and whatever else is needed to handle the job +of installing Python modules and applications. + + +.. _inst-how-install-works: + +How installation works +---------------------- + +After the :command:`build` command runs (whether you run it explicitly, or the +:command:`install` command does it for you), the work of the :command:`install` +command is relatively simple: all it has to do is copy everything under +:file:`build/lib` (or :file:`build/lib.{plat}`) to your chosen installation +directory. + +If you don't choose an installation directory---i.e., if you just run ``setup.py +install``\ ---then the :command:`install` command installs to the standard +location for third-party Python modules. This location varies by platform and +by how you built/installed Python itself. On Unix (and Mac OS X, which is also +Unix-based), it also depends on whether the module distribution being installed +is pure Python or contains extensions ("non-pure"): + +.. tabularcolumns:: |l|l|l|l| + ++-----------------+-----------------------------------------------------+--------------------------------------------------+-------+ +| Platform | Standard installation location | Default value | Notes | ++=================+=====================================================+==================================================+=======+ +| Unix (pure) | :file:`{prefix}/lib/python{X.Y}/site-packages` | :file:`/usr/local/lib/python{X.Y}/site-packages` | \(1) | ++-----------------+-----------------------------------------------------+--------------------------------------------------+-------+ +| Unix (non-pure) | :file:`{exec-prefix}/lib/python{X.Y}/site-packages` | :file:`/usr/local/lib/python{X.Y}/site-packages` | \(1) | ++-----------------+-----------------------------------------------------+--------------------------------------------------+-------+ +| Windows | :file:`{prefix}\\Lib\\site-packages` | :file:`C:\\Python{XY}\\Lib\\site-packages` | \(2) | ++-----------------+-----------------------------------------------------+--------------------------------------------------+-------+ + +Notes: + +(1) + Most Linux distributions include Python as a standard part of the system, so + :file:`{prefix}` and :file:`{exec-prefix}` are usually both :file:`/usr` on + Linux. If you build Python yourself on Linux (or any Unix-like system), the + default :file:`{prefix}` and :file:`{exec-prefix}` are :file:`/usr/local`. + +(2) + The default installation directory on Windows was :file:`C:\\Program + Files\\Python` under Python 1.6a1, 1.5.2, and earlier. + +:file:`{prefix}` and :file:`{exec-prefix}` stand for the directories that Python +is installed to, and where it finds its libraries at run-time. They are always +the same under Windows, and very often the same under Unix and Mac OS X. You +can find out what your Python installation uses for :file:`{prefix}` and +:file:`{exec-prefix}` by running Python in interactive mode and typing a few +simple commands. Under Unix, just type ``python`` at the shell prompt. Under +Windows, choose :menuselection:`Start --> Programs --> Python X.Y --> +Python (command line)`. Once the interpreter is started, you type Python code +at the prompt. For example, on my Linux system, I type the three Python +statements shown below, and get the output as shown, to find out my +:file:`{prefix}` and :file:`{exec-prefix}`: + +.. code-block:: pycon + + Python 2.4 (#26, Aug 7 2004, 17:19:02) + Type "help", "copyright", "credits" or "license" for more information. + >>> import sys + >>> sys.prefix + '/usr' + >>> sys.exec_prefix + '/usr' + +A few other placeholders are used in this document: :file:`{X.Y}` stands for the +version of Python, for example ``3.2``; :file:`{abiflags}` will be replaced by +the value of :data:`sys.abiflags` or the empty string for platforms which don't +define ABI flags; :file:`{distname}` will be replaced by the name of the module +distribution being installed. Dots and capitalization are important in the +paths; for example, a value that uses ``python3.2`` on UNIX will typically use +``Python32`` on Windows. + +If you don't want to install modules to the standard location, or if you don't +have permission to write there, then you need to read about alternate +installations in section :ref:`inst-alt-install`. If you want to customize your +installation directories more heavily, see section :ref:`inst-custom-install` on +custom installations. + + +.. _inst-alt-install: + +Alternate Installation +====================== + +Often, it is necessary or desirable to install modules to a location other than +the standard location for third-party Python modules. For example, on a Unix +system you might not have permission to write to the standard third-party module +directory. Or you might wish to try out a module before making it a standard +part of your local Python installation. This is especially true when upgrading +a distribution already present: you want to make sure your existing base of +scripts still works with the new version before actually upgrading. + +The Distutils :command:`install` command is designed to make installing module +distributions to an alternate location simple and painless. The basic idea is +that you supply a base directory for the installation, and the +:command:`install` command picks a set of directories (called an *installation +scheme*) under this base directory in which to install files. The details +differ across platforms, so read whichever of the following sections applies to +you. + +Note that the various alternate installation schemes are mutually exclusive: you +can pass ``--user``, or ``--home``, or ``--prefix`` and ``--exec-prefix``, or +``--install-base`` and ``--install-platbase``, but you can't mix from these +groups. + + +.. _inst-alt-install-user: + +Alternate installation: the user scheme +--------------------------------------- + +This scheme is designed to be the most convenient solution for users that don't +have write permission to the global site-packages directory or don't want to +install into it. It is enabled with a simple option:: + + python setup.py install --user + +Files will be installed into subdirectories of :data:`site.USER_BASE` (written +as :file:`{userbase}` hereafter). This scheme installs pure Python modules and +extension modules in the same location (also known as :data:`site.USER_SITE`). +Here are the values for UNIX, including Mac OS X: + +=============== =========================================================== +Type of file Installation directory +=============== =========================================================== +modules :file:`{userbase}/lib/python{X.Y}/site-packages` +scripts :file:`{userbase}/bin` +data :file:`{userbase}` +C headers :file:`{userbase}/include/python{X.Y}{abiflags}/{distname}` +=============== =========================================================== + +And here are the values used on Windows: + +=============== =========================================================== +Type of file Installation directory +=============== =========================================================== +modules :file:`{userbase}\\Python{XY}\\site-packages` +scripts :file:`{userbase}\\Python{XY}\\Scripts` +data :file:`{userbase}` +C headers :file:`{userbase}\\Python{XY}\\Include\\{distname}` +=============== =========================================================== + +The advantage of using this scheme compared to the other ones described below is +that the user site-packages directory is under normal conditions always included +in :data:`sys.path` (see :mod:`site` for more information), which means that +there is no additional step to perform after running the :file:`setup.py` script +to finalize the installation. + +The :command:`build_ext` command also has a ``--user`` option to add +:file:`{userbase}/include` to the compiler search path for header files and +:file:`{userbase}/lib` to the compiler search path for libraries as well as to +the runtime search path for shared C libraries (rpath). + + +.. _inst-alt-install-home: + +Alternate installation: the home scheme +--------------------------------------- + +The idea behind the "home scheme" is that you build and maintain a personal +stash of Python modules. This scheme's name is derived from the idea of a +"home" directory on Unix, since it's not unusual for a Unix user to make their +home directory have a layout similar to :file:`/usr/` or :file:`/usr/local/`. +This scheme can be used by anyone, regardless of the operating system they +are installing for. + +Installing a new module distribution is as simple as :: + + python setup.py install --home= + +where you can supply any directory you like for the :option:`!--home` option. On +Unix, lazy typists can just type a tilde (``~``); the :command:`install` command +will expand this to your home directory:: + + python setup.py install --home=~ + +To make Python find the distributions installed with this scheme, you may have +to :ref:`modify Python's search path ` or edit +:mod:`sitecustomize` (see :mod:`site`) to call :func:`site.addsitedir` or edit +:data:`sys.path`. + +The :option:`!--home` option defines the installation base directory. Files are +installed to the following directories under the installation base as follows: + +=============== =========================================================== +Type of file Installation directory +=============== =========================================================== +modules :file:`{home}/lib/python` +scripts :file:`{home}/bin` +data :file:`{home}` +C headers :file:`{home}/include/python/{distname}` +=============== =========================================================== + +(Mentally replace slashes with backslashes if you're on Windows.) + + +.. _inst-alt-install-prefix-unix: + +Alternate installation: Unix (the prefix scheme) +------------------------------------------------ + +The "prefix scheme" is useful when you wish to use one Python installation to +perform the build/install (i.e., to run the setup script), but install modules +into the third-party module directory of a different Python installation (or +something that looks like a different Python installation). If this sounds a +trifle unusual, it is---that's why the user and home schemes come before. However, +there are at least two known cases where the prefix scheme will be useful. + +First, consider that many Linux distributions put Python in :file:`/usr`, rather +than the more traditional :file:`/usr/local`. This is entirely appropriate, +since in those cases Python is part of "the system" rather than a local add-on. +However, if you are installing Python modules from source, you probably want +them to go in :file:`/usr/local/lib/python2.{X}` rather than +:file:`/usr/lib/python2.{X}`. This can be done with :: + + /usr/bin/python setup.py install --prefix=/usr/local + +Another possibility is a network filesystem where the name used to write to a +remote directory is different from the name used to read it: for example, the +Python interpreter accessed as :file:`/usr/local/bin/python` might search for +modules in :file:`/usr/local/lib/python2.{X}`, but those modules would have to +be installed to, say, :file:`/mnt/{@server}/export/lib/python2.{X}`. This could +be done with :: + + /usr/local/bin/python setup.py install --prefix=/mnt/@server/export + +In either case, the :option:`!--prefix` option defines the installation base, and +the :option:`!--exec-prefix` option defines the platform-specific installation +base, which is used for platform-specific files. (Currently, this just means +non-pure module distributions, but could be expanded to C libraries, binary +executables, etc.) If :option:`!--exec-prefix` is not supplied, it defaults to +:option:`!--prefix`. Files are installed as follows: + +================= ========================================================== +Type of file Installation directory +================= ========================================================== +Python modules :file:`{prefix}/lib/python{X.Y}/site-packages` +extension modules :file:`{exec-prefix}/lib/python{X.Y}/site-packages` +scripts :file:`{prefix}/bin` +data :file:`{prefix}` +C headers :file:`{prefix}/include/python{X.Y}{abiflags}/{distname}` +================= ========================================================== + +There is no requirement that :option:`!--prefix` or :option:`!--exec-prefix` +actually point to an alternate Python installation; if the directories listed +above do not already exist, they are created at installation time. + +Incidentally, the real reason the prefix scheme is important is simply that a +standard Unix installation uses the prefix scheme, but with :option:`!--prefix` +and :option:`!--exec-prefix` supplied by Python itself as ``sys.prefix`` and +``sys.exec_prefix``. Thus, you might think you'll never use the prefix scheme, +but every time you run ``python setup.py install`` without any other options, +you're using it. + +Note that installing extensions to an alternate Python installation has no +effect on how those extensions are built: in particular, the Python header files +(:file:`Python.h` and friends) installed with the Python interpreter used to run +the setup script will be used in compiling extensions. It is your +responsibility to ensure that the interpreter used to run extensions installed +in this way is compatible with the interpreter used to build them. The best way +to do this is to ensure that the two interpreters are the same version of Python +(possibly different builds, or possibly copies of the same build). (Of course, +if your :option:`!--prefix` and :option:`!--exec-prefix` don't even point to an +alternate Python installation, this is immaterial.) + + +.. _inst-alt-install-prefix-windows: + +Alternate installation: Windows (the prefix scheme) +--------------------------------------------------- + +Windows has no concept of a user's home directory, and since the standard Python +installation under Windows is simpler than under Unix, the :option:`!--prefix` +option has traditionally been used to install additional packages in separate +locations on Windows. :: + + python setup.py install --prefix="\Temp\Python" + +to install modules to the :file:`\\Temp\\Python` directory on the current drive. + +The installation base is defined by the :option:`!--prefix` option; the +:option:`!--exec-prefix` option is not supported under Windows, which means that +pure Python modules and extension modules are installed into the same location. +Files are installed as follows: + +=============== ========================================================== +Type of file Installation directory +=============== ========================================================== +modules :file:`{prefix}\\Lib\\site-packages` +scripts :file:`{prefix}\\Scripts` +data :file:`{prefix}` +C headers :file:`{prefix}\\Include\\{distname}` +=============== ========================================================== + + +.. _inst-custom-install: + +Custom Installation +=================== + +Sometimes, the alternate installation schemes described in section +:ref:`inst-alt-install` just don't do what you want. You might want to tweak just +one or two directories while keeping everything under the same base directory, +or you might want to completely redefine the installation scheme. In either +case, you're creating a *custom installation scheme*. + +To create a custom installation scheme, you start with one of the alternate +schemes and override some of the installation directories used for the various +types of files, using these options: + +====================== ======================= +Type of file Override option +====================== ======================= +Python modules ``--install-purelib`` +extension modules ``--install-platlib`` +all modules ``--install-lib`` +scripts ``--install-scripts`` +data ``--install-data`` +C headers ``--install-headers`` +====================== ======================= + +These override options can be relative, absolute, +or explicitly defined in terms of one of the installation base directories. +(There are two installation base directories, and they are normally the +same---they only differ when you use the Unix "prefix scheme" and supply +different ``--prefix`` and ``--exec-prefix`` options; using ``--install-lib`` +will override values computed or given for ``--install-purelib`` and +``--install-platlib``, and is recommended for schemes that don't make a +difference between Python and extension modules.) + +For example, say you're installing a module distribution to your home directory +under Unix---but you want scripts to go in :file:`~/scripts` rather than +:file:`~/bin`. As you might expect, you can override this directory with the +:option:`!--install-scripts` option; in this case, it makes most sense to supply +a relative path, which will be interpreted relative to the installation base +directory (your home directory, in this case):: + + python setup.py install --home=~ --install-scripts=scripts + +Another Unix example: suppose your Python installation was built and installed +with a prefix of :file:`/usr/local/python`, so under a standard installation +scripts will wind up in :file:`/usr/local/python/bin`. If you want them in +:file:`/usr/local/bin` instead, you would supply this absolute directory for the +:option:`!--install-scripts` option:: + + python setup.py install --install-scripts=/usr/local/bin + +(This performs an installation using the "prefix scheme", where the prefix is +whatever your Python interpreter was installed with--- :file:`/usr/local/python` +in this case.) + +If you maintain Python on Windows, you might want third-party modules to live in +a subdirectory of :file:`{prefix}`, rather than right in :file:`{prefix}` +itself. This is almost as easy as customizing the script installation +directory---you just have to remember that there are two types of modules +to worry about, Python and extension modules, which can conveniently be both +controlled by one option:: + + python setup.py install --install-lib=Site + +The specified installation directory is relative to :file:`{prefix}`. Of +course, you also have to ensure that this directory is in Python's module +search path, such as by putting a :file:`.pth` file in a site directory (see +:mod:`site`). See section :ref:`inst-search-path` to find out how to modify +Python's search path. + +If you want to define an entire installation scheme, you just have to supply all +of the installation directory options. The recommended way to do this is to +supply relative paths; for example, if you want to maintain all Python +module-related files under :file:`python` in your home directory, and you want a +separate directory for each platform that you use your home directory from, you +might define the following installation scheme:: + + python setup.py install --home=~ \ + --install-purelib=python/lib \ + --install-platlib=python/lib.$PLAT \ + --install-scripts=python/scripts + --install-data=python/data + +or, equivalently, :: + + python setup.py install --home=~/python \ + --install-purelib=lib \ + --install-platlib='lib.$PLAT' \ + --install-scripts=scripts + --install-data=data + +``$PLAT`` is not (necessarily) an environment variable---it will be expanded by +the Distutils as it parses your command line options, just as it does when +parsing your configuration file(s). + +Obviously, specifying the entire installation scheme every time you install a +new module distribution would be very tedious. Thus, you can put these options +into your Distutils config file (see section :ref:`inst-config-files`): + +.. code-block:: ini + + [install] + install-base=$HOME + install-purelib=python/lib + install-platlib=python/lib.$PLAT + install-scripts=python/scripts + install-data=python/data + +or, equivalently, + +.. code-block:: ini + + [install] + install-base=$HOME/python + install-purelib=lib + install-platlib=lib.$PLAT + install-scripts=scripts + install-data=data + +Note that these two are *not* equivalent if you supply a different installation +base directory when you run the setup script. For example, :: + + python setup.py install --install-base=/tmp + +would install pure modules to :file:`/tmp/python/lib` in the first case, and +to :file:`/tmp/lib` in the second case. (For the second case, you probably +want to supply an installation base of :file:`/tmp/python`.) + +You probably noticed the use of ``$HOME`` and ``$PLAT`` in the sample +configuration file input. These are Distutils configuration variables, which +bear a strong resemblance to environment variables. In fact, you can use +environment variables in config files on platforms that have such a notion but +the Distutils additionally define a few extra variables that may not be in your +environment, such as ``$PLAT``. (And of course, on systems that don't have +environment variables, such as Mac OS 9, the configuration variables supplied by +the Distutils are the only ones you can use.) See section :ref:`inst-config-files` +for details. + +.. note:: When a :ref:`virtual environment ` is activated, any options + that change the installation path will be ignored from all distutils configuration + files to prevent inadvertently installing projects outside of the virtual + environment. + +.. XXX need some Windows examples---when would custom installation schemes be + needed on those platforms? + + +.. XXX Move this to Doc/using + +.. _inst-search-path: + +Modifying Python's Search Path +------------------------------ + +When the Python interpreter executes an :keyword:`import` statement, it searches +for both Python code and extension modules along a search path. A default value +for the path is configured into the Python binary when the interpreter is built. +You can determine the path by importing the :mod:`sys` module and printing the +value of ``sys.path``. :: + + $ python + Python 2.2 (#11, Oct 3 2002, 13:31:27) + [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-112)] on linux2 + Type "help", "copyright", "credits" or "license" for more information. + >>> import sys + >>> sys.path + ['', '/usr/local/lib/python2.3', '/usr/local/lib/python2.3/plat-linux2', + '/usr/local/lib/python2.3/lib-tk', '/usr/local/lib/python2.3/lib-dynload', + '/usr/local/lib/python2.3/site-packages'] + >>> + +The null string in ``sys.path`` represents the current working directory. + +The expected convention for locally installed packages is to put them in the +:file:`{...}/site-packages/` directory, but you may want to install Python +modules into some arbitrary directory. For example, your site may have a +convention of keeping all software related to the web server under :file:`/www`. +Add-on Python modules might then belong in :file:`/www/python`, and in order to +import them, this directory must be added to ``sys.path``. There are several +different ways to add the directory. + +The most convenient way is to add a path configuration file to a directory +that's already on Python's path, usually to the :file:`.../site-packages/` +directory. Path configuration files have an extension of :file:`.pth`, and each +line must contain a single path that will be appended to ``sys.path``. (Because +the new paths are appended to ``sys.path``, modules in the added directories +will not override standard modules. This means you can't use this mechanism for +installing fixed versions of standard modules.) + +Paths can be absolute or relative, in which case they're relative to the +directory containing the :file:`.pth` file. See the documentation of +the :mod:`site` module for more information. + +A slightly less convenient way is to edit the :file:`site.py` file in Python's +standard library, and modify ``sys.path``. :file:`site.py` is automatically +imported when the Python interpreter is executed, unless the :option:`-S` switch +is supplied to suppress this behaviour. So you could simply edit +:file:`site.py` and add two lines to it: + +.. code-block:: python + + import sys + sys.path.append('/www/python/') + +However, if you reinstall the same major version of Python (perhaps when +upgrading from 2.2 to 2.2.2, for example) :file:`site.py` will be overwritten by +the stock version. You'd have to remember that it was modified and save a copy +before doing the installation. + +There are two environment variables that can modify ``sys.path``. +:envvar:`PYTHONHOME` sets an alternate value for the prefix of the Python +installation. For example, if :envvar:`PYTHONHOME` is set to ``/www/python``, +the search path will be set to ``['', '/www/python/lib/pythonX.Y/', +'/www/python/lib/pythonX.Y/plat-linux2', ...]``. + +The :envvar:`PYTHONPATH` variable can be set to a list of paths that will be +added to the beginning of ``sys.path``. For example, if :envvar:`PYTHONPATH` is +set to ``/www/python:/opt/py``, the search path will begin with +``['/www/python', '/opt/py']``. (Note that directories must exist in order to +be added to ``sys.path``; the :mod:`site` module removes paths that don't +exist.) + +Finally, ``sys.path`` is just a regular Python list, so any Python application +can modify it by adding or removing entries. + + +.. _inst-config-files: + +Distutils Configuration Files +============================= + +As mentioned above, you can use Distutils configuration files to record personal +or site preferences for any Distutils options. That is, any option to any +command can be stored in one of two or three (depending on your platform) +configuration files, which will be consulted before the command-line is parsed. +This means that configuration files will override default values, and the +command-line will in turn override configuration files. Furthermore, if +multiple configuration files apply, values from "earlier" files are overridden +by "later" files. + + +.. _inst-config-filenames: + +Location and names of config files +---------------------------------- + +The names and locations of the configuration files vary slightly across +platforms. On Unix and Mac OS X, the three configuration files (in the order +they are processed) are: + ++--------------+----------------------------------------------------------+-------+ +| Type of file | Location and filename | Notes | ++==============+==========================================================+=======+ +| system | :file:`{prefix}/lib/python{ver}/distutils/distutils.cfg` | \(1) | ++--------------+----------------------------------------------------------+-------+ +| personal | :file:`$HOME/.pydistutils.cfg` | \(2) | ++--------------+----------------------------------------------------------+-------+ +| local | :file:`setup.cfg` | \(3) | ++--------------+----------------------------------------------------------+-------+ + +And on Windows, the configuration files are: + ++--------------+-------------------------------------------------+-------+ +| Type of file | Location and filename | Notes | ++==============+=================================================+=======+ +| system | :file:`{prefix}\\Lib\\distutils\\distutils.cfg` | \(4) | ++--------------+-------------------------------------------------+-------+ +| personal | :file:`%HOME%\\pydistutils.cfg` | \(5) | ++--------------+-------------------------------------------------+-------+ +| local | :file:`setup.cfg` | \(3) | ++--------------+-------------------------------------------------+-------+ + +On all platforms, the "personal" file can be temporarily disabled by +passing the `--no-user-cfg` option. + +Notes: + +(1) + Strictly speaking, the system-wide configuration file lives in the directory + where the Distutils are installed; under Python 1.6 and later on Unix, this is + as shown. For Python 1.5.2, the Distutils will normally be installed to + :file:`{prefix}/lib/python1.5/site-packages/distutils`, so the system + configuration file should be put there under Python 1.5.2. + +(2) + On Unix, if the :envvar:`HOME` environment variable is not defined, the user's + home directory will be determined with the :func:`getpwuid` function from the + standard :mod:`pwd` module. This is done by the :func:`os.path.expanduser` + function used by Distutils. + +(3) + I.e., in the current directory (usually the location of the setup script). + +(4) + (See also note (1).) Under Python 1.6 and later, Python's default "installation + prefix" is :file:`C:\\Python`, so the system configuration file is normally + :file:`C:\\Python\\Lib\\distutils\\distutils.cfg`. Under Python 1.5.2, the + default prefix was :file:`C:\\Program Files\\Python`, and the Distutils were not + part of the standard library---so the system configuration file would be + :file:`C:\\Program Files\\Python\\distutils\\distutils.cfg` in a standard Python + 1.5.2 installation under Windows. + +(5) + On Windows, if the :envvar:`HOME` environment variable is not defined, + :envvar:`USERPROFILE` then :envvar:`HOMEDRIVE` and :envvar:`HOMEPATH` will + be tried. This is done by the :func:`os.path.expanduser` function used + by Distutils. + + +.. _inst-config-syntax: + +Syntax of config files +---------------------- + +The Distutils configuration files all have the same syntax. The config files +are grouped into sections. There is one section for each Distutils command, +plus a ``global`` section for global options that affect every command. Each +section consists of one option per line, specified as ``option=value``. + +For example, the following is a complete config file that just forces all +commands to run quietly by default: + +.. code-block:: ini + + [global] + verbose=0 + +If this is installed as the system config file, it will affect all processing of +any Python module distribution by any user on the current system. If it is +installed as your personal config file (on systems that support them), it will +affect only module distributions processed by you. And if it is used as the +:file:`setup.cfg` for a particular module distribution, it affects only that +distribution. + +You could override the default "build base" directory and make the +:command:`build\*` commands always forcibly rebuild all files with the +following: + +.. code-block:: ini + + [build] + build-base=blib + force=1 + +which corresponds to the command-line arguments :: + + python setup.py build --build-base=blib --force + +except that including the :command:`build` command on the command-line means +that command will be run. Including a particular command in config files has no +such implication; it only means that if the command is run, the options in the +config file will apply. (Or if other commands that derive values from it are +run, they will use the values in the config file.) + +You can find out the complete list of options for any command using the +:option:`!--help` option, e.g.:: + + python setup.py build --help + +and you can find out the complete list of global options by using +:option:`!--help` without a command:: + + python setup.py --help + +See also the "Reference" section of the "Distributing Python Modules" manual. + + +.. _inst-building-ext: + +Building Extensions: Tips and Tricks +==================================== + +Whenever possible, the Distutils try to use the configuration information made +available by the Python interpreter used to run the :file:`setup.py` script. +For example, the same compiler and linker flags used to compile Python will also +be used for compiling extensions. Usually this will work well, but in +complicated situations this might be inappropriate. This section discusses how +to override the usual Distutils behaviour. + + +.. _inst-tweak-flags: + +Tweaking compiler/linker flags +------------------------------ + +Compiling a Python extension written in C or C++ will sometimes require +specifying custom flags for the compiler and linker in order to use a particular +library or produce a special kind of object code. This is especially true if the +extension hasn't been tested on your platform, or if you're trying to +cross-compile Python. + +In the most general case, the extension author might have foreseen that +compiling the extensions would be complicated, and provided a :file:`Setup` file +for you to edit. This will likely only be done if the module distribution +contains many separate extension modules, or if they often require elaborate +sets of compiler flags in order to work. + +A :file:`Setup` file, if present, is parsed in order to get a list of extensions +to build. Each line in a :file:`Setup` describes a single module. Lines have +the following structure:: + + module ... [sourcefile ...] [cpparg ...] [library ...] + + +Let's examine each of the fields in turn. + +* *module* is the name of the extension module to be built, and should be a + valid Python identifier. You can't just change this in order to rename a module + (edits to the source code would also be needed), so this should be left alone. + +* *sourcefile* is anything that's likely to be a source code file, at least + judging by the filename. Filenames ending in :file:`.c` are assumed to be + written in C, filenames ending in :file:`.C`, :file:`.cc`, and :file:`.c++` are + assumed to be C++, and filenames ending in :file:`.m` or :file:`.mm` are assumed + to be in Objective C. + +* *cpparg* is an argument for the C preprocessor, and is anything starting with + :option:`!-I`, :option:`!-D`, :option:`!-U` or :option:`!-C`. + +* *library* is anything ending in :file:`.a` or beginning with :option:`!-l` or + :option:`!-L`. + +If a particular platform requires a special library on your platform, you can +add it by editing the :file:`Setup` file and running ``python setup.py build``. +For example, if the module defined by the line :: + + foo foomodule.c + +must be linked with the math library :file:`libm.a` on your platform, simply add +:option:`!-lm` to the line:: + + foo foomodule.c -lm + +Arbitrary switches intended for the compiler or the linker can be supplied with +the :option:`!-Xcompiler` *arg* and :option:`!-Xlinker` *arg* options:: + + foo foomodule.c -Xcompiler -o32 -Xlinker -shared -lm + +The next option after :option:`!-Xcompiler` and :option:`!-Xlinker` will be +appended to the proper command line, so in the above example the compiler will +be passed the :option:`!-o32` option, and the linker will be passed +:option:`!-shared`. If a compiler option requires an argument, you'll have to +supply multiple :option:`!-Xcompiler` options; for example, to pass ``-x c++`` +the :file:`Setup` file would have to contain ``-Xcompiler -x -Xcompiler c++``. + +Compiler flags can also be supplied through setting the :envvar:`CFLAGS` +environment variable. If set, the contents of :envvar:`CFLAGS` will be added to +the compiler flags specified in the :file:`Setup` file. + + +.. _inst-non-ms-compilers: + +Using non-Microsoft compilers on Windows +---------------------------------------- + +.. sectionauthor:: Rene Liebscher + + + +Borland/CodeGear C++ +^^^^^^^^^^^^^^^^^^^^ + +This subsection describes the necessary steps to use Distutils with the Borland +C++ compiler version 5.5. First you have to know that Borland's object file +format (OMF) is different from the format used by the Python version you can +download from the Python or ActiveState Web site. (Python is built with +Microsoft Visual C++, which uses COFF as the object file format.) For this +reason you have to convert Python's library :file:`python25.lib` into the +Borland format. You can do this as follows: + +.. Should we mention that users have to create cfg-files for the compiler? +.. see also http://community.borland.com/article/0,1410,21205,00.html + +:: + + coff2omf python25.lib python25_bcpp.lib + +The :file:`coff2omf` program comes with the Borland compiler. The file +:file:`python25.lib` is in the :file:`Libs` directory of your Python +installation. If your extension uses other libraries (zlib, ...) you have to +convert them too. + +The converted files have to reside in the same directories as the normal +libraries. + +How does Distutils manage to use these libraries with their changed names? If +the extension needs a library (eg. :file:`foo`) Distutils checks first if it +finds a library with suffix :file:`_bcpp` (eg. :file:`foo_bcpp.lib`) and then +uses this library. In the case it doesn't find such a special library it uses +the default name (:file:`foo.lib`.) [#]_ + +To let Distutils compile your extension with Borland C++ you now have to type:: + + python setup.py build --compiler=bcpp + +If you want to use the Borland C++ compiler as the default, you could specify +this in your personal or system-wide configuration file for Distutils (see +section :ref:`inst-config-files`.) + + +.. seealso:: + + `C++Builder Compiler `_ + Information about the free C++ compiler from Borland, including links to the + download pages. + + `Creating Python Extensions Using Borland's Free Compiler `_ + Document describing how to use Borland's free command-line C++ compiler to build + Python. + + +GNU C / Cygwin / MinGW +^^^^^^^^^^^^^^^^^^^^^^ + +This section describes the necessary steps to use Distutils with the GNU C/C++ +compilers in their Cygwin and MinGW distributions. [#]_ For a Python interpreter +that was built with Cygwin, everything should work without any of these +following steps. + +Not all extensions can be built with MinGW or Cygwin, but many can. Extensions +most likely to not work are those that use C++ or depend on Microsoft Visual C +extensions. + +To let Distutils compile your extension with Cygwin you have to type:: + + python setup.py build --compiler=cygwin + +and for Cygwin in no-cygwin mode [#]_ or for MinGW type:: + + python setup.py build --compiler=mingw32 + +If you want to use any of these options/compilers as default, you should +consider writing it in your personal or system-wide configuration file for +Distutils (see section :ref:`inst-config-files`.) + +Older Versions of Python and MinGW +"""""""""""""""""""""""""""""""""" +The following instructions only apply if you're using a version of Python +inferior to 2.4.1 with a MinGW inferior to 3.0.0 (with +binutils-2.13.90-20030111-1). + +These compilers require some special libraries. This task is more complex than +for Borland's C++, because there is no program to convert the library. First +you have to create a list of symbols which the Python DLL exports. (You can find +a good program for this task at +https://sourceforge.net/projects/mingw/files/MinGW/Extension/pexports/). + +.. I don't understand what the next line means. --amk +.. (inclusive the references on data structures.) + +:: + + pexports python25.dll >python25.def + +The location of an installed :file:`python25.dll` will depend on the +installation options and the version and language of Windows. In a "just for +me" installation, it will appear in the root of the installation directory. In +a shared installation, it will be located in the system directory. + +Then you can create from these information an import library for gcc. :: + + /cygwin/bin/dlltool --dllname python25.dll --def python25.def --output-lib libpython25.a + +The resulting library has to be placed in the same directory as +:file:`python25.lib`. (Should be the :file:`libs` directory under your Python +installation directory.) + +If your extension uses other libraries (zlib,...) you might have to convert +them too. The converted files have to reside in the same directories as the +normal libraries do. + + +.. seealso:: + + `Building Python modules on MS Windows platform with MinGW `_ + Information about building the required libraries for the MinGW environment. + + +.. rubric:: Footnotes + +.. [#] This also means you could replace all existing COFF-libraries with OMF-libraries + of the same name. + +.. [#] Check https://www.sourceware.org/cygwin/ and http://www.mingw.org/ for more + information + +.. [#] Then you have no POSIX emulation available, but you also don't need + :file:`cygwin1.dll`. diff --git a/cpython_2/environment/repo/Doc/installing/index.rst b/cpython_2/environment/repo/Doc/installing/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..31e9b0bde0724440d4a876b311476a506ef01dae --- /dev/null +++ b/cpython_2/environment/repo/Doc/installing/index.rst @@ -0,0 +1,241 @@ +.. highlight:: none + +.. _installing-index: + +************************* +Installing Python Modules +************************* + +:Email: distutils-sig@python.org + +As a popular open source development project, Python has an active +supporting community of contributors and users that also make their software +available for other Python developers to use under open source license terms. + +This allows Python users to share and collaborate effectively, benefiting +from the solutions others have already created to common (and sometimes +even rare!) problems, as well as potentially contributing their own +solutions to the common pool. + +This guide covers the installation part of the process. For a guide to +creating and sharing your own Python projects, refer to the +:ref:`distribution guide `. + +.. note:: + + For corporate and other institutional users, be aware that many + organisations have their own policies around using and contributing to + open source software. Please take such policies into account when making + use of the distribution and installation tools provided with Python. + + +Key terms +========= + +* ``pip`` is the preferred installer program. Starting with Python 3.4, it + is included by default with the Python binary installers. +* A *virtual environment* is a semi-isolated Python environment that allows + packages to be installed for use by a particular application, rather than + being installed system wide. +* ``venv`` is the standard tool for creating virtual environments, and has + been part of Python since Python 3.3. Starting with Python 3.4, it + defaults to installing ``pip`` into all created virtual environments. +* ``virtualenv`` is a third party alternative (and predecessor) to + ``venv``. It allows virtual environments to be used on versions of + Python prior to 3.4, which either don't provide ``venv`` at all, or + aren't able to automatically install ``pip`` into created environments. +* The `Python Packaging Index `__ is a public + repository of open source licensed packages made available for use by + other Python users. +* the `Python Packaging Authority + `__ is the group of + developers and documentation authors responsible for the maintenance and + evolution of the standard packaging tools and the associated metadata and + file format standards. They maintain a variety of tools, documentation, + and issue trackers on both `GitHub `__ and + `Bitbucket `__. +* ``distutils`` is the original build and distribution system first added to + the Python standard library in 1998. While direct use of ``distutils`` is + being phased out, it still laid the foundation for the current packaging + and distribution infrastructure, and it not only remains part of the + standard library, but its name lives on in other ways (such as the name + of the mailing list used to coordinate Python packaging standards + development). + +.. versionchanged:: 3.5 + The use of ``venv`` is now recommended for creating virtual environments. + +.. seealso:: + + `Python Packaging User Guide: Creating and using virtual environments + `__ + + +Basic usage +=========== + +The standard packaging tools are all designed to be used from the command +line. + +The following command will install the latest version of a module and its +dependencies from the Python Packaging Index:: + + python -m pip install SomePackage + +.. note:: + + For POSIX users (including Mac OS X and Linux users), the examples in + this guide assume the use of a :term:`virtual environment`. + + For Windows users, the examples in this guide assume that the option to + adjust the system PATH environment variable was selected when installing + Python. + +It's also possible to specify an exact or minimum version directly on the +command line. When using comparator operators such as ``>``, ``<`` or some other +special character which get interpreted by shell, the package name and the +version should be enclosed within double quotes:: + + python -m pip install SomePackage==1.0.4 # specific version + python -m pip install "SomePackage>=1.0.4" # minimum version + +Normally, if a suitable module is already installed, attempting to install +it again will have no effect. Upgrading existing modules must be requested +explicitly:: + + python -m pip install --upgrade SomePackage + +More information and resources regarding ``pip`` and its capabilities can be +found in the `Python Packaging User Guide `__. + +Creation of virtual environments is done through the :mod:`venv` module. +Installing packages into an active virtual environment uses the commands shown +above. + +.. seealso:: + + `Python Packaging User Guide: Installing Python Distribution Packages + `__ + + +How do I ...? +============= + +These are quick answers or links for some common tasks. + +... install ``pip`` in versions of Python prior to Python 3.4? +-------------------------------------------------------------- + +Python only started bundling ``pip`` with Python 3.4. For earlier versions, +``pip`` needs to be "bootstrapped" as described in the Python Packaging +User Guide. + +.. seealso:: + + `Python Packaging User Guide: Requirements for Installing Packages + `__ + + +.. installing-per-user-installation: + +... install packages just for the current user? +----------------------------------------------- + +Passing the ``--user`` option to ``python -m pip install`` will install a +package just for the current user, rather than for all users of the system. + + +... install scientific Python packages? +--------------------------------------- + +A number of scientific Python packages have complex binary dependencies, and +aren't currently easy to install using ``pip`` directly. At this point in +time, it will often be easier for users to install these packages by +`other means `__ +rather than attempting to install them with ``pip``. + +.. seealso:: + + `Python Packaging User Guide: Installing Scientific Packages + `__ + + +... work with multiple versions of Python installed in parallel? +---------------------------------------------------------------- + +On Linux, Mac OS X, and other POSIX systems, use the versioned Python commands +in combination with the ``-m`` switch to run the appropriate copy of +``pip``:: + + python2 -m pip install SomePackage # default Python 2 + python2.7 -m pip install SomePackage # specifically Python 2.7 + python3 -m pip install SomePackage # default Python 3 + python3.4 -m pip install SomePackage # specifically Python 3.4 + +Appropriately versioned ``pip`` commands may also be available. + +On Windows, use the ``py`` Python launcher in combination with the ``-m`` +switch:: + + py -2 -m pip install SomePackage # default Python 2 + py -2.7 -m pip install SomePackage # specifically Python 2.7 + py -3 -m pip install SomePackage # default Python 3 + py -3.4 -m pip install SomePackage # specifically Python 3.4 + +.. other questions: + + Once the Development & Deployment part of PPUG is fleshed out, some of + those sections should be linked from new questions here (most notably, + we should have a question about avoiding depending on PyPI that links to + https://packaging.python.org/en/latest/mirrors/) + + +Common installation issues +========================== + +Installing into the system Python on Linux +------------------------------------------ + +On Linux systems, a Python installation will typically be included as part +of the distribution. Installing into this Python installation requires +root access to the system, and may interfere with the operation of the +system package manager and other components of the system if a component +is unexpectedly upgraded using ``pip``. + +On such systems, it is often better to use a virtual environment or a +per-user installation when installing packages with ``pip``. + + +Pip not installed +----------------- + +It is possible that ``pip`` does not get installed by default. One potential fix is:: + + python -m ensurepip --default-pip + +There are also additional resources for `installing pip. +`__ + + +Installing binary extensions +---------------------------- + +Python has typically relied heavily on source based distribution, with end +users being expected to compile extension modules from source as part of +the installation process. + +With the introduction of support for the binary ``wheel`` format, and the +ability to publish wheels for at least Windows and Mac OS X through the +Python Packaging Index, this problem is expected to diminish over time, +as users are more regularly able to install pre-built extensions rather +than needing to build them themselves. + +Some of the solutions for installing `scientific software +`__ +that are not yet available as pre-built ``wheel`` files may also help with +obtaining other binary extensions without needing to build them locally. + +.. seealso:: + + `Python Packaging User Guide: Binary Extensions + `__ diff --git a/cpython_2/environment/repo/Doc/library/2to3.rst b/cpython_2/environment/repo/Doc/library/2to3.rst new file mode 100644 index 0000000000000000000000000000000000000000..1d7bd262872905654cd67049dce165955b17356a --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/2to3.rst @@ -0,0 +1,480 @@ +.. _2to3-reference: + +2to3 - Automated Python 2 to 3 code translation +=============================================== + +.. sectionauthor:: Benjamin Peterson + +2to3 is a Python program that reads Python 2.x source code and applies a series +of *fixers* to transform it into valid Python 3.x code. The standard library +contains a rich set of fixers that will handle almost all code. 2to3 supporting +library :mod:`lib2to3` is, however, a flexible and generic library, so it is +possible to write your own fixers for 2to3. + + +.. _2to3-using: + +Using 2to3 +---------- + +2to3 will usually be installed with the Python interpreter as a script. It is +also located in the :file:`Tools/scripts` directory of the Python root. + +2to3's basic arguments are a list of files or directories to transform. The +directories are recursively traversed for Python sources. + +Here is a sample Python 2.x source file, :file:`example.py`:: + + def greet(name): + print "Hello, {0}!".format(name) + print "What's your name?" + name = raw_input() + greet(name) + +It can be converted to Python 3.x code via 2to3 on the command line: + +.. code-block:: shell-session + + $ 2to3 example.py + +A diff against the original source file is printed. 2to3 can also write the +needed modifications right back to the source file. (A backup of the original +file is made unless :option:`!-n` is also given.) Writing the changes back is +enabled with the :option:`!-w` flag: + +.. code-block:: shell-session + + $ 2to3 -w example.py + +After transformation, :file:`example.py` looks like this:: + + def greet(name): + print("Hello, {0}!".format(name)) + print("What's your name?") + name = input() + greet(name) + +Comments and exact indentation are preserved throughout the translation process. + +By default, 2to3 runs a set of :ref:`predefined fixers <2to3-fixers>`. The +:option:`!-l` flag lists all available fixers. An explicit set of fixers to run +can be given with :option:`!-f`. Likewise the :option:`!-x` explicitly disables a +fixer. The following example runs only the ``imports`` and ``has_key`` fixers: + +.. code-block:: shell-session + + $ 2to3 -f imports -f has_key example.py + +This command runs every fixer except the ``apply`` fixer: + +.. code-block:: shell-session + + $ 2to3 -x apply example.py + +Some fixers are *explicit*, meaning they aren't run by default and must be +listed on the command line to be run. Here, in addition to the default fixers, +the ``idioms`` fixer is run: + +.. code-block:: shell-session + + $ 2to3 -f all -f idioms example.py + +Notice how passing ``all`` enables all default fixers. + +Sometimes 2to3 will find a place in your source code that needs to be changed, +but 2to3 cannot fix automatically. In this case, 2to3 will print a warning +beneath the diff for a file. You should address the warning in order to have +compliant 3.x code. + +2to3 can also refactor doctests. To enable this mode, use the :option:`!-d` +flag. Note that *only* doctests will be refactored. This also doesn't require +the module to be valid Python. For example, doctest like examples in a reST +document could also be refactored with this option. + +The :option:`!-v` option enables output of more information on the translation +process. + +Since some print statements can be parsed as function calls or statements, 2to3 +cannot always read files containing the print function. When 2to3 detects the +presence of the ``from __future__ import print_function`` compiler directive, it +modifies its internal grammar to interpret :func:`print` as a function. This +change can also be enabled manually with the :option:`!-p` flag. Use +:option:`!-p` to run fixers on code that already has had its print statements +converted. Also :option:`!-e` can be used to make :func:`exec` a function. + +The :option:`!-o` or :option:`!--output-dir` option allows specification of an +alternate directory for processed output files to be written to. The +:option:`!-n` flag is required when using this as backup files do not make sense +when not overwriting the input files. + +.. versionadded:: 3.2.3 + The :option:`!-o` option was added. + +The :option:`!-W` or :option:`!--write-unchanged-files` flag tells 2to3 to always +write output files even if no changes were required to the file. This is most +useful with :option:`!-o` so that an entire Python source tree is copied with +translation from one directory to another. +This option implies the :option:`!-w` flag as it would not make sense otherwise. + +.. versionadded:: 3.2.3 + The :option:`!-W` flag was added. + +The :option:`!--add-suffix` option specifies a string to append to all output +filenames. The :option:`!-n` flag is required when specifying this as backups +are not necessary when writing to different filenames. Example: + +.. code-block:: shell-session + + $ 2to3 -n -W --add-suffix=3 example.py + +Will cause a converted file named ``example.py3`` to be written. + +.. versionadded:: 3.2.3 + The :option:`!--add-suffix` option was added. + +To translate an entire project from one directory tree to another use: + +.. code-block:: shell-session + + $ 2to3 --output-dir=python3-version/mycode -W -n python2-version/mycode + + +.. _2to3-fixers: + +Fixers +------ + +Each step of transforming code is encapsulated in a fixer. The command ``2to3 +-l`` lists them. As :ref:`documented above <2to3-using>`, each can be turned on +and off individually. They are described here in more detail. + + +.. 2to3fixer:: apply + + Removes usage of :func:`apply`. For example ``apply(function, *args, + **kwargs)`` is converted to ``function(*args, **kwargs)``. + +.. 2to3fixer:: asserts + + Replaces deprecated :mod:`unittest` method names with the correct ones. + + ================================ ========================================== + From To + ================================ ========================================== + ``failUnlessEqual(a, b)`` :meth:`assertEqual(a, b) + ` + ``assertEquals(a, b)`` :meth:`assertEqual(a, b) + ` + ``failIfEqual(a, b)`` :meth:`assertNotEqual(a, b) + ` + ``assertNotEquals(a, b)`` :meth:`assertNotEqual(a, b) + ` + ``failUnless(a)`` :meth:`assertTrue(a) + ` + ``assert_(a)`` :meth:`assertTrue(a) + ` + ``failIf(a)`` :meth:`assertFalse(a) + ` + ``failUnlessRaises(exc, cal)`` :meth:`assertRaises(exc, cal) + ` + ``failUnlessAlmostEqual(a, b)`` :meth:`assertAlmostEqual(a, b) + ` + ``assertAlmostEquals(a, b)`` :meth:`assertAlmostEqual(a, b) + ` + ``failIfAlmostEqual(a, b)`` :meth:`assertNotAlmostEqual(a, b) + ` + ``assertNotAlmostEquals(a, b)`` :meth:`assertNotAlmostEqual(a, b) + ` + ================================ ========================================== + +.. 2to3fixer:: basestring + + Converts :class:`basestring` to :class:`str`. + +.. 2to3fixer:: buffer + + Converts :class:`buffer` to :class:`memoryview`. This fixer is optional + because the :class:`memoryview` API is similar but not exactly the same as + that of :class:`buffer`. + +.. 2to3fixer:: dict + + Fixes dictionary iteration methods. :meth:`dict.iteritems` is converted to + :meth:`dict.items`, :meth:`dict.iterkeys` to :meth:`dict.keys`, and + :meth:`dict.itervalues` to :meth:`dict.values`. Similarly, + :meth:`dict.viewitems`, :meth:`dict.viewkeys` and :meth:`dict.viewvalues` are + converted respectively to :meth:`dict.items`, :meth:`dict.keys` and + :meth:`dict.values`. It also wraps existing usages of :meth:`dict.items`, + :meth:`dict.keys`, and :meth:`dict.values` in a call to :class:`list`. + +.. 2to3fixer:: except + + Converts ``except X, T`` to ``except X as T``. + +.. 2to3fixer:: exec + + Converts the ``exec`` statement to the :func:`exec` function. + +.. 2to3fixer:: execfile + + Removes usage of :func:`execfile`. The argument to :func:`execfile` is + wrapped in calls to :func:`open`, :func:`compile`, and :func:`exec`. + +.. 2to3fixer:: exitfunc + + Changes assignment of :attr:`sys.exitfunc` to use of the :mod:`atexit` + module. + +.. 2to3fixer:: filter + + Wraps :func:`filter` usage in a :class:`list` call. + +.. 2to3fixer:: funcattrs + + Fixes function attributes that have been renamed. For example, + ``my_function.func_closure`` is converted to ``my_function.__closure__``. + +.. 2to3fixer:: future + + Removes ``from __future__ import new_feature`` statements. + +.. 2to3fixer:: getcwdu + + Renames :func:`os.getcwdu` to :func:`os.getcwd`. + +.. 2to3fixer:: has_key + + Changes ``dict.has_key(key)`` to ``key in dict``. + +.. 2to3fixer:: idioms + + This optional fixer performs several transformations that make Python code + more idiomatic. Type comparisons like ``type(x) is SomeClass`` and + ``type(x) == SomeClass`` are converted to ``isinstance(x, SomeClass)``. + ``while 1`` becomes ``while True``. This fixer also tries to make use of + :func:`sorted` in appropriate places. For example, this block :: + + L = list(some_iterable) + L.sort() + + is changed to :: + + L = sorted(some_iterable) + +.. 2to3fixer:: import + + Detects sibling imports and converts them to relative imports. + +.. 2to3fixer:: imports + + Handles module renames in the standard library. + +.. 2to3fixer:: imports2 + + Handles other modules renames in the standard library. It is separate from + the :2to3fixer:`imports` fixer only because of technical limitations. + +.. 2to3fixer:: input + + Converts ``input(prompt)`` to ``eval(input(prompt))``. + +.. 2to3fixer:: intern + + Converts :func:`intern` to :func:`sys.intern`. + +.. 2to3fixer:: isinstance + + Fixes duplicate types in the second argument of :func:`isinstance`. For + example, ``isinstance(x, (int, int))`` is converted to ``isinstance(x, + int)`` and ``isinstance(x, (int, float, int))`` is converted to + ``isinstance(x, (int, float))``. + +.. 2to3fixer:: itertools_imports + + Removes imports of :func:`itertools.ifilter`, :func:`itertools.izip`, and + :func:`itertools.imap`. Imports of :func:`itertools.ifilterfalse` are also + changed to :func:`itertools.filterfalse`. + +.. 2to3fixer:: itertools + + Changes usage of :func:`itertools.ifilter`, :func:`itertools.izip`, and + :func:`itertools.imap` to their built-in equivalents. + :func:`itertools.ifilterfalse` is changed to :func:`itertools.filterfalse`. + +.. 2to3fixer:: long + + Renames :class:`long` to :class:`int`. + +.. 2to3fixer:: map + + Wraps :func:`map` in a :class:`list` call. It also changes ``map(None, x)`` + to ``list(x)``. Using ``from future_builtins import map`` disables this + fixer. + +.. 2to3fixer:: metaclass + + Converts the old metaclass syntax (``__metaclass__ = Meta`` in the class + body) to the new (``class X(metaclass=Meta)``). + +.. 2to3fixer:: methodattrs + + Fixes old method attribute names. For example, ``meth.im_func`` is converted + to ``meth.__func__``. + +.. 2to3fixer:: ne + + Converts the old not-equal syntax, ``<>``, to ``!=``. + +.. 2to3fixer:: next + + Converts the use of iterator's :meth:`~iterator.next` methods to the + :func:`next` function. It also renames :meth:`next` methods to + :meth:`~iterator.__next__`. + +.. 2to3fixer:: nonzero + + Renames :meth:`__nonzero__` to :meth:`~object.__bool__`. + +.. 2to3fixer:: numliterals + + Converts octal literals into the new syntax. + +.. 2to3fixer:: operator + + Converts calls to various functions in the :mod:`operator` module to other, + but equivalent, function calls. When needed, the appropriate ``import`` + statements are added, e.g. ``import collections.abc``. The following mapping + are made: + + ================================== ============================================= + From To + ================================== ============================================= + ``operator.isCallable(obj)`` ``callable(obj)`` + ``operator.sequenceIncludes(obj)`` ``operator.contains(obj)`` + ``operator.isSequenceType(obj)`` ``isinstance(obj, collections.abc.Sequence)`` + ``operator.isMappingType(obj)`` ``isinstance(obj, collections.abc.Mapping)`` + ``operator.isNumberType(obj)`` ``isinstance(obj, numbers.Number)`` + ``operator.repeat(obj, n)`` ``operator.mul(obj, n)`` + ``operator.irepeat(obj, n)`` ``operator.imul(obj, n)`` + ================================== ============================================= + +.. 2to3fixer:: paren + + Add extra parenthesis where they are required in list comprehensions. For + example, ``[x for x in 1, 2]`` becomes ``[x for x in (1, 2)]``. + +.. 2to3fixer:: print + + Converts the ``print`` statement to the :func:`print` function. + +.. 2to3fixer:: raise + + Converts ``raise E, V`` to ``raise E(V)``, and ``raise E, V, T`` to ``raise + E(V).with_traceback(T)``. If ``E`` is a tuple, the translation will be + incorrect because substituting tuples for exceptions has been removed in 3.0. + +.. 2to3fixer:: raw_input + + Converts :func:`raw_input` to :func:`input`. + +.. 2to3fixer:: reduce + + Handles the move of :func:`reduce` to :func:`functools.reduce`. + +.. 2to3fixer:: reload + + Converts :func:`reload` to :func:`importlib.reload`. + +.. 2to3fixer:: renames + + Changes :data:`sys.maxint` to :data:`sys.maxsize`. + +.. 2to3fixer:: repr + + Replaces backtick repr with the :func:`repr` function. + +.. 2to3fixer:: set_literal + + Replaces use of the :class:`set` constructor with set literals. This fixer + is optional. + +.. 2to3fixer:: standarderror + + Renames :exc:`StandardError` to :exc:`Exception`. + +.. 2to3fixer:: sys_exc + + Changes the deprecated :data:`sys.exc_value`, :data:`sys.exc_type`, + :data:`sys.exc_traceback` to use :func:`sys.exc_info`. + +.. 2to3fixer:: throw + + Fixes the API change in generator's :meth:`throw` method. + +.. 2to3fixer:: tuple_params + + Removes implicit tuple parameter unpacking. This fixer inserts temporary + variables. + +.. 2to3fixer:: types + + Fixes code broken from the removal of some members in the :mod:`types` + module. + +.. 2to3fixer:: unicode + + Renames :class:`unicode` to :class:`str`. + +.. 2to3fixer:: urllib + + Handles the rename of :mod:`urllib` and :mod:`urllib2` to the :mod:`urllib` + package. + +.. 2to3fixer:: ws_comma + + Removes excess whitespace from comma separated items. This fixer is + optional. + +.. 2to3fixer:: xrange + + Renames :func:`xrange` to :func:`range` and wraps existing :func:`range` + calls with :class:`list`. + +.. 2to3fixer:: xreadlines + + Changes ``for x in file.xreadlines()`` to ``for x in file``. + +.. 2to3fixer:: zip + + Wraps :func:`zip` usage in a :class:`list` call. This is disabled when + ``from future_builtins import zip`` appears. + + +:mod:`lib2to3` - 2to3's library +------------------------------- + +.. module:: lib2to3 + :synopsis: The 2to3 library + +.. moduleauthor:: Guido van Rossum +.. moduleauthor:: Collin Winter +.. moduleauthor:: Benjamin Peterson + +**Source code:** :source:`Lib/lib2to3/` + +-------------- + +.. deprecated:: 3.10 + Python 3.9 will switch to a PEG parser (see :pep:`617`), and Python 3.10 may + include new language syntax that is not parsable by lib2to3's LL(1) parser. + The ``lib2to3`` module may be removed from the standard library in a future + Python version. Consider third-party alternatives such as `LibCST`_ or + `parso`_. + +.. note:: + + The :mod:`lib2to3` API should be considered unstable and may change + drastically in the future. + +.. _LibCST: https://libcst.readthedocs.io/ +.. _parso: https://parso.readthedocs.io/ diff --git a/cpython_2/environment/repo/Doc/library/__future__.rst b/cpython_2/environment/repo/Doc/library/__future__.rst new file mode 100644 index 0000000000000000000000000000000000000000..e3d749e60178478fe8645fa9b6ad5465b449ef8f --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/__future__.rst @@ -0,0 +1,103 @@ +:mod:`__future__` --- Future statement definitions +================================================== + +.. module:: __future__ + :synopsis: Future statement definitions + +**Source code:** :source:`Lib/__future__.py` + +-------------- + +:mod:`__future__` is a real module, and serves three purposes: + +* To avoid confusing existing tools that analyze import statements and expect to + find the modules they're importing. + +* To ensure that :ref:`future statements ` run under releases prior to + 2.1 at least yield runtime exceptions (the import of :mod:`__future__` will + fail, because there was no module of that name prior to 2.1). + +* To document when incompatible changes were introduced, and when they will be + --- or were --- made mandatory. This is a form of executable documentation, and + can be inspected programmatically via importing :mod:`__future__` and examining + its contents. + +Each statement in :file:`__future__.py` is of the form:: + + FeatureName = _Feature(OptionalRelease, MandatoryRelease, + CompilerFlag) + + +where, normally, *OptionalRelease* is less than *MandatoryRelease*, and both are +5-tuples of the same form as :data:`sys.version_info`:: + + (PY_MAJOR_VERSION, # the 2 in 2.1.0a3; an int + PY_MINOR_VERSION, # the 1; an int + PY_MICRO_VERSION, # the 0; an int + PY_RELEASE_LEVEL, # "alpha", "beta", "candidate" or "final"; string + PY_RELEASE_SERIAL # the 3; an int + ) + +*OptionalRelease* records the first release in which the feature was accepted. + +In the case of a *MandatoryRelease* that has not yet occurred, +*MandatoryRelease* predicts the release in which the feature will become part of +the language. + +Else *MandatoryRelease* records when the feature became part of the language; in +releases at or after that, modules no longer need a future statement to use the +feature in question, but may continue to use such imports. + +*MandatoryRelease* may also be ``None``, meaning that a planned feature got +dropped. + +Instances of class :class:`_Feature` have two corresponding methods, +:meth:`getOptionalRelease` and :meth:`getMandatoryRelease`. + +*CompilerFlag* is the (bitfield) flag that should be passed in the fourth +argument to the built-in function :func:`compile` to enable the feature in +dynamically compiled code. This flag is stored in the :attr:`compiler_flag` +attribute on :class:`_Feature` instances. + +No feature description will ever be deleted from :mod:`__future__`. Since its +introduction in Python 2.1 the following features have found their way into the +language using this mechanism: + ++------------------+-------------+--------------+---------------------------------------------+ +| feature | optional in | mandatory in | effect | ++==================+=============+==============+=============================================+ +| nested_scopes | 2.1.0b1 | 2.2 | :pep:`227`: | +| | | | *Statically Nested Scopes* | ++------------------+-------------+--------------+---------------------------------------------+ +| generators | 2.2.0a1 | 2.3 | :pep:`255`: | +| | | | *Simple Generators* | ++------------------+-------------+--------------+---------------------------------------------+ +| division | 2.2.0a2 | 3.0 | :pep:`238`: | +| | | | *Changing the Division Operator* | ++------------------+-------------+--------------+---------------------------------------------+ +| absolute_import | 2.5.0a1 | 3.0 | :pep:`328`: | +| | | | *Imports: Multi-Line and Absolute/Relative* | ++------------------+-------------+--------------+---------------------------------------------+ +| with_statement | 2.5.0a1 | 2.6 | :pep:`343`: | +| | | | *The "with" Statement* | ++------------------+-------------+--------------+---------------------------------------------+ +| print_function | 2.6.0a2 | 3.0 | :pep:`3105`: | +| | | | *Make print a function* | ++------------------+-------------+--------------+---------------------------------------------+ +| unicode_literals | 2.6.0a2 | 3.0 | :pep:`3112`: | +| | | | *Bytes literals in Python 3000* | ++------------------+-------------+--------------+---------------------------------------------+ +| generator_stop | 3.5.0b1 | 3.7 | :pep:`479`: | +| | | | *StopIteration handling inside generators* | ++------------------+-------------+--------------+---------------------------------------------+ +| annotations | 3.7.0b1 | 4.0 | :pep:`563`: | +| | | | *Postponed evaluation of annotations* | ++------------------+-------------+--------------+---------------------------------------------+ + +.. XXX Adding a new entry? Remember to update simple_stmts.rst, too. + + +.. seealso:: + + :ref:`future` + How the compiler treats future imports. diff --git a/cpython_2/environment/repo/Doc/library/__main__.rst b/cpython_2/environment/repo/Doc/library/__main__.rst new file mode 100644 index 0000000000000000000000000000000000000000..a64faf1bbe3c849f0ba5dc2e4b210558bba6d430 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/__main__.rst @@ -0,0 +1,25 @@ + +:mod:`__main__` --- Top-level script environment +================================================ + +.. module:: __main__ + :synopsis: The environment where the top-level script is run. + +-------------- + +``'__main__'`` is the name of the scope in which top-level code executes. +A module's __name__ is set equal to ``'__main__'`` when read from +standard input, a script, or from an interactive prompt. + +A module can discover whether or not it is running in the main scope by +checking its own ``__name__``, which allows a common idiom for conditionally +executing code in a module when it is run as a script or with ``python +-m`` but not when it is imported:: + + if __name__ == "__main__": + # execute only if run as a script + main() + +For a package, the same effect can be achieved by including a +``__main__.py`` module, the contents of which will be executed when the +module is run with ``-m``. diff --git a/cpython_2/environment/repo/Doc/library/_thread.rst b/cpython_2/environment/repo/Doc/library/_thread.rst new file mode 100644 index 0000000000000000000000000000000000000000..bd653ab32bb9c43425ba0107f495110ae07286de --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/_thread.rst @@ -0,0 +1,215 @@ +:mod:`_thread` --- Low-level threading API +========================================== + +.. module:: _thread + :synopsis: Low-level threading API. + +.. index:: + single: light-weight processes + single: processes, light-weight + single: binary semaphores + single: semaphores, binary + +-------------- + +This module provides low-level primitives for working with multiple threads +(also called :dfn:`light-weight processes` or :dfn:`tasks`) --- multiple threads of +control sharing their global data space. For synchronization, simple locks +(also called :dfn:`mutexes` or :dfn:`binary semaphores`) are provided. +The :mod:`threading` module provides an easier to use and higher-level +threading API built on top of this module. + +.. index:: + single: pthreads + pair: threads; POSIX + +.. versionchanged:: 3.7 + This module used to be optional, it is now always available. + +This module defines the following constants and functions: + +.. exception:: error + + Raised on thread-specific errors. + + .. versionchanged:: 3.3 + This is now a synonym of the built-in :exc:`RuntimeError`. + + +.. data:: LockType + + This is the type of lock objects. + + +.. function:: start_new_thread(function, args[, kwargs]) + + Start a new thread and return its identifier. The thread executes the + function *function* with the argument list *args* (which must be a tuple). + The optional *kwargs* argument specifies a dictionary of keyword arguments. + + When the function returns, the thread silently exits. + + When the function terminates with an unhandled exception, + :func:`sys.unraisablehook` is called to handle the exception. The *object* + attribute of the hook argument is *function*. By default, a stack trace is + printed and then the thread exits (but other threads continue to run). + + When the function raises a :exc:`SystemExit` exception, it is silently + ignored. + + .. versionchanged:: 3.8 + :func:`sys.unraisablehook` is now used to handle unhandled exceptions. + + +.. function:: interrupt_main() + + Simulate the effect of a :data:`signal.SIGINT` signal arriving in the main + thread. A thread can use this function to interrupt the main thread. + + If :data:`signal.SIGINT` isn't handled by Python (it was set to + :data:`signal.SIG_DFL` or :data:`signal.SIG_IGN`), this function does + nothing. + + +.. function:: exit() + + Raise the :exc:`SystemExit` exception. When not caught, this will cause the + thread to exit silently. + +.. + function:: exit_prog(status) + + Exit all threads and report the value of the integer argument + *status* as the exit status of the entire program. + **Caveat:** code in pending :keyword:`finally` clauses, in this thread + or in other threads, is not executed. + + +.. function:: allocate_lock() + + Return a new lock object. Methods of locks are described below. The lock is + initially unlocked. + + +.. function:: get_ident() + + Return the 'thread identifier' of the current thread. This is a nonzero + integer. Its value has no direct meaning; it is intended as a magic cookie to + be used e.g. to index a dictionary of thread-specific data. Thread identifiers + may be recycled when a thread exits and another thread is created. + + +.. function:: get_native_id() + + Return the native integral Thread ID of the current thread assigned by the kernel. + This is a non-negative integer. + Its value may be used to uniquely identify this particular thread system-wide + (until the thread terminates, after which the value may be recycled by the OS). + + .. availability:: Windows, FreeBSD, Linux, macOS, OpenBSD, NetBSD, AIX. + + .. versionadded:: 3.8 + + +.. function:: stack_size([size]) + + Return the thread stack size used when creating new threads. The optional + *size* argument specifies the stack size to be used for subsequently created + threads, and must be 0 (use platform or configured default) or a positive + integer value of at least 32,768 (32 KiB). If *size* is not specified, + 0 is used. If changing the thread stack size is + unsupported, a :exc:`RuntimeError` is raised. If the specified stack size is + invalid, a :exc:`ValueError` is raised and the stack size is unmodified. 32 KiB + is currently the minimum supported stack size value to guarantee sufficient + stack space for the interpreter itself. Note that some platforms may have + particular restrictions on values for the stack size, such as requiring a + minimum stack size > 32 KiB or requiring allocation in multiples of the system + memory page size - platform documentation should be referred to for more + information (4 KiB pages are common; using multiples of 4096 for the stack size is + the suggested approach in the absence of more specific information). + + .. availability:: Windows, systems with POSIX threads. + + +.. data:: TIMEOUT_MAX + + The maximum value allowed for the *timeout* parameter of + :meth:`Lock.acquire`. Specifying a timeout greater than this value will + raise an :exc:`OverflowError`. + + .. versionadded:: 3.2 + + +Lock objects have the following methods: + + +.. method:: lock.acquire(waitflag=1, timeout=-1) + + Without any optional argument, this method acquires the lock unconditionally, if + necessary waiting until it is released by another thread (only one thread at a + time can acquire a lock --- that's their reason for existence). + + If the integer *waitflag* argument is present, the action depends on its + value: if it is zero, the lock is only acquired if it can be acquired + immediately without waiting, while if it is nonzero, the lock is acquired + unconditionally as above. + + If the floating-point *timeout* argument is present and positive, it + specifies the maximum wait time in seconds before returning. A negative + *timeout* argument specifies an unbounded wait. You cannot specify + a *timeout* if *waitflag* is zero. + + The return value is ``True`` if the lock is acquired successfully, + ``False`` if not. + + .. versionchanged:: 3.2 + The *timeout* parameter is new. + + .. versionchanged:: 3.2 + Lock acquires can now be interrupted by signals on POSIX. + + +.. method:: lock.release() + + Releases the lock. The lock must have been acquired earlier, but not + necessarily by the same thread. + + +.. method:: lock.locked() + + Return the status of the lock: ``True`` if it has been acquired by some thread, + ``False`` if not. + +In addition to these methods, lock objects can also be used via the +:keyword:`with` statement, e.g.:: + + import _thread + + a_lock = _thread.allocate_lock() + + with a_lock: + print("a_lock is locked while this executes") + +**Caveats:** + + .. index:: module: signal + +* Threads interact strangely with interrupts: the :exc:`KeyboardInterrupt` + exception will be received by an arbitrary thread. (When the :mod:`signal` + module is available, interrupts always go to the main thread.) + +* Calling :func:`sys.exit` or raising the :exc:`SystemExit` exception is + equivalent to calling :func:`_thread.exit`. + +* It is not possible to interrupt the :meth:`acquire` method on a lock --- the + :exc:`KeyboardInterrupt` exception will happen after the lock has been acquired. + +* When the main thread exits, it is system defined whether the other threads + survive. On most systems, they are killed without executing + :keyword:`try` ... :keyword:`finally` clauses or executing object + destructors. + +* When the main thread exits, it does not do any of its usual cleanup (except + that :keyword:`try` ... :keyword:`finally` clauses are honored), and the + standard I/O files are not flushed. + diff --git a/cpython_2/environment/repo/Doc/library/abc.rst b/cpython_2/environment/repo/Doc/library/abc.rst new file mode 100644 index 0000000000000000000000000000000000000000..424ae547d829a4cb1dcccfc88418410ba3495e5c --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/abc.rst @@ -0,0 +1,342 @@ +:mod:`abc` --- Abstract Base Classes +==================================== + +.. module:: abc + :synopsis: Abstract base classes according to :pep:`3119`. + +.. moduleauthor:: Guido van Rossum +.. sectionauthor:: Georg Brandl +.. much of the content adapted from docstrings + +**Source code:** :source:`Lib/abc.py` + +-------------- + +This module provides the infrastructure for defining :term:`abstract base +classes ` (ABCs) in Python, as outlined in :pep:`3119`; +see the PEP for why this was added to Python. (See also :pep:`3141` and the +:mod:`numbers` module regarding a type hierarchy for numbers based on ABCs.) + +The :mod:`collections` module has some concrete classes that derive from +ABCs; these can, of course, be further derived. In addition, the +:mod:`collections.abc` submodule has some ABCs that can be used to test whether +a class or instance provides a particular interface, for example, if it is +hashable or if it is a mapping. + + +This module provides the metaclass :class:`ABCMeta` for defining ABCs and +a helper class :class:`ABC` to alternatively define ABCs through inheritance: + +.. class:: ABC + + A helper class that has :class:`ABCMeta` as its metaclass. With this class, + an abstract base class can be created by simply deriving from :class:`ABC` + avoiding sometimes confusing metaclass usage, for example:: + + from abc import ABC + + class MyABC(ABC): + pass + + Note that the type of :class:`ABC` is still :class:`ABCMeta`, therefore + inheriting from :class:`ABC` requires the usual precautions regarding + metaclass usage, as multiple inheritance may lead to metaclass conflicts. + One may also define an abstract base class by passing the metaclass + keyword and using :class:`ABCMeta` directly, for example:: + + from abc import ABCMeta + + class MyABC(metaclass=ABCMeta): + pass + + .. versionadded:: 3.4 + + +.. class:: ABCMeta + + Metaclass for defining Abstract Base Classes (ABCs). + + Use this metaclass to create an ABC. An ABC can be subclassed directly, and + then acts as a mix-in class. You can also register unrelated concrete + classes (even built-in classes) and unrelated ABCs as "virtual subclasses" -- + these and their descendants will be considered subclasses of the registering + ABC by the built-in :func:`issubclass` function, but the registering ABC + won't show up in their MRO (Method Resolution Order) nor will method + implementations defined by the registering ABC be callable (not even via + :func:`super`). [#]_ + + Classes created with a metaclass of :class:`ABCMeta` have the following method: + + .. method:: register(subclass) + + Register *subclass* as a "virtual subclass" of this ABC. For + example:: + + from abc import ABC + + class MyABC(ABC): + pass + + MyABC.register(tuple) + + assert issubclass(tuple, MyABC) + assert isinstance((), MyABC) + + .. versionchanged:: 3.3 + Returns the registered subclass, to allow usage as a class decorator. + + .. versionchanged:: 3.4 + To detect calls to :meth:`register`, you can use the + :func:`get_cache_token` function. + + You can also override this method in an abstract base class: + + .. method:: __subclasshook__(subclass) + + (Must be defined as a class method.) + + Check whether *subclass* is considered a subclass of this ABC. This means + that you can customize the behavior of ``issubclass`` further without the + need to call :meth:`register` on every class you want to consider a + subclass of the ABC. (This class method is called from the + :meth:`__subclasscheck__` method of the ABC.) + + This method should return ``True``, ``False`` or ``NotImplemented``. If + it returns ``True``, the *subclass* is considered a subclass of this ABC. + If it returns ``False``, the *subclass* is not considered a subclass of + this ABC, even if it would normally be one. If it returns + ``NotImplemented``, the subclass check is continued with the usual + mechanism. + + .. XXX explain the "usual mechanism" + + + For a demonstration of these concepts, look at this example ABC definition:: + + class Foo: + def __getitem__(self, index): + ... + def __len__(self): + ... + def get_iterator(self): + return iter(self) + + class MyIterable(ABC): + + @abstractmethod + def __iter__(self): + while False: + yield None + + def get_iterator(self): + return self.__iter__() + + @classmethod + def __subclasshook__(cls, C): + if cls is MyIterable: + if any("__iter__" in B.__dict__ for B in C.__mro__): + return True + return NotImplemented + + MyIterable.register(Foo) + + The ABC ``MyIterable`` defines the standard iterable method, + :meth:`~iterator.__iter__`, as an abstract method. The implementation given + here can still be called from subclasses. The :meth:`get_iterator` method + is also part of the ``MyIterable`` abstract base class, but it does not have + to be overridden in non-abstract derived classes. + + The :meth:`__subclasshook__` class method defined here says that any class + that has an :meth:`~iterator.__iter__` method in its + :attr:`~object.__dict__` (or in that of one of its base classes, accessed + via the :attr:`~class.__mro__` list) is considered a ``MyIterable`` too. + + Finally, the last line makes ``Foo`` a virtual subclass of ``MyIterable``, + even though it does not define an :meth:`~iterator.__iter__` method (it uses + the old-style iterable protocol, defined in terms of :meth:`__len__` and + :meth:`__getitem__`). Note that this will not make ``get_iterator`` + available as a method of ``Foo``, so it is provided separately. + + + + +The :mod:`abc` module also provides the following decorator: + +.. decorator:: abstractmethod + + A decorator indicating abstract methods. + + Using this decorator requires that the class's metaclass is :class:`ABCMeta` + or is derived from it. A class that has a metaclass derived from + :class:`ABCMeta` cannot be instantiated unless all of its abstract methods + and properties are overridden. The abstract methods can be called using any + of the normal 'super' call mechanisms. :func:`abstractmethod` may be used + to declare abstract methods for properties and descriptors. + + Dynamically adding abstract methods to a class, or attempting to modify the + abstraction status of a method or class once it is created, are not + supported. The :func:`abstractmethod` only affects subclasses derived using + regular inheritance; "virtual subclasses" registered with the ABC's + :meth:`register` method are not affected. + + When :func:`abstractmethod` is applied in combination with other method + descriptors, it should be applied as the innermost decorator, as shown in + the following usage examples:: + + class C(ABC): + @abstractmethod + def my_abstract_method(self, ...): + ... + @classmethod + @abstractmethod + def my_abstract_classmethod(cls, ...): + ... + @staticmethod + @abstractmethod + def my_abstract_staticmethod(...): + ... + + @property + @abstractmethod + def my_abstract_property(self): + ... + @my_abstract_property.setter + @abstractmethod + def my_abstract_property(self, val): + ... + + @abstractmethod + def _get_x(self): + ... + @abstractmethod + def _set_x(self, val): + ... + x = property(_get_x, _set_x) + + In order to correctly interoperate with the abstract base class machinery, + the descriptor must identify itself as abstract using + :attr:`__isabstractmethod__`. In general, this attribute should be ``True`` + if any of the methods used to compose the descriptor are abstract. For + example, Python's built-in :class:`property` does the equivalent of:: + + class Descriptor: + ... + @property + def __isabstractmethod__(self): + return any(getattr(f, '__isabstractmethod__', False) for + f in (self._fget, self._fset, self._fdel)) + + .. note:: + + Unlike Java abstract methods, these abstract + methods may have an implementation. This implementation can be + called via the :func:`super` mechanism from the class that + overrides it. This could be useful as an end-point for a + super-call in a framework that uses cooperative + multiple-inheritance. + + +The :mod:`abc` module also supports the following legacy decorators: + +.. decorator:: abstractclassmethod + + .. versionadded:: 3.2 + .. deprecated:: 3.3 + It is now possible to use :class:`classmethod` with + :func:`abstractmethod`, making this decorator redundant. + + A subclass of the built-in :func:`classmethod`, indicating an abstract + classmethod. Otherwise it is similar to :func:`abstractmethod`. + + This special case is deprecated, as the :func:`classmethod` decorator + is now correctly identified as abstract when applied to an abstract + method:: + + class C(ABC): + @classmethod + @abstractmethod + def my_abstract_classmethod(cls, ...): + ... + + +.. decorator:: abstractstaticmethod + + .. versionadded:: 3.2 + .. deprecated:: 3.3 + It is now possible to use :class:`staticmethod` with + :func:`abstractmethod`, making this decorator redundant. + + A subclass of the built-in :func:`staticmethod`, indicating an abstract + staticmethod. Otherwise it is similar to :func:`abstractmethod`. + + This special case is deprecated, as the :func:`staticmethod` decorator + is now correctly identified as abstract when applied to an abstract + method:: + + class C(ABC): + @staticmethod + @abstractmethod + def my_abstract_staticmethod(...): + ... + + +.. decorator:: abstractproperty + + .. deprecated:: 3.3 + It is now possible to use :class:`property`, :meth:`property.getter`, + :meth:`property.setter` and :meth:`property.deleter` with + :func:`abstractmethod`, making this decorator redundant. + + A subclass of the built-in :func:`property`, indicating an abstract + property. + + This special case is deprecated, as the :func:`property` decorator + is now correctly identified as abstract when applied to an abstract + method:: + + class C(ABC): + @property + @abstractmethod + def my_abstract_property(self): + ... + + The above example defines a read-only property; you can also define a + read-write abstract property by appropriately marking one or more of the + underlying methods as abstract:: + + class C(ABC): + @property + def x(self): + ... + + @x.setter + @abstractmethod + def x(self, val): + ... + + If only some components are abstract, only those components need to be + updated to create a concrete property in a subclass:: + + class D(C): + @C.x.setter + def x(self, val): + ... + + +The :mod:`abc` module also provides the following functions: + +.. function:: get_cache_token() + + Returns the current abstract base class cache token. + + The token is an opaque object (that supports equality testing) identifying + the current version of the abstract base class cache for virtual subclasses. + The token changes with every call to :meth:`ABCMeta.register` on any ABC. + + .. versionadded:: 3.4 + + +.. rubric:: Footnotes + +.. [#] C++ programmers should note that Python's virtual base class + concept is not the same as C++'s. diff --git a/cpython_2/environment/repo/Doc/library/aifc.rst b/cpython_2/environment/repo/Doc/library/aifc.rst new file mode 100644 index 0000000000000000000000000000000000000000..7328907730fb107ae853bf5195a4e6a60228000b --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/aifc.rst @@ -0,0 +1,239 @@ +:mod:`aifc` --- Read and write AIFF and AIFC files +================================================== + +.. module:: aifc + :synopsis: Read and write audio files in AIFF or AIFC format. + +**Source code:** :source:`Lib/aifc.py` + +.. index:: + single: Audio Interchange File Format + single: AIFF + single: AIFF-C + +-------------- + +This module provides support for reading and writing AIFF and AIFF-C files. +AIFF is Audio Interchange File Format, a format for storing digital audio +samples in a file. AIFF-C is a newer version of the format that includes the +ability to compress the audio data. + +Audio files have a number of parameters that describe the audio data. The +sampling rate or frame rate is the number of times per second the sound is +sampled. The number of channels indicate if the audio is mono, stereo, or +quadro. Each frame consists of one sample per channel. The sample size is the +size in bytes of each sample. Thus a frame consists of +``nchannels * samplesize`` bytes, and a second's worth of audio consists of +``nchannels * samplesize * framerate`` bytes. + +For example, CD quality audio has a sample size of two bytes (16 bits), uses two +channels (stereo) and has a frame rate of 44,100 frames/second. This gives a +frame size of 4 bytes (2\*2), and a second's worth occupies 2\*2\*44100 bytes +(176,400 bytes). + +Module :mod:`aifc` defines the following function: + + +.. function:: open(file, mode=None) + + Open an AIFF or AIFF-C file and return an object instance with methods that are + described below. The argument *file* is either a string naming a file or a + :term:`file object`. *mode* must be ``'r'`` or ``'rb'`` when the file must be + opened for reading, or ``'w'`` or ``'wb'`` when the file must be opened for writing. + If omitted, ``file.mode`` is used if it exists, otherwise ``'rb'`` is used. When + used for writing, the file object should be seekable, unless you know ahead of + time how many samples you are going to write in total and use + :meth:`writeframesraw` and :meth:`setnframes`. + The :func:`.open` function may be used in a :keyword:`with` statement. When + the :keyword:`!with` block completes, the :meth:`~aifc.close` method is called. + + .. versionchanged:: 3.4 + Support for the :keyword:`with` statement was added. + +Objects returned by :func:`.open` when a file is opened for reading have the +following methods: + + +.. method:: aifc.getnchannels() + + Return the number of audio channels (1 for mono, 2 for stereo). + + +.. method:: aifc.getsampwidth() + + Return the size in bytes of individual samples. + + +.. method:: aifc.getframerate() + + Return the sampling rate (number of audio frames per second). + + +.. method:: aifc.getnframes() + + Return the number of audio frames in the file. + + +.. method:: aifc.getcomptype() + + Return a bytes array of length 4 describing the type of compression + used in the audio file. For AIFF files, the returned value is + ``b'NONE'``. + + +.. method:: aifc.getcompname() + + Return a bytes array convertible to a human-readable description + of the type of compression used in the audio file. For AIFF files, + the returned value is ``b'not compressed'``. + + +.. method:: aifc.getparams() + + Returns a :func:`~collections.namedtuple` ``(nchannels, sampwidth, + framerate, nframes, comptype, compname)``, equivalent to output of the + :meth:`get\*` methods. + + +.. method:: aifc.getmarkers() + + Return a list of markers in the audio file. A marker consists of a tuple of + three elements. The first is the mark ID (an integer), the second is the mark + position in frames from the beginning of the data (an integer), the third is the + name of the mark (a string). + + +.. method:: aifc.getmark(id) + + Return the tuple as described in :meth:`getmarkers` for the mark with the given + *id*. + + +.. method:: aifc.readframes(nframes) + + Read and return the next *nframes* frames from the audio file. The returned + data is a string containing for each frame the uncompressed samples of all + channels. + + +.. method:: aifc.rewind() + + Rewind the read pointer. The next :meth:`readframes` will start from the + beginning. + + +.. method:: aifc.setpos(pos) + + Seek to the specified frame number. + + +.. method:: aifc.tell() + + Return the current frame number. + + +.. method:: aifc.close() + + Close the AIFF file. After calling this method, the object can no longer be + used. + +Objects returned by :func:`.open` when a file is opened for writing have all the +above methods, except for :meth:`readframes` and :meth:`setpos`. In addition +the following methods exist. The :meth:`get\*` methods can only be called after +the corresponding :meth:`set\*` methods have been called. Before the first +:meth:`writeframes` or :meth:`writeframesraw`, all parameters except for the +number of frames must be filled in. + + +.. method:: aifc.aiff() + + Create an AIFF file. The default is that an AIFF-C file is created, unless the + name of the file ends in ``'.aiff'`` in which case the default is an AIFF file. + + +.. method:: aifc.aifc() + + Create an AIFF-C file. The default is that an AIFF-C file is created, unless + the name of the file ends in ``'.aiff'`` in which case the default is an AIFF + file. + + +.. method:: aifc.setnchannels(nchannels) + + Specify the number of channels in the audio file. + + +.. method:: aifc.setsampwidth(width) + + Specify the size in bytes of audio samples. + + +.. method:: aifc.setframerate(rate) + + Specify the sampling frequency in frames per second. + + +.. method:: aifc.setnframes(nframes) + + Specify the number of frames that are to be written to the audio file. If this + parameter is not set, or not set correctly, the file needs to support seeking. + + +.. method:: aifc.setcomptype(type, name) + + .. index:: + single: u-LAW + single: A-LAW + single: G.722 + + Specify the compression type. If not specified, the audio data will + not be compressed. In AIFF files, compression is not possible. + The name parameter should be a human-readable description of the + compression type as a bytes array, the type parameter should be a + bytes array of length 4. Currently the following compression types + are supported: ``b'NONE'``, ``b'ULAW'``, ``b'ALAW'``, ``b'G722'``. + + +.. method:: aifc.setparams(nchannels, sampwidth, framerate, comptype, compname) + + Set all the above parameters at once. The argument is a tuple consisting of the + various parameters. This means that it is possible to use the result of a + :meth:`getparams` call as argument to :meth:`setparams`. + + +.. method:: aifc.setmark(id, pos, name) + + Add a mark with the given id (larger than 0), and the given name at the given + position. This method can be called at any time before :meth:`close`. + + +.. method:: aifc.tell() + + Return the current write position in the output file. Useful in combination + with :meth:`setmark`. + + +.. method:: aifc.writeframes(data) + + Write data to the output file. This method can only be called after the audio + file parameters have been set. + + .. versionchanged:: 3.4 + Any :term:`bytes-like object` is now accepted. + + +.. method:: aifc.writeframesraw(data) + + Like :meth:`writeframes`, except that the header of the audio file is not + updated. + + .. versionchanged:: 3.4 + Any :term:`bytes-like object` is now accepted. + + +.. method:: aifc.close() + + Close the AIFF file. The header of the file is updated to reflect the actual + size of the audio data. After calling this method, the object can no longer be + used. + diff --git a/cpython_2/environment/repo/Doc/library/allos.rst b/cpython_2/environment/repo/Doc/library/allos.rst new file mode 100644 index 0000000000000000000000000000000000000000..f7105d8af8e28b3d83588c09159fdb901a825f29 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/allos.rst @@ -0,0 +1,29 @@ +.. _allos: + +********************************* +Generic Operating System Services +********************************* + +The modules described in this chapter provide interfaces to operating system +features that are available on (almost) all operating systems, such as files and +a clock. The interfaces are generally modeled after the Unix or C interfaces, +but they are available on most other systems as well. Here's an overview: + + +.. toctree:: + + os.rst + io.rst + time.rst + argparse.rst + getopt.rst + logging.rst + logging.config.rst + logging.handlers.rst + getpass.rst + curses.rst + curses.ascii.rst + curses.panel.rst + platform.rst + errno.rst + ctypes.rst diff --git a/cpython_2/environment/repo/Doc/library/archiving.rst b/cpython_2/environment/repo/Doc/library/archiving.rst new file mode 100644 index 0000000000000000000000000000000000000000..c9284949af49726c0c66d2c64b5b16431c5e67cb --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/archiving.rst @@ -0,0 +1,20 @@ +.. _archiving: + +****************************** +Data Compression and Archiving +****************************** + +The modules described in this chapter support data compression with the zlib, +gzip, bzip2 and lzma algorithms, and the creation of ZIP- and tar-format +archives. See also :ref:`archiving-operations` provided by the :mod:`shutil` +module. + + +.. toctree:: + + zlib.rst + gzip.rst + bz2.rst + lzma.rst + zipfile.rst + tarfile.rst diff --git a/cpython_2/environment/repo/Doc/library/argparse.rst b/cpython_2/environment/repo/Doc/library/argparse.rst new file mode 100644 index 0000000000000000000000000000000000000000..f8e39189686208fa896d8922b1a1e89576fba8d5 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/argparse.rst @@ -0,0 +1,2156 @@ +:mod:`argparse` --- Parser for command-line options, arguments and sub-commands +=============================================================================== + +.. module:: argparse + :synopsis: Command-line option and argument parsing library. + +.. moduleauthor:: Steven Bethard +.. sectionauthor:: Steven Bethard + +.. versionadded:: 3.2 + +**Source code:** :source:`Lib/argparse.py` + +-------------- + +.. sidebar:: Tutorial + + This page contains the API reference information. For a more gentle + introduction to Python command-line parsing, have a look at the + :ref:`argparse tutorial `. + +The :mod:`argparse` module makes it easy to write user-friendly command-line +interfaces. The program defines what arguments it requires, and :mod:`argparse` +will figure out how to parse those out of :data:`sys.argv`. The :mod:`argparse` +module also automatically generates help and usage messages and issues errors +when users give the program invalid arguments. + + +Example +------- + +The following code is a Python program that takes a list of integers and +produces either the sum or the max:: + + import argparse + + parser = argparse.ArgumentParser(description='Process some integers.') + parser.add_argument('integers', metavar='N', type=int, nargs='+', + help='an integer for the accumulator') + parser.add_argument('--sum', dest='accumulate', action='store_const', + const=sum, default=max, + help='sum the integers (default: find the max)') + + args = parser.parse_args() + print(args.accumulate(args.integers)) + +Assuming the Python code above is saved into a file called ``prog.py``, it can +be run at the command line and provides useful help messages: + +.. code-block:: shell-session + + $ python prog.py -h + usage: prog.py [-h] [--sum] N [N ...] + + Process some integers. + + positional arguments: + N an integer for the accumulator + + optional arguments: + -h, --help show this help message and exit + --sum sum the integers (default: find the max) + +When run with the appropriate arguments, it prints either the sum or the max of +the command-line integers: + +.. code-block:: shell-session + + $ python prog.py 1 2 3 4 + 4 + + $ python prog.py 1 2 3 4 --sum + 10 + +If invalid arguments are passed in, it will issue an error: + +.. code-block:: shell-session + + $ python prog.py a b c + usage: prog.py [-h] [--sum] N [N ...] + prog.py: error: argument N: invalid int value: 'a' + +The following sections walk you through this example. + + +Creating a parser +^^^^^^^^^^^^^^^^^ + +The first step in using the :mod:`argparse` is creating an +:class:`ArgumentParser` object:: + + >>> parser = argparse.ArgumentParser(description='Process some integers.') + +The :class:`ArgumentParser` object will hold all the information necessary to +parse the command line into Python data types. + + +Adding arguments +^^^^^^^^^^^^^^^^ + +Filling an :class:`ArgumentParser` with information about program arguments is +done by making calls to the :meth:`~ArgumentParser.add_argument` method. +Generally, these calls tell the :class:`ArgumentParser` how to take the strings +on the command line and turn them into objects. This information is stored and +used when :meth:`~ArgumentParser.parse_args` is called. For example:: + + >>> parser.add_argument('integers', metavar='N', type=int, nargs='+', + ... help='an integer for the accumulator') + >>> parser.add_argument('--sum', dest='accumulate', action='store_const', + ... const=sum, default=max, + ... help='sum the integers (default: find the max)') + +Later, calling :meth:`~ArgumentParser.parse_args` will return an object with +two attributes, ``integers`` and ``accumulate``. The ``integers`` attribute +will be a list of one or more ints, and the ``accumulate`` attribute will be +either the :func:`sum` function, if ``--sum`` was specified at the command line, +or the :func:`max` function if it was not. + + +Parsing arguments +^^^^^^^^^^^^^^^^^ + +:class:`ArgumentParser` parses arguments through the +:meth:`~ArgumentParser.parse_args` method. This will inspect the command line, +convert each argument to the appropriate type and then invoke the appropriate action. +In most cases, this means a simple :class:`Namespace` object will be built up from +attributes parsed out of the command line:: + + >>> parser.parse_args(['--sum', '7', '-1', '42']) + Namespace(accumulate=, integers=[7, -1, 42]) + +In a script, :meth:`~ArgumentParser.parse_args` will typically be called with no +arguments, and the :class:`ArgumentParser` will automatically determine the +command-line arguments from :data:`sys.argv`. + + +ArgumentParser objects +---------------------- + +.. class:: ArgumentParser(prog=None, usage=None, description=None, \ + epilog=None, parents=[], \ + formatter_class=argparse.HelpFormatter, \ + prefix_chars='-', fromfile_prefix_chars=None, \ + argument_default=None, conflict_handler='error', \ + add_help=True, allow_abbrev=True, exit_on_error=True) + + Create a new :class:`ArgumentParser` object. All parameters should be passed + as keyword arguments. Each parameter has its own more detailed description + below, but in short they are: + + * prog_ - The name of the program (default: ``sys.argv[0]``) + + * usage_ - The string describing the program usage (default: generated from + arguments added to parser) + + * description_ - Text to display before the argument help (default: none) + + * epilog_ - Text to display after the argument help (default: none) + + * parents_ - A list of :class:`ArgumentParser` objects whose arguments should + also be included + + * formatter_class_ - A class for customizing the help output + + * prefix_chars_ - The set of characters that prefix optional arguments + (default: '-') + + * fromfile_prefix_chars_ - The set of characters that prefix files from + which additional arguments should be read (default: ``None``) + + * argument_default_ - The global default value for arguments + (default: ``None``) + + * conflict_handler_ - The strategy for resolving conflicting optionals + (usually unnecessary) + + * add_help_ - Add a ``-h/--help`` option to the parser (default: ``True``) + + * allow_abbrev_ - Allows long options to be abbreviated if the + abbreviation is unambiguous. (default: ``True``) + + * exit_on_error_ - Determines whether or not ArgumentParser exits with + error info when an error occurs. (default: ``True``) + + .. versionchanged:: 3.5 + *allow_abbrev* parameter was added. + + .. versionchanged:: 3.8 + In previous versions, *allow_abbrev* also disabled grouping of short + flags such as ``-vv`` to mean ``-v -v``. + + .. versionchanged:: 3.9 + *exit_on_error* parameter was added. + +The following sections describe how each of these are used. + + +prog +^^^^ + +By default, :class:`ArgumentParser` objects use ``sys.argv[0]`` to determine +how to display the name of the program in help messages. This default is almost +always desirable because it will make the help messages match how the program was +invoked on the command line. For example, consider a file named +``myprogram.py`` with the following code:: + + import argparse + parser = argparse.ArgumentParser() + parser.add_argument('--foo', help='foo help') + args = parser.parse_args() + +The help for this program will display ``myprogram.py`` as the program name +(regardless of where the program was invoked from): + +.. code-block:: shell-session + + $ python myprogram.py --help + usage: myprogram.py [-h] [--foo FOO] + + optional arguments: + -h, --help show this help message and exit + --foo FOO foo help + $ cd .. + $ python subdir/myprogram.py --help + usage: myprogram.py [-h] [--foo FOO] + + optional arguments: + -h, --help show this help message and exit + --foo FOO foo help + +To change this default behavior, another value can be supplied using the +``prog=`` argument to :class:`ArgumentParser`:: + + >>> parser = argparse.ArgumentParser(prog='myprogram') + >>> parser.print_help() + usage: myprogram [-h] + + optional arguments: + -h, --help show this help message and exit + +Note that the program name, whether determined from ``sys.argv[0]`` or from the +``prog=`` argument, is available to help messages using the ``%(prog)s`` format +specifier. + +:: + + >>> parser = argparse.ArgumentParser(prog='myprogram') + >>> parser.add_argument('--foo', help='foo of the %(prog)s program') + >>> parser.print_help() + usage: myprogram [-h] [--foo FOO] + + optional arguments: + -h, --help show this help message and exit + --foo FOO foo of the myprogram program + + +usage +^^^^^ + +By default, :class:`ArgumentParser` calculates the usage message from the +arguments it contains:: + + >>> parser = argparse.ArgumentParser(prog='PROG') + >>> parser.add_argument('--foo', nargs='?', help='foo help') + >>> parser.add_argument('bar', nargs='+', help='bar help') + >>> parser.print_help() + usage: PROG [-h] [--foo [FOO]] bar [bar ...] + + positional arguments: + bar bar help + + optional arguments: + -h, --help show this help message and exit + --foo [FOO] foo help + +The default message can be overridden with the ``usage=`` keyword argument:: + + >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]') + >>> parser.add_argument('--foo', nargs='?', help='foo help') + >>> parser.add_argument('bar', nargs='+', help='bar help') + >>> parser.print_help() + usage: PROG [options] + + positional arguments: + bar bar help + + optional arguments: + -h, --help show this help message and exit + --foo [FOO] foo help + +The ``%(prog)s`` format specifier is available to fill in the program name in +your usage messages. + + +description +^^^^^^^^^^^ + +Most calls to the :class:`ArgumentParser` constructor will use the +``description=`` keyword argument. This argument gives a brief description of +what the program does and how it works. In help messages, the description is +displayed between the command-line usage string and the help messages for the +various arguments:: + + >>> parser = argparse.ArgumentParser(description='A foo that bars') + >>> parser.print_help() + usage: argparse.py [-h] + + A foo that bars + + optional arguments: + -h, --help show this help message and exit + +By default, the description will be line-wrapped so that it fits within the +given space. To change this behavior, see the formatter_class_ argument. + + +epilog +^^^^^^ + +Some programs like to display additional description of the program after the +description of the arguments. Such text can be specified using the ``epilog=`` +argument to :class:`ArgumentParser`:: + + >>> parser = argparse.ArgumentParser( + ... description='A foo that bars', + ... epilog="And that's how you'd foo a bar") + >>> parser.print_help() + usage: argparse.py [-h] + + A foo that bars + + optional arguments: + -h, --help show this help message and exit + + And that's how you'd foo a bar + +As with the description_ argument, the ``epilog=`` text is by default +line-wrapped, but this behavior can be adjusted with the formatter_class_ +argument to :class:`ArgumentParser`. + + +parents +^^^^^^^ + +Sometimes, several parsers share a common set of arguments. Rather than +repeating the definitions of these arguments, a single parser with all the +shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser` +can be used. The ``parents=`` argument takes a list of :class:`ArgumentParser` +objects, collects all the positional and optional actions from them, and adds +these actions to the :class:`ArgumentParser` object being constructed:: + + >>> parent_parser = argparse.ArgumentParser(add_help=False) + >>> parent_parser.add_argument('--parent', type=int) + + >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser]) + >>> foo_parser.add_argument('foo') + >>> foo_parser.parse_args(['--parent', '2', 'XXX']) + Namespace(foo='XXX', parent=2) + + >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser]) + >>> bar_parser.add_argument('--bar') + >>> bar_parser.parse_args(['--bar', 'YYY']) + Namespace(bar='YYY', parent=None) + +Note that most parent parsers will specify ``add_help=False``. Otherwise, the +:class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent +and one in the child) and raise an error. + +.. note:: + You must fully initialize the parsers before passing them via ``parents=``. + If you change the parent parsers after the child parser, those changes will + not be reflected in the child. + + +formatter_class +^^^^^^^^^^^^^^^ + +:class:`ArgumentParser` objects allow the help formatting to be customized by +specifying an alternate formatting class. Currently, there are four such +classes: + +.. class:: RawDescriptionHelpFormatter + RawTextHelpFormatter + ArgumentDefaultsHelpFormatter + MetavarTypeHelpFormatter + +:class:`RawDescriptionHelpFormatter` and :class:`RawTextHelpFormatter` give +more control over how textual descriptions are displayed. +By default, :class:`ArgumentParser` objects line-wrap the description_ and +epilog_ texts in command-line help messages:: + + >>> parser = argparse.ArgumentParser( + ... prog='PROG', + ... description='''this description + ... was indented weird + ... but that is okay''', + ... epilog=''' + ... likewise for this epilog whose whitespace will + ... be cleaned up and whose words will be wrapped + ... across a couple lines''') + >>> parser.print_help() + usage: PROG [-h] + + this description was indented weird but that is okay + + optional arguments: + -h, --help show this help message and exit + + likewise for this epilog whose whitespace will be cleaned up and whose words + will be wrapped across a couple lines + +Passing :class:`RawDescriptionHelpFormatter` as ``formatter_class=`` +indicates that description_ and epilog_ are already correctly formatted and +should not be line-wrapped:: + + >>> parser = argparse.ArgumentParser( + ... prog='PROG', + ... formatter_class=argparse.RawDescriptionHelpFormatter, + ... description=textwrap.dedent('''\ + ... Please do not mess up this text! + ... -------------------------------- + ... I have indented it + ... exactly the way + ... I want it + ... ''')) + >>> parser.print_help() + usage: PROG [-h] + + Please do not mess up this text! + -------------------------------- + I have indented it + exactly the way + I want it + + optional arguments: + -h, --help show this help message and exit + +:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text, +including argument descriptions. However, multiple new lines are replaced with +one. If you wish to preserve multiple blank lines, add spaces between the +newlines. + +:class:`ArgumentDefaultsHelpFormatter` automatically adds information about +default values to each of the argument help messages:: + + >>> parser = argparse.ArgumentParser( + ... prog='PROG', + ... formatter_class=argparse.ArgumentDefaultsHelpFormatter) + >>> parser.add_argument('--foo', type=int, default=42, help='FOO!') + >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!') + >>> parser.print_help() + usage: PROG [-h] [--foo FOO] [bar ...] + + positional arguments: + bar BAR! (default: [1, 2, 3]) + + optional arguments: + -h, --help show this help message and exit + --foo FOO FOO! (default: 42) + +:class:`MetavarTypeHelpFormatter` uses the name of the type_ argument for each +argument as the display name for its values (rather than using the dest_ +as the regular formatter does):: + + >>> parser = argparse.ArgumentParser( + ... prog='PROG', + ... formatter_class=argparse.MetavarTypeHelpFormatter) + >>> parser.add_argument('--foo', type=int) + >>> parser.add_argument('bar', type=float) + >>> parser.print_help() + usage: PROG [-h] [--foo int] float + + positional arguments: + float + + optional arguments: + -h, --help show this help message and exit + --foo int + + +prefix_chars +^^^^^^^^^^^^ + +Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``. +Parsers that need to support different or additional prefix +characters, e.g. for options +like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument +to the ArgumentParser constructor:: + + >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+') + >>> parser.add_argument('+f') + >>> parser.add_argument('++bar') + >>> parser.parse_args('+f X ++bar Y'.split()) + Namespace(bar='Y', f='X') + +The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of +characters that does not include ``-`` will cause ``-f/--foo`` options to be +disallowed. + + +fromfile_prefix_chars +^^^^^^^^^^^^^^^^^^^^^ + +Sometimes, for example when dealing with a particularly long argument lists, it +may make sense to keep the list of arguments in a file rather than typing it out +at the command line. If the ``fromfile_prefix_chars=`` argument is given to the +:class:`ArgumentParser` constructor, then arguments that start with any of the +specified characters will be treated as files, and will be replaced by the +arguments they contain. For example:: + + >>> with open('args.txt', 'w') as fp: + ... fp.write('-f\nbar') + >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@') + >>> parser.add_argument('-f') + >>> parser.parse_args(['-f', 'foo', '@args.txt']) + Namespace(f='bar') + +Arguments read from a file must by default be one per line (but see also +:meth:`~ArgumentParser.convert_arg_line_to_args`) and are treated as if they +were in the same place as the original file referencing argument on the command +line. So in the example above, the expression ``['-f', 'foo', '@args.txt']`` +is considered equivalent to the expression ``['-f', 'foo', '-f', 'bar']``. + +The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that +arguments will never be treated as file references. + + +argument_default +^^^^^^^^^^^^^^^^ + +Generally, argument defaults are specified either by passing a default to +:meth:`~ArgumentParser.add_argument` or by calling the +:meth:`~ArgumentParser.set_defaults` methods with a specific set of name-value +pairs. Sometimes however, it may be useful to specify a single parser-wide +default for arguments. This can be accomplished by passing the +``argument_default=`` keyword argument to :class:`ArgumentParser`. For example, +to globally suppress attribute creation on :meth:`~ArgumentParser.parse_args` +calls, we supply ``argument_default=SUPPRESS``:: + + >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS) + >>> parser.add_argument('--foo') + >>> parser.add_argument('bar', nargs='?') + >>> parser.parse_args(['--foo', '1', 'BAR']) + Namespace(bar='BAR', foo='1') + >>> parser.parse_args([]) + Namespace() + +.. _allow_abbrev: + +allow_abbrev +^^^^^^^^^^^^ + +Normally, when you pass an argument list to the +:meth:`~ArgumentParser.parse_args` method of an :class:`ArgumentParser`, +it :ref:`recognizes abbreviations ` of long options. + +This feature can be disabled by setting ``allow_abbrev`` to ``False``:: + + >>> parser = argparse.ArgumentParser(prog='PROG', allow_abbrev=False) + >>> parser.add_argument('--foobar', action='store_true') + >>> parser.add_argument('--foonley', action='store_false') + >>> parser.parse_args(['--foon']) + usage: PROG [-h] [--foobar] [--foonley] + PROG: error: unrecognized arguments: --foon + +.. versionadded:: 3.5 + + +conflict_handler +^^^^^^^^^^^^^^^^ + +:class:`ArgumentParser` objects do not allow two actions with the same option +string. By default, :class:`ArgumentParser` objects raise an exception if an +attempt is made to create an argument with an option string that is already in +use:: + + >>> parser = argparse.ArgumentParser(prog='PROG') + >>> parser.add_argument('-f', '--foo', help='old foo help') + >>> parser.add_argument('--foo', help='new foo help') + Traceback (most recent call last): + .. + ArgumentError: argument --foo: conflicting option string(s): --foo + +Sometimes (e.g. when using parents_) it may be useful to simply override any +older arguments with the same option string. To get this behavior, the value +``'resolve'`` can be supplied to the ``conflict_handler=`` argument of +:class:`ArgumentParser`:: + + >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve') + >>> parser.add_argument('-f', '--foo', help='old foo help') + >>> parser.add_argument('--foo', help='new foo help') + >>> parser.print_help() + usage: PROG [-h] [-f FOO] [--foo FOO] + + optional arguments: + -h, --help show this help message and exit + -f FOO old foo help + --foo FOO new foo help + +Note that :class:`ArgumentParser` objects only remove an action if all of its +option strings are overridden. So, in the example above, the old ``-f/--foo`` +action is retained as the ``-f`` action, because only the ``--foo`` option +string was overridden. + + +add_help +^^^^^^^^ + +By default, ArgumentParser objects add an option which simply displays +the parser's help message. For example, consider a file named +``myprogram.py`` containing the following code:: + + import argparse + parser = argparse.ArgumentParser() + parser.add_argument('--foo', help='foo help') + args = parser.parse_args() + +If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser +help will be printed: + +.. code-block:: shell-session + + $ python myprogram.py --help + usage: myprogram.py [-h] [--foo FOO] + + optional arguments: + -h, --help show this help message and exit + --foo FOO foo help + +Occasionally, it may be useful to disable the addition of this help option. +This can be achieved by passing ``False`` as the ``add_help=`` argument to +:class:`ArgumentParser`:: + + >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False) + >>> parser.add_argument('--foo', help='foo help') + >>> parser.print_help() + usage: PROG [--foo FOO] + + optional arguments: + --foo FOO foo help + +The help option is typically ``-h/--help``. The exception to this is +if the ``prefix_chars=`` is specified and does not include ``-``, in +which case ``-h`` and ``--help`` are not valid options. In +this case, the first character in ``prefix_chars`` is used to prefix +the help options:: + + >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/') + >>> parser.print_help() + usage: PROG [+h] + + optional arguments: + +h, ++help show this help message and exit + + +exit_on_error +^^^^^^^^^^^^^ + +Normally, when you pass an invalid argument list to the :meth:`~ArgumentParser.parse_args` +method of an :class:`ArgumentParser`, it will exit with error info. + +If the user would like catch errors manually, the feature can be enable by setting +``exit_on_error`` to ``False``:: + + >>> parser = argparse.ArgumentParser(exit_on_error=False) + >>> parser.add_argument('--integers', type=int) + _StoreAction(option_strings=['--integers'], dest='integers', nargs=None, const=None, default=None, type=, choices=None, help=None, metavar=None) + >>> try: + ... parser.parse_args('--integers a'.split()) + ... except argparse.ArgumentError: + ... print('Catching an argumentError') + ... + Catching an argumentError + +.. versionadded:: 3.9 + + +The add_argument() method +------------------------- + +.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \ + [const], [default], [type], [choices], [required], \ + [help], [metavar], [dest]) + + Define how a single command-line argument should be parsed. Each parameter + has its own more detailed description below, but in short they are: + + * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo`` + or ``-f, --foo``. + + * action_ - The basic type of action to be taken when this argument is + encountered at the command line. + + * nargs_ - The number of command-line arguments that should be consumed. + + * const_ - A constant value required by some action_ and nargs_ selections. + + * default_ - The value produced if the argument is absent from the + command line. + + * type_ - The type to which the command-line argument should be converted. + + * choices_ - A container of the allowable values for the argument. + + * required_ - Whether or not the command-line option may be omitted + (optionals only). + + * help_ - A brief description of what the argument does. + + * metavar_ - A name for the argument in usage messages. + + * dest_ - The name of the attribute to be added to the object returned by + :meth:`parse_args`. + +The following sections describe how each of these are used. + + +name or flags +^^^^^^^^^^^^^ + +The :meth:`~ArgumentParser.add_argument` method must know whether an optional +argument, like ``-f`` or ``--foo``, or a positional argument, like a list of +filenames, is expected. The first arguments passed to +:meth:`~ArgumentParser.add_argument` must therefore be either a series of +flags, or a simple argument name. For example, an optional argument could +be created like:: + + >>> parser.add_argument('-f', '--foo') + +while a positional argument could be created like:: + + >>> parser.add_argument('bar') + +When :meth:`~ArgumentParser.parse_args` is called, optional arguments will be +identified by the ``-`` prefix, and the remaining arguments will be assumed to +be positional:: + + >>> parser = argparse.ArgumentParser(prog='PROG') + >>> parser.add_argument('-f', '--foo') + >>> parser.add_argument('bar') + >>> parser.parse_args(['BAR']) + Namespace(bar='BAR', foo=None) + >>> parser.parse_args(['BAR', '--foo', 'FOO']) + Namespace(bar='BAR', foo='FOO') + >>> parser.parse_args(['--foo', 'FOO']) + usage: PROG [-h] [-f FOO] bar + PROG: error: the following arguments are required: bar + + +action +^^^^^^ + +:class:`ArgumentParser` objects associate command-line arguments with actions. These +actions can do just about anything with the command-line arguments associated with +them, though most actions simply add an attribute to the object returned by +:meth:`~ArgumentParser.parse_args`. The ``action`` keyword argument specifies +how the command-line arguments should be handled. The supplied actions are: + +* ``'store'`` - This just stores the argument's value. This is the default + action. For example:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('--foo') + >>> parser.parse_args('--foo 1'.split()) + Namespace(foo='1') + +* ``'store_const'`` - This stores the value specified by the const_ keyword + argument. The ``'store_const'`` action is most commonly used with + optional arguments that specify some sort of flag. For example:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('--foo', action='store_const', const=42) + >>> parser.parse_args(['--foo']) + Namespace(foo=42) + +* ``'store_true'`` and ``'store_false'`` - These are special cases of + ``'store_const'`` used for storing the values ``True`` and ``False`` + respectively. In addition, they create default values of ``False`` and + ``True`` respectively. For example:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('--foo', action='store_true') + >>> parser.add_argument('--bar', action='store_false') + >>> parser.add_argument('--baz', action='store_false') + >>> parser.parse_args('--foo --bar'.split()) + Namespace(foo=True, bar=False, baz=True) + +* ``'append'`` - This stores a list, and appends each argument value to the + list. This is useful to allow an option to be specified multiple times. + Example usage:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('--foo', action='append') + >>> parser.parse_args('--foo 1 --foo 2'.split()) + Namespace(foo=['1', '2']) + +* ``'append_const'`` - This stores a list, and appends the value specified by + the const_ keyword argument to the list. (Note that the const_ keyword + argument defaults to ``None``.) The ``'append_const'`` action is typically + useful when multiple arguments need to store constants to the same list. For + example:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('--str', dest='types', action='append_const', const=str) + >>> parser.add_argument('--int', dest='types', action='append_const', const=int) + >>> parser.parse_args('--str --int'.split()) + Namespace(types=[, ]) + +* ``'count'`` - This counts the number of times a keyword argument occurs. For + example, this is useful for increasing verbosity levels:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('--verbose', '-v', action='count', default=0) + >>> parser.parse_args(['-vvv']) + Namespace(verbose=3) + + Note, the *default* will be ``None`` unless explicitly set to *0*. + +* ``'help'`` - This prints a complete help message for all the options in the + current parser and then exits. By default a help action is automatically + added to the parser. See :class:`ArgumentParser` for details of how the + output is created. + +* ``'version'`` - This expects a ``version=`` keyword argument in the + :meth:`~ArgumentParser.add_argument` call, and prints version information + and exits when invoked:: + + >>> import argparse + >>> parser = argparse.ArgumentParser(prog='PROG') + >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0') + >>> parser.parse_args(['--version']) + PROG 2.0 + +* ``'extend'`` - This stores a list, and extends each argument value to the + list. + Example usage:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument("--foo", action="extend", nargs="+", type=str) + >>> parser.parse_args(["--foo", "f1", "--foo", "f2", "f3", "f4"]) + Namespace(foo=['f1', 'f2', 'f3', 'f4']) + + .. versionadded:: 3.8 + +You may also specify an arbitrary action by passing an Action subclass or +other object that implements the same interface. The ``BooleanOptionalAction`` +is available in ``argparse`` and adds support for boolean actions such as +``--foo`` and ``--no-foo``:: + + >>> import argparse + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('--foo', action=argparse.BooleanOptionalAction) + >>> parser.parse_args(['--no-foo']) + Namespace(foo=False) + +The recommended way to create a custom action is to extend :class:`Action`, +overriding the ``__call__`` method and optionally the ``__init__`` and +``format_usage`` methods. + +An example of a custom action:: + + >>> class FooAction(argparse.Action): + ... def __init__(self, option_strings, dest, nargs=None, **kwargs): + ... if nargs is not None: + ... raise ValueError("nargs not allowed") + ... super(FooAction, self).__init__(option_strings, dest, **kwargs) + ... def __call__(self, parser, namespace, values, option_string=None): + ... print('%r %r %r' % (namespace, values, option_string)) + ... setattr(namespace, self.dest, values) + ... + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('--foo', action=FooAction) + >>> parser.add_argument('bar', action=FooAction) + >>> args = parser.parse_args('1 --foo 2'.split()) + Namespace(bar=None, foo=None) '1' None + Namespace(bar='1', foo=None) '2' '--foo' + >>> args + Namespace(bar='1', foo='2') + +For more details, see :class:`Action`. + +nargs +^^^^^ + +ArgumentParser objects usually associate a single command-line argument with a +single action to be taken. The ``nargs`` keyword argument associates a +different number of command-line arguments with a single action. The supported +values are: + +* ``N`` (an integer). ``N`` arguments from the command line will be gathered + together into a list. For example:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('--foo', nargs=2) + >>> parser.add_argument('bar', nargs=1) + >>> parser.parse_args('c --foo a b'.split()) + Namespace(bar=['c'], foo=['a', 'b']) + + Note that ``nargs=1`` produces a list of one item. This is different from + the default, in which the item is produced by itself. + +.. index:: single: ? (question mark); in argparse module + +* ``'?'``. One argument will be consumed from the command line if possible, and + produced as a single item. If no command-line argument is present, the value from + default_ will be produced. Note that for optional arguments, there is an + additional case - the option string is present but not followed by a + command-line argument. In this case the value from const_ will be produced. Some + examples to illustrate this:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('--foo', nargs='?', const='c', default='d') + >>> parser.add_argument('bar', nargs='?', default='d') + >>> parser.parse_args(['XX', '--foo', 'YY']) + Namespace(bar='XX', foo='YY') + >>> parser.parse_args(['XX', '--foo']) + Namespace(bar='XX', foo='c') + >>> parser.parse_args([]) + Namespace(bar='d', foo='d') + + One of the more common uses of ``nargs='?'`` is to allow optional input and + output files:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'), + ... default=sys.stdin) + >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'), + ... default=sys.stdout) + >>> parser.parse_args(['input.txt', 'output.txt']) + Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>, + outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>) + >>> parser.parse_args([]) + Namespace(infile=<_io.TextIOWrapper name='' encoding='UTF-8'>, + outfile=<_io.TextIOWrapper name='' encoding='UTF-8'>) + +.. index:: single: * (asterisk); in argparse module + +* ``'*'``. All command-line arguments present are gathered into a list. Note that + it generally doesn't make much sense to have more than one positional argument + with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is + possible. For example:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('--foo', nargs='*') + >>> parser.add_argument('--bar', nargs='*') + >>> parser.add_argument('baz', nargs='*') + >>> parser.parse_args('a b --foo x y --bar 1 2'.split()) + Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y']) + +.. index:: single: + (plus); in argparse module + +* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a + list. Additionally, an error message will be generated if there wasn't at + least one command-line argument present. For example:: + + >>> parser = argparse.ArgumentParser(prog='PROG') + >>> parser.add_argument('foo', nargs='+') + >>> parser.parse_args(['a', 'b']) + Namespace(foo=['a', 'b']) + >>> parser.parse_args([]) + usage: PROG [-h] foo [foo ...] + PROG: error: the following arguments are required: foo + +.. _`argparse.REMAINDER`: + +* ``argparse.REMAINDER``. All the remaining command-line arguments are gathered + into a list. This is commonly useful for command line utilities that dispatch + to other command line utilities:: + + >>> parser = argparse.ArgumentParser(prog='PROG') + >>> parser.add_argument('--foo') + >>> parser.add_argument('command') + >>> parser.add_argument('args', nargs=argparse.REMAINDER) + >>> print(parser.parse_args('--foo B cmd --arg1 XX ZZ'.split())) + Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B') + +If the ``nargs`` keyword argument is not provided, the number of arguments consumed +is determined by the action_. Generally this means a single command-line argument +will be consumed and a single item (not a list) will be produced. + + +const +^^^^^ + +The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to hold +constant values that are not read from the command line but are required for +the various :class:`ArgumentParser` actions. The two most common uses of it are: + +* When :meth:`~ArgumentParser.add_argument` is called with + ``action='store_const'`` or ``action='append_const'``. These actions add the + ``const`` value to one of the attributes of the object returned by + :meth:`~ArgumentParser.parse_args`. See the action_ description for examples. + +* When :meth:`~ArgumentParser.add_argument` is called with option strings + (like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional + argument that can be followed by zero or one command-line arguments. + When parsing the command line, if the option string is encountered with no + command-line argument following it, the value of ``const`` will be assumed instead. + See the nargs_ description for examples. + +With the ``'store_const'`` and ``'append_const'`` actions, the ``const`` +keyword argument must be given. For other actions, it defaults to ``None``. + + +default +^^^^^^^ + +All optional arguments and some positional arguments may be omitted at the +command line. The ``default`` keyword argument of +:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``, +specifies what value should be used if the command-line argument is not present. +For optional arguments, the ``default`` value is used when the option string +was not present at the command line:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('--foo', default=42) + >>> parser.parse_args(['--foo', '2']) + Namespace(foo='2') + >>> parser.parse_args([]) + Namespace(foo=42) + +If the ``default`` value is a string, the parser parses the value as if it +were a command-line argument. In particular, the parser applies any type_ +conversion argument, if provided, before setting the attribute on the +:class:`Namespace` return value. Otherwise, the parser uses the value as is:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('--length', default='10', type=int) + >>> parser.add_argument('--width', default=10.5, type=int) + >>> parser.parse_args() + Namespace(length=10, width=10.5) + +For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value +is used when no command-line argument was present:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('foo', nargs='?', default=42) + >>> parser.parse_args(['a']) + Namespace(foo='a') + >>> parser.parse_args([]) + Namespace(foo=42) + + +Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the +command-line argument was not present:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('--foo', default=argparse.SUPPRESS) + >>> parser.parse_args([]) + Namespace() + >>> parser.parse_args(['--foo', '1']) + Namespace(foo='1') + + +type +^^^^ + +By default, :class:`ArgumentParser` objects read command-line arguments in as simple +strings. However, quite often the command-line string should instead be +interpreted as another type, like a :class:`float` or :class:`int`. The +``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any +necessary type-checking and type conversions to be performed. Common built-in +types and functions can be used directly as the value of the ``type`` argument:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('foo', type=int) + >>> parser.add_argument('bar', type=open) + >>> parser.parse_args('2 temp.txt'.split()) + Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2) + +See the section on the default_ keyword argument for information on when the +``type`` argument is applied to default arguments. + +To ease the use of various types of files, the argparse module provides the +factory FileType which takes the ``mode=``, ``bufsize=``, ``encoding=`` and +``errors=`` arguments of the :func:`open` function. For example, +``FileType('w')`` can be used to create a writable file:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('bar', type=argparse.FileType('w')) + >>> parser.parse_args(['out.txt']) + Namespace(bar=<_io.TextIOWrapper name='out.txt' encoding='UTF-8'>) + +``type=`` can take any callable that takes a single string argument and returns +the converted value:: + + >>> def perfect_square(string): + ... value = int(string) + ... sqrt = math.sqrt(value) + ... if sqrt != int(sqrt): + ... msg = "%r is not a perfect square" % string + ... raise argparse.ArgumentTypeError(msg) + ... return value + ... + >>> parser = argparse.ArgumentParser(prog='PROG') + >>> parser.add_argument('foo', type=perfect_square) + >>> parser.parse_args(['9']) + Namespace(foo=9) + >>> parser.parse_args(['7']) + usage: PROG [-h] foo + PROG: error: argument foo: '7' is not a perfect square + +The choices_ keyword argument may be more convenient for type checkers that +simply check against a range of values:: + + >>> parser = argparse.ArgumentParser(prog='PROG') + >>> parser.add_argument('foo', type=int, choices=range(5, 10)) + >>> parser.parse_args(['7']) + Namespace(foo=7) + >>> parser.parse_args(['11']) + usage: PROG [-h] {5,6,7,8,9} + PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9) + +See the choices_ section for more details. + + +choices +^^^^^^^ + +Some command-line arguments should be selected from a restricted set of values. +These can be handled by passing a container object as the *choices* keyword +argument to :meth:`~ArgumentParser.add_argument`. When the command line is +parsed, argument values will be checked, and an error message will be displayed +if the argument was not one of the acceptable values:: + + >>> parser = argparse.ArgumentParser(prog='game.py') + >>> parser.add_argument('move', choices=['rock', 'paper', 'scissors']) + >>> parser.parse_args(['rock']) + Namespace(move='rock') + >>> parser.parse_args(['fire']) + usage: game.py [-h] {rock,paper,scissors} + game.py: error: argument move: invalid choice: 'fire' (choose from 'rock', + 'paper', 'scissors') + +Note that inclusion in the *choices* container is checked after any type_ +conversions have been performed, so the type of the objects in the *choices* +container should match the type_ specified:: + + >>> parser = argparse.ArgumentParser(prog='doors.py') + >>> parser.add_argument('door', type=int, choices=range(1, 4)) + >>> print(parser.parse_args(['3'])) + Namespace(door=3) + >>> parser.parse_args(['4']) + usage: doors.py [-h] {1,2,3} + doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3) + +Any container can be passed as the *choices* value, so :class:`list` objects, +:class:`set` objects, and custom containers are all supported. + + +required +^^^^^^^^ + +In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar`` +indicate *optional* arguments, which can always be omitted at the command line. +To make an option *required*, ``True`` can be specified for the ``required=`` +keyword argument to :meth:`~ArgumentParser.add_argument`:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('--foo', required=True) + >>> parser.parse_args(['--foo', 'BAR']) + Namespace(foo='BAR') + >>> parser.parse_args([]) + usage: argparse.py [-h] [--foo FOO] + argparse.py: error: option --foo is required + +As the example shows, if an option is marked as ``required``, +:meth:`~ArgumentParser.parse_args` will report an error if that option is not +present at the command line. + +.. note:: + + Required options are generally considered bad form because users expect + *options* to be *optional*, and thus they should be avoided when possible. + + +help +^^^^ + +The ``help`` value is a string containing a brief description of the argument. +When a user requests help (usually by using ``-h`` or ``--help`` at the +command line), these ``help`` descriptions will be displayed with each +argument:: + + >>> parser = argparse.ArgumentParser(prog='frobble') + >>> parser.add_argument('--foo', action='store_true', + ... help='foo the bars before frobbling') + >>> parser.add_argument('bar', nargs='+', + ... help='one of the bars to be frobbled') + >>> parser.parse_args(['-h']) + usage: frobble [-h] [--foo] bar [bar ...] + + positional arguments: + bar one of the bars to be frobbled + + optional arguments: + -h, --help show this help message and exit + --foo foo the bars before frobbling + +The ``help`` strings can include various format specifiers to avoid repetition +of things like the program name or the argument default_. The available +specifiers include the program name, ``%(prog)s`` and most keyword arguments to +:meth:`~ArgumentParser.add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.:: + + >>> parser = argparse.ArgumentParser(prog='frobble') + >>> parser.add_argument('bar', nargs='?', type=int, default=42, + ... help='the bar to %(prog)s (default: %(default)s)') + >>> parser.print_help() + usage: frobble [-h] [bar] + + positional arguments: + bar the bar to frobble (default: 42) + + optional arguments: + -h, --help show this help message and exit + +As the help string supports %-formatting, if you want a literal ``%`` to appear +in the help string, you must escape it as ``%%``. + +:mod:`argparse` supports silencing the help entry for certain options, by +setting the ``help`` value to ``argparse.SUPPRESS``:: + + >>> parser = argparse.ArgumentParser(prog='frobble') + >>> parser.add_argument('--foo', help=argparse.SUPPRESS) + >>> parser.print_help() + usage: frobble [-h] + + optional arguments: + -h, --help show this help message and exit + + +metavar +^^^^^^^ + +When :class:`ArgumentParser` generates help messages, it needs some way to refer +to each expected argument. By default, ArgumentParser objects use the dest_ +value as the "name" of each object. By default, for positional argument +actions, the dest_ value is used directly, and for optional argument actions, +the dest_ value is uppercased. So, a single positional argument with +``dest='bar'`` will be referred to as ``bar``. A single +optional argument ``--foo`` that should be followed by a single command-line argument +will be referred to as ``FOO``. An example:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('--foo') + >>> parser.add_argument('bar') + >>> parser.parse_args('X --foo Y'.split()) + Namespace(bar='X', foo='Y') + >>> parser.print_help() + usage: [-h] [--foo FOO] bar + + positional arguments: + bar + + optional arguments: + -h, --help show this help message and exit + --foo FOO + +An alternative name can be specified with ``metavar``:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('--foo', metavar='YYY') + >>> parser.add_argument('bar', metavar='XXX') + >>> parser.parse_args('X --foo Y'.split()) + Namespace(bar='X', foo='Y') + >>> parser.print_help() + usage: [-h] [--foo YYY] XXX + + positional arguments: + XXX + + optional arguments: + -h, --help show this help message and exit + --foo YYY + +Note that ``metavar`` only changes the *displayed* name - the name of the +attribute on the :meth:`~ArgumentParser.parse_args` object is still determined +by the dest_ value. + +Different values of ``nargs`` may cause the metavar to be used multiple times. +Providing a tuple to ``metavar`` specifies a different display for each of the +arguments:: + + >>> parser = argparse.ArgumentParser(prog='PROG') + >>> parser.add_argument('-x', nargs=2) + >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz')) + >>> parser.print_help() + usage: PROG [-h] [-x X X] [--foo bar baz] + + optional arguments: + -h, --help show this help message and exit + -x X X + --foo bar baz + + +dest +^^^^ + +Most :class:`ArgumentParser` actions add some value as an attribute of the +object returned by :meth:`~ArgumentParser.parse_args`. The name of this +attribute is determined by the ``dest`` keyword argument of +:meth:`~ArgumentParser.add_argument`. For positional argument actions, +``dest`` is normally supplied as the first argument to +:meth:`~ArgumentParser.add_argument`:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('bar') + >>> parser.parse_args(['XXX']) + Namespace(bar='XXX') + +For optional argument actions, the value of ``dest`` is normally inferred from +the option strings. :class:`ArgumentParser` generates the value of ``dest`` by +taking the first long option string and stripping away the initial ``--`` +string. If no long option strings were supplied, ``dest`` will be derived from +the first short option string by stripping the initial ``-`` character. Any +internal ``-`` characters will be converted to ``_`` characters to make sure +the string is a valid attribute name. The examples below illustrate this +behavior:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('-f', '--foo-bar', '--foo') + >>> parser.add_argument('-x', '-y') + >>> parser.parse_args('-f 1 -x 2'.split()) + Namespace(foo_bar='1', x='2') + >>> parser.parse_args('--foo 1 -y 2'.split()) + Namespace(foo_bar='1', x='2') + +``dest`` allows a custom attribute name to be provided:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('--foo', dest='bar') + >>> parser.parse_args('--foo XXX'.split()) + Namespace(bar='XXX') + +Action classes +^^^^^^^^^^^^^^ + +Action classes implement the Action API, a callable which returns a callable +which processes arguments from the command-line. Any object which follows +this API may be passed as the ``action`` parameter to +:meth:`add_argument`. + +.. class:: Action(option_strings, dest, nargs=None, const=None, default=None, \ + type=None, choices=None, required=False, help=None, \ + metavar=None) + +Action objects are used by an ArgumentParser to represent the information +needed to parse a single argument from one or more strings from the +command line. The Action class must accept the two positional arguments +plus any keyword arguments passed to :meth:`ArgumentParser.add_argument` +except for the ``action`` itself. + +Instances of Action (or return value of any callable to the ``action`` +parameter) should have attributes "dest", "option_strings", "default", "type", +"required", "help", etc. defined. The easiest way to ensure these attributes +are defined is to call ``Action.__init__``. + +Action instances should be callable, so subclasses must override the +``__call__`` method, which should accept four parameters: + +* ``parser`` - The ArgumentParser object which contains this action. + +* ``namespace`` - The :class:`Namespace` object that will be returned by + :meth:`~ArgumentParser.parse_args`. Most actions add an attribute to this + object using :func:`setattr`. + +* ``values`` - The associated command-line arguments, with any type conversions + applied. Type conversions are specified with the type_ keyword argument to + :meth:`~ArgumentParser.add_argument`. + +* ``option_string`` - The option string that was used to invoke this action. + The ``option_string`` argument is optional, and will be absent if the action + is associated with a positional argument. + +The ``__call__`` method may perform arbitrary actions, but will typically set +attributes on the ``namespace`` based on ``dest`` and ``values``. + +Action subclasses can define a ``format_usage`` method that takes no argument +and return a string which will be used when printing the usage of the program. +If such method is not provided, a sensible default will be used. + +The parse_args() method +----------------------- + +.. method:: ArgumentParser.parse_args(args=None, namespace=None) + + Convert argument strings to objects and assign them as attributes of the + namespace. Return the populated namespace. + + Previous calls to :meth:`add_argument` determine exactly what objects are + created and how they are assigned. See the documentation for + :meth:`add_argument` for details. + + * args_ - List of strings to parse. The default is taken from + :data:`sys.argv`. + + * namespace_ - An object to take the attributes. The default is a new empty + :class:`Namespace` object. + + +Option value syntax +^^^^^^^^^^^^^^^^^^^ + +The :meth:`~ArgumentParser.parse_args` method supports several ways of +specifying the value of an option (if it takes one). In the simplest case, the +option and its value are passed as two separate arguments:: + + >>> parser = argparse.ArgumentParser(prog='PROG') + >>> parser.add_argument('-x') + >>> parser.add_argument('--foo') + >>> parser.parse_args(['-x', 'X']) + Namespace(foo=None, x='X') + >>> parser.parse_args(['--foo', 'FOO']) + Namespace(foo='FOO', x=None) + +For long options (options with names longer than a single character), the option +and value can also be passed as a single command-line argument, using ``=`` to +separate them:: + + >>> parser.parse_args(['--foo=FOO']) + Namespace(foo='FOO', x=None) + +For short options (options only one character long), the option and its value +can be concatenated:: + + >>> parser.parse_args(['-xX']) + Namespace(foo=None, x='X') + +Several short options can be joined together, using only a single ``-`` prefix, +as long as only the last option (or none of them) requires a value:: + + >>> parser = argparse.ArgumentParser(prog='PROG') + >>> parser.add_argument('-x', action='store_true') + >>> parser.add_argument('-y', action='store_true') + >>> parser.add_argument('-z') + >>> parser.parse_args(['-xyzZ']) + Namespace(x=True, y=True, z='Z') + + +Invalid arguments +^^^^^^^^^^^^^^^^^ + +While parsing the command line, :meth:`~ArgumentParser.parse_args` checks for a +variety of errors, including ambiguous options, invalid types, invalid options, +wrong number of positional arguments, etc. When it encounters such an error, +it exits and prints the error along with a usage message:: + + >>> parser = argparse.ArgumentParser(prog='PROG') + >>> parser.add_argument('--foo', type=int) + >>> parser.add_argument('bar', nargs='?') + + >>> # invalid type + >>> parser.parse_args(['--foo', 'spam']) + usage: PROG [-h] [--foo FOO] [bar] + PROG: error: argument --foo: invalid int value: 'spam' + + >>> # invalid option + >>> parser.parse_args(['--bar']) + usage: PROG [-h] [--foo FOO] [bar] + PROG: error: no such option: --bar + + >>> # wrong number of arguments + >>> parser.parse_args(['spam', 'badger']) + usage: PROG [-h] [--foo FOO] [bar] + PROG: error: extra arguments found: badger + + +Arguments containing ``-`` +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever +the user has clearly made a mistake, but some situations are inherently +ambiguous. For example, the command-line argument ``-1`` could either be an +attempt to specify an option or an attempt to provide a positional argument. +The :meth:`~ArgumentParser.parse_args` method is cautious here: positional +arguments may only begin with ``-`` if they look like negative numbers and +there are no options in the parser that look like negative numbers:: + + >>> parser = argparse.ArgumentParser(prog='PROG') + >>> parser.add_argument('-x') + >>> parser.add_argument('foo', nargs='?') + + >>> # no negative number options, so -1 is a positional argument + >>> parser.parse_args(['-x', '-1']) + Namespace(foo=None, x='-1') + + >>> # no negative number options, so -1 and -5 are positional arguments + >>> parser.parse_args(['-x', '-1', '-5']) + Namespace(foo='-5', x='-1') + + >>> parser = argparse.ArgumentParser(prog='PROG') + >>> parser.add_argument('-1', dest='one') + >>> parser.add_argument('foo', nargs='?') + + >>> # negative number options present, so -1 is an option + >>> parser.parse_args(['-1', 'X']) + Namespace(foo=None, one='X') + + >>> # negative number options present, so -2 is an option + >>> parser.parse_args(['-2']) + usage: PROG [-h] [-1 ONE] [foo] + PROG: error: no such option: -2 + + >>> # negative number options present, so both -1s are options + >>> parser.parse_args(['-1', '-1']) + usage: PROG [-h] [-1 ONE] [foo] + PROG: error: argument -1: expected one argument + +If you have positional arguments that must begin with ``-`` and don't look +like negative numbers, you can insert the pseudo-argument ``'--'`` which tells +:meth:`~ArgumentParser.parse_args` that everything after that is a positional +argument:: + + >>> parser.parse_args(['--', '-f']) + Namespace(foo='-f', one=None) + +.. _prefix-matching: + +Argument abbreviations (prefix matching) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The :meth:`~ArgumentParser.parse_args` method :ref:`by default ` +allows long options to be abbreviated to a prefix, if the abbreviation is +unambiguous (the prefix matches a unique option):: + + >>> parser = argparse.ArgumentParser(prog='PROG') + >>> parser.add_argument('-bacon') + >>> parser.add_argument('-badger') + >>> parser.parse_args('-bac MMM'.split()) + Namespace(bacon='MMM', badger=None) + >>> parser.parse_args('-bad WOOD'.split()) + Namespace(bacon=None, badger='WOOD') + >>> parser.parse_args('-ba BA'.split()) + usage: PROG [-h] [-bacon BACON] [-badger BADGER] + PROG: error: ambiguous option: -ba could match -badger, -bacon + +An error is produced for arguments that could produce more than one options. +This feature can be disabled by setting :ref:`allow_abbrev` to ``False``. + +.. _args: + +Beyond ``sys.argv`` +^^^^^^^^^^^^^^^^^^^ + +Sometimes it may be useful to have an ArgumentParser parse arguments other than those +of :data:`sys.argv`. This can be accomplished by passing a list of strings to +:meth:`~ArgumentParser.parse_args`. This is useful for testing at the +interactive prompt:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument( + ... 'integers', metavar='int', type=int, choices=range(10), + ... nargs='+', help='an integer in the range 0..9') + >>> parser.add_argument( + ... '--sum', dest='accumulate', action='store_const', const=sum, + ... default=max, help='sum the integers (default: find the max)') + >>> parser.parse_args(['1', '2', '3', '4']) + Namespace(accumulate=, integers=[1, 2, 3, 4]) + >>> parser.parse_args(['1', '2', '3', '4', '--sum']) + Namespace(accumulate=, integers=[1, 2, 3, 4]) + +.. _namespace: + +The Namespace object +^^^^^^^^^^^^^^^^^^^^ + +.. class:: Namespace + + Simple class used by default by :meth:`~ArgumentParser.parse_args` to create + an object holding attributes and return it. + +This class is deliberately simple, just an :class:`object` subclass with a +readable string representation. If you prefer to have dict-like view of the +attributes, you can use the standard Python idiom, :func:`vars`:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('--foo') + >>> args = parser.parse_args(['--foo', 'BAR']) + >>> vars(args) + {'foo': 'BAR'} + +It may also be useful to have an :class:`ArgumentParser` assign attributes to an +already existing object, rather than a new :class:`Namespace` object. This can +be achieved by specifying the ``namespace=`` keyword argument:: + + >>> class C: + ... pass + ... + >>> c = C() + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('--foo') + >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c) + >>> c.foo + 'BAR' + + +Other utilities +--------------- + +Sub-commands +^^^^^^^^^^^^ + +.. method:: ArgumentParser.add_subparsers([title], [description], [prog], \ + [parser_class], [action], \ + [option_string], [dest], [required], \ + [help], [metavar]) + + Many programs split up their functionality into a number of sub-commands, + for example, the ``svn`` program can invoke sub-commands like ``svn + checkout``, ``svn update``, and ``svn commit``. Splitting up functionality + this way can be a particularly good idea when a program performs several + different functions which require different kinds of command-line arguments. + :class:`ArgumentParser` supports the creation of such sub-commands with the + :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally + called with no arguments and returns a special action object. This object + has a single method, :meth:`~ArgumentParser.add_parser`, which takes a + command name and any :class:`ArgumentParser` constructor arguments, and + returns an :class:`ArgumentParser` object that can be modified as usual. + + Description of parameters: + + * title - title for the sub-parser group in help output; by default + "subcommands" if description is provided, otherwise uses title for + positional arguments + + * description - description for the sub-parser group in help output, by + default ``None`` + + * prog - usage information that will be displayed with sub-command help, + by default the name of the program and any positional arguments before the + subparser argument + + * parser_class - class which will be used to create sub-parser instances, by + default the class of the current parser (e.g. ArgumentParser) + + * action_ - the basic type of action to be taken when this argument is + encountered at the command line + + * dest_ - name of the attribute under which sub-command name will be + stored; by default ``None`` and no value is stored + + * required_ - Whether or not a subcommand must be provided, by default + ``False`` (added in 3.7) + + * help_ - help for sub-parser group in help output, by default ``None`` + + * metavar_ - string presenting available sub-commands in help; by default it + is ``None`` and presents sub-commands in form {cmd1, cmd2, ..} + + Some example usage:: + + >>> # create the top-level parser + >>> parser = argparse.ArgumentParser(prog='PROG') + >>> parser.add_argument('--foo', action='store_true', help='foo help') + >>> subparsers = parser.add_subparsers(help='sub-command help') + >>> + >>> # create the parser for the "a" command + >>> parser_a = subparsers.add_parser('a', help='a help') + >>> parser_a.add_argument('bar', type=int, help='bar help') + >>> + >>> # create the parser for the "b" command + >>> parser_b = subparsers.add_parser('b', help='b help') + >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help') + >>> + >>> # parse some argument lists + >>> parser.parse_args(['a', '12']) + Namespace(bar=12, foo=False) + >>> parser.parse_args(['--foo', 'b', '--baz', 'Z']) + Namespace(baz='Z', foo=True) + + Note that the object returned by :meth:`parse_args` will only contain + attributes for the main parser and the subparser that was selected by the + command line (and not any other subparsers). So in the example above, when + the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are + present, and when the ``b`` command is specified, only the ``foo`` and + ``baz`` attributes are present. + + Similarly, when a help message is requested from a subparser, only the help + for that particular parser will be printed. The help message will not + include parent parser or sibling parser messages. (A help message for each + subparser command, however, can be given by supplying the ``help=`` argument + to :meth:`add_parser` as above.) + + :: + + >>> parser.parse_args(['--help']) + usage: PROG [-h] [--foo] {a,b} ... + + positional arguments: + {a,b} sub-command help + a a help + b b help + + optional arguments: + -h, --help show this help message and exit + --foo foo help + + >>> parser.parse_args(['a', '--help']) + usage: PROG a [-h] bar + + positional arguments: + bar bar help + + optional arguments: + -h, --help show this help message and exit + + >>> parser.parse_args(['b', '--help']) + usage: PROG b [-h] [--baz {X,Y,Z}] + + optional arguments: + -h, --help show this help message and exit + --baz {X,Y,Z} baz help + + The :meth:`add_subparsers` method also supports ``title`` and ``description`` + keyword arguments. When either is present, the subparser's commands will + appear in their own group in the help output. For example:: + + >>> parser = argparse.ArgumentParser() + >>> subparsers = parser.add_subparsers(title='subcommands', + ... description='valid subcommands', + ... help='additional help') + >>> subparsers.add_parser('foo') + >>> subparsers.add_parser('bar') + >>> parser.parse_args(['-h']) + usage: [-h] {foo,bar} ... + + optional arguments: + -h, --help show this help message and exit + + subcommands: + valid subcommands + + {foo,bar} additional help + + Furthermore, ``add_parser`` supports an additional ``aliases`` argument, + which allows multiple strings to refer to the same subparser. This example, + like ``svn``, aliases ``co`` as a shorthand for ``checkout``:: + + >>> parser = argparse.ArgumentParser() + >>> subparsers = parser.add_subparsers() + >>> checkout = subparsers.add_parser('checkout', aliases=['co']) + >>> checkout.add_argument('foo') + >>> parser.parse_args(['co', 'bar']) + Namespace(foo='bar') + + One particularly effective way of handling sub-commands is to combine the use + of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so + that each subparser knows which Python function it should execute. For + example:: + + >>> # sub-command functions + >>> def foo(args): + ... print(args.x * args.y) + ... + >>> def bar(args): + ... print('((%s))' % args.z) + ... + >>> # create the top-level parser + >>> parser = argparse.ArgumentParser() + >>> subparsers = parser.add_subparsers() + >>> + >>> # create the parser for the "foo" command + >>> parser_foo = subparsers.add_parser('foo') + >>> parser_foo.add_argument('-x', type=int, default=1) + >>> parser_foo.add_argument('y', type=float) + >>> parser_foo.set_defaults(func=foo) + >>> + >>> # create the parser for the "bar" command + >>> parser_bar = subparsers.add_parser('bar') + >>> parser_bar.add_argument('z') + >>> parser_bar.set_defaults(func=bar) + >>> + >>> # parse the args and call whatever function was selected + >>> args = parser.parse_args('foo 1 -x 2'.split()) + >>> args.func(args) + 2.0 + >>> + >>> # parse the args and call whatever function was selected + >>> args = parser.parse_args('bar XYZYX'.split()) + >>> args.func(args) + ((XYZYX)) + + This way, you can let :meth:`parse_args` do the job of calling the + appropriate function after argument parsing is complete. Associating + functions with actions like this is typically the easiest way to handle the + different actions for each of your subparsers. However, if it is necessary + to check the name of the subparser that was invoked, the ``dest`` keyword + argument to the :meth:`add_subparsers` call will work:: + + >>> parser = argparse.ArgumentParser() + >>> subparsers = parser.add_subparsers(dest='subparser_name') + >>> subparser1 = subparsers.add_parser('1') + >>> subparser1.add_argument('-x') + >>> subparser2 = subparsers.add_parser('2') + >>> subparser2.add_argument('y') + >>> parser.parse_args(['2', 'frobble']) + Namespace(subparser_name='2', y='frobble') + + .. versionchanged:: 3.7 + New *required* keyword argument. + + +FileType objects +^^^^^^^^^^^^^^^^ + +.. class:: FileType(mode='r', bufsize=-1, encoding=None, errors=None) + + The :class:`FileType` factory creates objects that can be passed to the type + argument of :meth:`ArgumentParser.add_argument`. Arguments that have + :class:`FileType` objects as their type will open command-line arguments as + files with the requested modes, buffer sizes, encodings and error handling + (see the :func:`open` function for more details):: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('--raw', type=argparse.FileType('wb', 0)) + >>> parser.add_argument('out', type=argparse.FileType('w', encoding='UTF-8')) + >>> parser.parse_args(['--raw', 'raw.dat', 'file.txt']) + Namespace(out=<_io.TextIOWrapper name='file.txt' mode='w' encoding='UTF-8'>, raw=<_io.FileIO name='raw.dat' mode='wb'>) + + FileType objects understand the pseudo-argument ``'-'`` and automatically + convert this into ``sys.stdin`` for readable :class:`FileType` objects and + ``sys.stdout`` for writable :class:`FileType` objects:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('infile', type=argparse.FileType('r')) + >>> parser.parse_args(['-']) + Namespace(infile=<_io.TextIOWrapper name='' encoding='UTF-8'>) + + .. versionadded:: 3.4 + The *encodings* and *errors* keyword arguments. + + +Argument groups +^^^^^^^^^^^^^^^ + +.. method:: ArgumentParser.add_argument_group(title=None, description=None) + + By default, :class:`ArgumentParser` groups command-line arguments into + "positional arguments" and "optional arguments" when displaying help + messages. When there is a better conceptual grouping of arguments than this + default one, appropriate groups can be created using the + :meth:`add_argument_group` method:: + + >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False) + >>> group = parser.add_argument_group('group') + >>> group.add_argument('--foo', help='foo help') + >>> group.add_argument('bar', help='bar help') + >>> parser.print_help() + usage: PROG [--foo FOO] bar + + group: + bar bar help + --foo FOO foo help + + The :meth:`add_argument_group` method returns an argument group object which + has an :meth:`~ArgumentParser.add_argument` method just like a regular + :class:`ArgumentParser`. When an argument is added to the group, the parser + treats it just like a normal argument, but displays the argument in a + separate group for help messages. The :meth:`add_argument_group` method + accepts *title* and *description* arguments which can be used to + customize this display:: + + >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False) + >>> group1 = parser.add_argument_group('group1', 'group1 description') + >>> group1.add_argument('foo', help='foo help') + >>> group2 = parser.add_argument_group('group2', 'group2 description') + >>> group2.add_argument('--bar', help='bar help') + >>> parser.print_help() + usage: PROG [--bar BAR] foo + + group1: + group1 description + + foo foo help + + group2: + group2 description + + --bar BAR bar help + + Note that any arguments not in your user-defined groups will end up back + in the usual "positional arguments" and "optional arguments" sections. + + +Mutual exclusion +^^^^^^^^^^^^^^^^ + +.. method:: ArgumentParser.add_mutually_exclusive_group(required=False) + + Create a mutually exclusive group. :mod:`argparse` will make sure that only + one of the arguments in the mutually exclusive group was present on the + command line:: + + >>> parser = argparse.ArgumentParser(prog='PROG') + >>> group = parser.add_mutually_exclusive_group() + >>> group.add_argument('--foo', action='store_true') + >>> group.add_argument('--bar', action='store_false') + >>> parser.parse_args(['--foo']) + Namespace(bar=True, foo=True) + >>> parser.parse_args(['--bar']) + Namespace(bar=False, foo=False) + >>> parser.parse_args(['--foo', '--bar']) + usage: PROG [-h] [--foo | --bar] + PROG: error: argument --bar: not allowed with argument --foo + + The :meth:`add_mutually_exclusive_group` method also accepts a *required* + argument, to indicate that at least one of the mutually exclusive arguments + is required:: + + >>> parser = argparse.ArgumentParser(prog='PROG') + >>> group = parser.add_mutually_exclusive_group(required=True) + >>> group.add_argument('--foo', action='store_true') + >>> group.add_argument('--bar', action='store_false') + >>> parser.parse_args([]) + usage: PROG [-h] (--foo | --bar) + PROG: error: one of the arguments --foo --bar is required + + Note that currently mutually exclusive argument groups do not support the + *title* and *description* arguments of + :meth:`~ArgumentParser.add_argument_group`. + + +Parser defaults +^^^^^^^^^^^^^^^ + +.. method:: ArgumentParser.set_defaults(**kwargs) + + Most of the time, the attributes of the object returned by :meth:`parse_args` + will be fully determined by inspecting the command-line arguments and the argument + actions. :meth:`set_defaults` allows some additional + attributes that are determined without any inspection of the command line to + be added:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('foo', type=int) + >>> parser.set_defaults(bar=42, baz='badger') + >>> parser.parse_args(['736']) + Namespace(bar=42, baz='badger', foo=736) + + Note that parser-level defaults always override argument-level defaults:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('--foo', default='bar') + >>> parser.set_defaults(foo='spam') + >>> parser.parse_args([]) + Namespace(foo='spam') + + Parser-level defaults can be particularly useful when working with multiple + parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an + example of this type. + +.. method:: ArgumentParser.get_default(dest) + + Get the default value for a namespace attribute, as set by either + :meth:`~ArgumentParser.add_argument` or by + :meth:`~ArgumentParser.set_defaults`:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('--foo', default='badger') + >>> parser.get_default('foo') + 'badger' + + +Printing help +^^^^^^^^^^^^^ + +In most typical applications, :meth:`~ArgumentParser.parse_args` will take +care of formatting and printing any usage or error messages. However, several +formatting methods are available: + +.. method:: ArgumentParser.print_usage(file=None) + + Print a brief description of how the :class:`ArgumentParser` should be + invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is + assumed. + +.. method:: ArgumentParser.print_help(file=None) + + Print a help message, including the program usage and information about the + arguments registered with the :class:`ArgumentParser`. If *file* is + ``None``, :data:`sys.stdout` is assumed. + +There are also variants of these methods that simply return a string instead of +printing it: + +.. method:: ArgumentParser.format_usage() + + Return a string containing a brief description of how the + :class:`ArgumentParser` should be invoked on the command line. + +.. method:: ArgumentParser.format_help() + + Return a string containing a help message, including the program usage and + information about the arguments registered with the :class:`ArgumentParser`. + + +Partial parsing +^^^^^^^^^^^^^^^ + +.. method:: ArgumentParser.parse_known_args(args=None, namespace=None) + +Sometimes a script may only parse a few of the command-line arguments, passing +the remaining arguments on to another script or program. In these cases, the +:meth:`~ArgumentParser.parse_known_args` method can be useful. It works much like +:meth:`~ArgumentParser.parse_args` except that it does not produce an error when +extra arguments are present. Instead, it returns a two item tuple containing +the populated namespace and the list of remaining argument strings. + +:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('--foo', action='store_true') + >>> parser.add_argument('bar') + >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam']) + (Namespace(bar='BAR', foo=True), ['--badger', 'spam']) + +.. warning:: + :ref:`Prefix matching ` rules apply to + :meth:`parse_known_args`. The parser may consume an option even if it's just + a prefix of one of its known options, instead of leaving it in the remaining + arguments list. + + +Customizing file parsing +^^^^^^^^^^^^^^^^^^^^^^^^ + +.. method:: ArgumentParser.convert_arg_line_to_args(arg_line) + + Arguments that are read from a file (see the *fromfile_prefix_chars* + keyword argument to the :class:`ArgumentParser` constructor) are read one + argument per line. :meth:`convert_arg_line_to_args` can be overridden for + fancier reading. + + This method takes a single argument *arg_line* which is a string read from + the argument file. It returns a list of arguments parsed from this string. + The method is called once per line read from the argument file, in order. + + A useful override of this method is one that treats each space-separated word + as an argument. The following example demonstrates how to do this:: + + class MyArgumentParser(argparse.ArgumentParser): + def convert_arg_line_to_args(self, arg_line): + return arg_line.split() + + +Exiting methods +^^^^^^^^^^^^^^^ + +.. method:: ArgumentParser.exit(status=0, message=None) + + This method terminates the program, exiting with the specified *status* + and, if given, it prints a *message* before that. The user can override + this method to handle these steps differently:: + + class ErrorCatchingArgumentParser(argparse.ArgumentParser): + def exit(self, status=0, message=None): + if status: + raise Exception(f'Exiting because of an error: {message}') + exit(status) + +.. method:: ArgumentParser.error(message) + + This method prints a usage message including the *message* to the + standard error and terminates the program with a status code of 2. + + +Intermixed parsing +^^^^^^^^^^^^^^^^^^ + +.. method:: ArgumentParser.parse_intermixed_args(args=None, namespace=None) +.. method:: ArgumentParser.parse_known_intermixed_args(args=None, namespace=None) + +A number of Unix commands allow the user to intermix optional arguments with +positional arguments. The :meth:`~ArgumentParser.parse_intermixed_args` +and :meth:`~ArgumentParser.parse_known_intermixed_args` methods +support this parsing style. + +These parsers do not support all the argparse features, and will raise +exceptions if unsupported features are used. In particular, subparsers, +``argparse.REMAINDER``, and mutually exclusive groups that include both +optionals and positionals are not supported. + +The following example shows the difference between +:meth:`~ArgumentParser.parse_known_args` and +:meth:`~ArgumentParser.parse_intermixed_args`: the former returns ``['2', +'3']`` as unparsed arguments, while the latter collects all the positionals +into ``rest``. :: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('--foo') + >>> parser.add_argument('cmd') + >>> parser.add_argument('rest', nargs='*', type=int) + >>> parser.parse_known_args('doit 1 --foo bar 2 3'.split()) + (Namespace(cmd='doit', foo='bar', rest=[1]), ['2', '3']) + >>> parser.parse_intermixed_args('doit 1 --foo bar 2 3'.split()) + Namespace(cmd='doit', foo='bar', rest=[1, 2, 3]) + +:meth:`~ArgumentParser.parse_known_intermixed_args` returns a two item tuple +containing the populated namespace and the list of remaining argument strings. +:meth:`~ArgumentParser.parse_intermixed_args` raises an error if there are any +remaining unparsed argument strings. + +.. versionadded:: 3.7 + +.. _upgrading-optparse-code: + +Upgrading optparse code +----------------------- + +Originally, the :mod:`argparse` module had attempted to maintain compatibility +with :mod:`optparse`. However, :mod:`optparse` was difficult to extend +transparently, particularly with the changes required to support the new +``nargs=`` specifiers and better usage messages. When most everything in +:mod:`optparse` had either been copy-pasted over or monkey-patched, it no +longer seemed practical to try to maintain the backwards compatibility. + +The :mod:`argparse` module improves on the standard library :mod:`optparse` +module in a number of ways including: + +* Handling positional arguments. +* Supporting sub-commands. +* Allowing alternative option prefixes like ``+`` and ``/``. +* Handling zero-or-more and one-or-more style arguments. +* Producing more informative usage messages. +* Providing a much simpler interface for custom ``type`` and ``action``. + +A partial upgrade path from :mod:`optparse` to :mod:`argparse`: + +* Replace all :meth:`optparse.OptionParser.add_option` calls with + :meth:`ArgumentParser.add_argument` calls. + +* Replace ``(options, args) = parser.parse_args()`` with ``args = + parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument` + calls for the positional arguments. Keep in mind that what was previously + called ``options``, now in the :mod:`argparse` context is called ``args``. + +* Replace :meth:`optparse.OptionParser.disable_interspersed_args` + by using :meth:`~ArgumentParser.parse_intermixed_args` instead of + :meth:`~ArgumentParser.parse_args`. + +* Replace callback actions and the ``callback_*`` keyword arguments with + ``type`` or ``action`` arguments. + +* Replace string names for ``type`` keyword arguments with the corresponding + type objects (e.g. int, float, complex, etc). + +* Replace :class:`optparse.Values` with :class:`Namespace` and + :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with + :exc:`ArgumentError`. + +* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with + the standard Python syntax to use dictionaries to format strings, that is, + ``%(default)s`` and ``%(prog)s``. + +* Replace the OptionParser constructor ``version`` argument with a call to + ``parser.add_argument('--version', action='version', version='')``. diff --git a/cpython_2/environment/repo/Doc/library/array.rst b/cpython_2/environment/repo/Doc/library/array.rst new file mode 100644 index 0000000000000000000000000000000000000000..78020738bf4f75b1206ec89e3a8c3130d00d7f34 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/array.rst @@ -0,0 +1,263 @@ +:mod:`array` --- Efficient arrays of numeric values +=================================================== + +.. module:: array + :synopsis: Space efficient arrays of uniformly typed numeric values. + +.. index:: single: arrays + +-------------- + +This module defines an object type which can compactly represent an array of +basic values: characters, integers, floating point numbers. Arrays are sequence +types and behave very much like lists, except that the type of objects stored in +them is constrained. The type is specified at object creation time by using a +:dfn:`type code`, which is a single character. The following type codes are +defined: + ++-----------+--------------------+-------------------+-----------------------+-------+ +| Type code | C Type | Python Type | Minimum size in bytes | Notes | ++===========+====================+===================+=======================+=======+ +| ``'b'`` | signed char | int | 1 | | ++-----------+--------------------+-------------------+-----------------------+-------+ +| ``'B'`` | unsigned char | int | 1 | | ++-----------+--------------------+-------------------+-----------------------+-------+ +| ``'u'`` | wchar_t | Unicode character | 2 | \(1) | ++-----------+--------------------+-------------------+-----------------------+-------+ +| ``'h'`` | signed short | int | 2 | | ++-----------+--------------------+-------------------+-----------------------+-------+ +| ``'H'`` | unsigned short | int | 2 | | ++-----------+--------------------+-------------------+-----------------------+-------+ +| ``'i'`` | signed int | int | 2 | | ++-----------+--------------------+-------------------+-----------------------+-------+ +| ``'I'`` | unsigned int | int | 2 | | ++-----------+--------------------+-------------------+-----------------------+-------+ +| ``'l'`` | signed long | int | 4 | | ++-----------+--------------------+-------------------+-----------------------+-------+ +| ``'L'`` | unsigned long | int | 4 | | ++-----------+--------------------+-------------------+-----------------------+-------+ +| ``'q'`` | signed long long | int | 8 | | ++-----------+--------------------+-------------------+-----------------------+-------+ +| ``'Q'`` | unsigned long long | int | 8 | | ++-----------+--------------------+-------------------+-----------------------+-------+ +| ``'f'`` | float | float | 4 | | ++-----------+--------------------+-------------------+-----------------------+-------+ +| ``'d'`` | double | float | 8 | | ++-----------+--------------------+-------------------+-----------------------+-------+ + +Notes: + +(1) + It can be 16 bits or 32 bits depending on the platform. + + .. versionchanged:: 3.9 + ``array('u')`` now uses ``wchar_t`` as C type instead of deprecated + ``Py_UNICODE``. This change doesn't affect to its behavior because + ``Py_UNICODE`` is alias of ``wchar_t`` since Python 3.3. + + .. deprecated-removed:: 3.3 4.0 + + +The actual representation of values is determined by the machine architecture +(strictly speaking, by the C implementation). The actual size can be accessed +through the :attr:`itemsize` attribute. + +The module defines the following type: + + +.. class:: array(typecode[, initializer]) + + A new array whose items are restricted by *typecode*, and initialized + from the optional *initializer* value, which must be a list, a + :term:`bytes-like object`, or iterable over elements of the + appropriate type. + + If given a list or string, the initializer is passed to the new array's + :meth:`fromlist`, :meth:`frombytes`, or :meth:`fromunicode` method (see below) + to add initial items to the array. Otherwise, the iterable initializer is + passed to the :meth:`extend` method. + + .. audit-event:: array.__new__ typecode,initializer array.array + +.. data:: typecodes + + A string with all available type codes. + +Array objects support the ordinary sequence operations of indexing, slicing, +concatenation, and multiplication. When using slice assignment, the assigned +value must be an array object with the same type code; in all other cases, +:exc:`TypeError` is raised. Array objects also implement the buffer interface, +and may be used wherever :term:`bytes-like objects ` are supported. + +The following data items and methods are also supported: + +.. attribute:: array.typecode + + The typecode character used to create the array. + + +.. attribute:: array.itemsize + + The length in bytes of one array item in the internal representation. + + +.. method:: array.append(x) + + Append a new item with value *x* to the end of the array. + + +.. method:: array.buffer_info() + + Return a tuple ``(address, length)`` giving the current memory address and the + length in elements of the buffer used to hold array's contents. The size of the + memory buffer in bytes can be computed as ``array.buffer_info()[1] * + array.itemsize``. This is occasionally useful when working with low-level (and + inherently unsafe) I/O interfaces that require memory addresses, such as certain + :c:func:`ioctl` operations. The returned numbers are valid as long as the array + exists and no length-changing operations are applied to it. + + .. note:: + + When using array objects from code written in C or C++ (the only way to + effectively make use of this information), it makes more sense to use the buffer + interface supported by array objects. This method is maintained for backward + compatibility and should be avoided in new code. The buffer interface is + documented in :ref:`bufferobjects`. + + +.. method:: array.byteswap() + + "Byteswap" all items of the array. This is only supported for values which are + 1, 2, 4, or 8 bytes in size; for other types of values, :exc:`RuntimeError` is + raised. It is useful when reading data from a file written on a machine with a + different byte order. + + +.. method:: array.count(x) + + Return the number of occurrences of *x* in the array. + + +.. method:: array.extend(iterable) + + Append items from *iterable* to the end of the array. If *iterable* is another + array, it must have *exactly* the same type code; if not, :exc:`TypeError` will + be raised. If *iterable* is not an array, it must be iterable and its elements + must be the right type to be appended to the array. + + +.. method:: array.frombytes(s) + + Appends items from the string, interpreting the string as an array of machine + values (as if it had been read from a file using the :meth:`fromfile` method). + + .. versionadded:: 3.2 + :meth:`fromstring` is renamed to :meth:`frombytes` for clarity. + + +.. method:: array.fromfile(f, n) + + Read *n* items (as machine values) from the :term:`file object` *f* and append + them to the end of the array. If less than *n* items are available, + :exc:`EOFError` is raised, but the items that were available are still + inserted into the array. *f* must be a real built-in file object; something + else with a :meth:`read` method won't do. + + +.. method:: array.fromlist(list) + + Append items from the list. This is equivalent to ``for x in list: + a.append(x)`` except that if there is a type error, the array is unchanged. + + +.. method:: array.fromunicode(s) + + Extends this array with data from the given unicode string. The array must + be a type ``'u'`` array; otherwise a :exc:`ValueError` is raised. Use + ``array.frombytes(unicodestring.encode(enc))`` to append Unicode data to an + array of some other type. + + +.. method:: array.index(x) + + Return the smallest *i* such that *i* is the index of the first occurrence of + *x* in the array. + + +.. method:: array.insert(i, x) + + Insert a new item with value *x* in the array before position *i*. Negative + values are treated as being relative to the end of the array. + + +.. method:: array.pop([i]) + + Removes the item with the index *i* from the array and returns it. The optional + argument defaults to ``-1``, so that by default the last item is removed and + returned. + + +.. method:: array.remove(x) + + Remove the first occurrence of *x* from the array. + + +.. method:: array.reverse() + + Reverse the order of the items in the array. + + +.. method:: array.tobytes() + + Convert the array to an array of machine values and return the bytes + representation (the same sequence of bytes that would be written to a file by + the :meth:`tofile` method.) + + .. versionadded:: 3.2 + :meth:`tostring` is renamed to :meth:`tobytes` for clarity. + + +.. method:: array.tofile(f) + + Write all items (as machine values) to the :term:`file object` *f*. + + +.. method:: array.tolist() + + Convert the array to an ordinary list with the same items. + + +.. method:: array.tounicode() + + Convert the array to a unicode string. The array must be a type ``'u'`` array; + otherwise a :exc:`ValueError` is raised. Use ``array.tobytes().decode(enc)`` to + obtain a unicode string from an array of some other type. + + +When an array object is printed or converted to a string, it is represented as +``array(typecode, initializer)``. The *initializer* is omitted if the array is +empty, otherwise it is a string if the *typecode* is ``'u'``, otherwise it is a +list of numbers. The string is guaranteed to be able to be converted back to an +array with the same type and value using :func:`eval`, so long as the +:class:`~array.array` class has been imported using ``from array import array``. +Examples:: + + array('l') + array('u', 'hello \u2641') + array('l', [1, 2, 3, 4, 5]) + array('d', [1.0, 2.0, 3.14]) + + +.. seealso:: + + Module :mod:`struct` + Packing and unpacking of heterogeneous binary data. + + Module :mod:`xdrlib` + Packing and unpacking of External Data Representation (XDR) data as used in some + remote procedure call systems. + + `The Numerical Python Documentation `_ + The Numeric Python extension (NumPy) defines another array type; see + http://www.numpy.org/ for further information about Numerical Python. + diff --git a/cpython_2/environment/repo/Doc/library/ast.rst b/cpython_2/environment/repo/Doc/library/ast.rst new file mode 100644 index 0000000000000000000000000000000000000000..6c6ad01b842c8ea9d271153ec903c174dfe051ba --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/ast.rst @@ -0,0 +1,1799 @@ +:mod:`ast` --- Abstract Syntax Trees +==================================== + +.. module:: ast + :synopsis: Abstract Syntax Tree classes and manipulation. + +.. sectionauthor:: Martin v. Löwis +.. sectionauthor:: Georg Brandl + +.. testsetup:: + + import ast + +**Source code:** :source:`Lib/ast.py` + +-------------- + +The :mod:`ast` module helps Python applications to process trees of the Python +abstract syntax grammar. The abstract syntax itself might change with each +Python release; this module helps to find out programmatically what the current +grammar looks like. + +An abstract syntax tree can be generated by passing :data:`ast.PyCF_ONLY_AST` as +a flag to the :func:`compile` built-in function, or using the :func:`parse` +helper provided in this module. The result will be a tree of objects whose +classes all inherit from :class:`ast.AST`. An abstract syntax tree can be +compiled into a Python code object using the built-in :func:`compile` function. + + +.. _abstract-grammar: + +Abstract Grammar +---------------- + +The abstract grammar is currently defined as follows: + +.. literalinclude:: ../../Parser/Python.asdl + :language: asdl + + +Node classes +------------ + +.. class:: AST + + This is the base of all AST node classes. The actual node classes are + derived from the :file:`Parser/Python.asdl` file, which is reproduced + :ref:`below `. They are defined in the :mod:`_ast` C + module and re-exported in :mod:`ast`. + + There is one class defined for each left-hand side symbol in the abstract + grammar (for example, :class:`ast.stmt` or :class:`ast.expr`). In addition, + there is one class defined for each constructor on the right-hand side; these + classes inherit from the classes for the left-hand side trees. For example, + :class:`ast.BinOp` inherits from :class:`ast.expr`. For production rules + with alternatives (aka "sums"), the left-hand side class is abstract: only + instances of specific constructor nodes are ever created. + + .. index:: single: ? (question mark); in AST grammar + .. index:: single: * (asterisk); in AST grammar + + .. attribute:: _fields + + Each concrete class has an attribute :attr:`_fields` which gives the names + of all child nodes. + + Each instance of a concrete class has one attribute for each child node, + of the type as defined in the grammar. For example, :class:`ast.BinOp` + instances have an attribute :attr:`left` of type :class:`ast.expr`. + + If these attributes are marked as optional in the grammar (using a + question mark), the value might be ``None``. If the attributes can have + zero-or-more values (marked with an asterisk), the values are represented + as Python lists. All possible attributes must be present and have valid + values when compiling an AST with :func:`compile`. + + .. attribute:: lineno + col_offset + end_lineno + end_col_offset + + Instances of :class:`ast.expr` and :class:`ast.stmt` subclasses have + :attr:`lineno`, :attr:`col_offset`, :attr:`lineno`, and :attr:`col_offset` + attributes. The :attr:`lineno` and :attr:`end_lineno` are the first and + last line numbers of source text span (1-indexed so the first line is line 1) + and the :attr:`col_offset` and :attr:`end_col_offset` are the corresponding + UTF-8 byte offsets of the first and last tokens that generated the node. + The UTF-8 offset is recorded because the parser uses UTF-8 internally. + + Note that the end positions are not required by the compiler and are + therefore optional. The end offset is *after* the last symbol, for example + one can get the source segment of a one-line expression node using + ``source_line[node.col_offset : node.end_col_offset]``. + + The constructor of a class :class:`ast.T` parses its arguments as follows: + + * If there are positional arguments, there must be as many as there are items + in :attr:`T._fields`; they will be assigned as attributes of these names. + * If there are keyword arguments, they will set the attributes of the same + names to the given values. + + For example, to create and populate an :class:`ast.UnaryOp` node, you could + use :: + + node = ast.UnaryOp() + node.op = ast.USub() + node.operand = ast.Constant() + node.operand.value = 5 + node.operand.lineno = 0 + node.operand.col_offset = 0 + node.lineno = 0 + node.col_offset = 0 + + or the more compact :: + + node = ast.UnaryOp(ast.USub(), ast.Constant(5, lineno=0, col_offset=0), + lineno=0, col_offset=0) + +.. versionchanged:: 3.8 + + Class :class:`ast.Constant` is now used for all constants. + +.. versionchanged:: 3.9 + + Simple indices are represented by their value, extended slices are + represented as tuples. + +.. deprecated:: 3.8 + + Old classes :class:`ast.Num`, :class:`ast.Str`, :class:`ast.Bytes`, + :class:`ast.NameConstant` and :class:`ast.Ellipsis` are still available, + but they will be removed in future Python releases. In the meantime, + instantiating them will return an instance of a different class. + +.. deprecated:: 3.9 + + Old classes :class:`ast.Index` and :class:`ast.ExtSlice` are still + available, but they will be removed in future Python releases. + In the meantime, instantiating them will return an instance of + a different class. + + +Literals +^^^^^^^^ + +.. class:: Constant(value) + + A constant value. The ``value`` attribute of the ``Constant`` literal contains the + Python object it represents. The values represented can be simple types + such as a number, string or ``None``, but also immutable container types + (tuples and frozensets) if all of their elements are constant. + + .. doctest:: + + >>> print(ast.dump(ast.parse('123', mode='eval'), indent=4)) + Expression( + body=Constant(value=123)) + + +.. class:: FormattedValue(value, conversion, format_spec) + + Node representing a single formatting field in an f-string. If the string + contains a single formatting field and nothing else the node can be + isolated otherwise it appears in :class:`JoinedStr`. + + * ``value`` is any expression node (such as a literal, a variable, or a + function call). + * ``conversion`` is an integer: + + * -1: no formatting + * 115: ``!s`` string formatting + * 114: ``!r`` repr formatting + * 97: ``!a`` ascii formatting + + * ``format_spec`` is a :class:`JoinedStr` node representing the formatting + of the value, or ``None`` if no format was specified. Both + ``conversion`` and ``format_spec`` can be set at the same time. + + +.. class:: JoinedStr(values) + + An f-string, comprising a series of :class:`FormattedValue` and :class:`Constant` + nodes. + + .. doctest:: + + >>> print(ast.dump(ast.parse('f"sin({a}) is {sin(a):.3}"', mode='eval'), indent=4)) + Expression( + body=JoinedStr( + values=[ + Constant(value='sin('), + FormattedValue( + value=Name(id='a', ctx=Load()), + conversion=-1), + Constant(value=') is '), + FormattedValue( + value=Call( + func=Name(id='sin', ctx=Load()), + args=[ + Name(id='a', ctx=Load())], + keywords=[]), + conversion=-1, + format_spec=JoinedStr( + values=[ + Constant(value='.3')]))])) + + +.. class:: List(elts, ctx) + Tuple(elts, ctx) + + A list or tuple. ``elts`` holds a list of nodes representing the elements. + ``ctx`` is :class:`Store` if the container is an assignment target (i.e. + ``(x,y)=something``), and :class:`Load` otherwise. + + .. doctest:: + + >>> print(ast.dump(ast.parse('[1, 2, 3]', mode='eval'), indent=4)) + Expression( + body=List( + elts=[ + Constant(value=1), + Constant(value=2), + Constant(value=3)], + ctx=Load())) + >>> print(ast.dump(ast.parse('(1, 2, 3)', mode='eval'), indent=4)) + Expression( + body=Tuple( + elts=[ + Constant(value=1), + Constant(value=2), + Constant(value=3)], + ctx=Load())) + + +.. class:: Set(elts) + + A set. ``elts`` holds a list of nodes representing the set's elements. + + .. doctest:: + + >>> print(ast.dump(ast.parse('{1, 2, 3}', mode='eval'), indent=4)) + Expression( + body=Set( + elts=[ + Constant(value=1), + Constant(value=2), + Constant(value=3)])) + + +.. class:: Dict(keys, values) + + A dictionary. ``keys`` and ``values`` hold lists of nodes representing the + keys and the values respectively, in matching order (what would be returned + when calling :code:`dictionary.keys()` and :code:`dictionary.values()`). + + When doing dictionary unpacking using dictionary literals the expression to be + expanded goes in the ``values`` list, with a ``None`` at the corresponding + position in ``keys``. + + .. doctest:: + + >>> print(ast.dump(ast.parse('{"a":1, **d}', mode='eval'), indent=4)) + Expression( + body=Dict( + keys=[ + Constant(value='a'), + None], + values=[ + Constant(value=1), + Name(id='d', ctx=Load())])) + + +Variables +^^^^^^^^^ + +.. class:: Name(id, ctx) + + A variable name. ``id`` holds the name as a string, and ``ctx`` is one of + the following types. + + +.. class:: Load() + Store() + Del() + + Variable references can be used to load the value of a variable, to assign + a new value to it, or to delete it. Variable references are given a context + to distinguish these cases. + + .. doctest:: + + >>> print(ast.dump(ast.parse('a'), indent=4)) + Module( + body=[ + Expr( + value=Name(id='a', ctx=Load()))], + type_ignores=[]) + + >>> print(ast.dump(ast.parse('a = 1'), indent=4)) + Module( + body=[ + Assign( + targets=[ + Name(id='a', ctx=Store())], + value=Constant(value=1))], + type_ignores=[]) + + >>> print(ast.dump(ast.parse('del a'), indent=4)) + Module( + body=[ + Delete( + targets=[ + Name(id='a', ctx=Del())])], + type_ignores=[]) + + +.. class:: Starred(value, ctx) + + A ``*var`` variable reference. ``value`` holds the variable, typically a + :class:`Name` node. This type must be used when building a :class:`Call` + node with ``*args``. + + .. doctest:: + + >>> print(ast.dump(ast.parse('a, *b = it'), indent=4)) + Module( + body=[ + Assign( + targets=[ + Tuple( + elts=[ + Name(id='a', ctx=Store()), + Starred( + value=Name(id='b', ctx=Store()), + ctx=Store())], + ctx=Store())], + value=Name(id='it', ctx=Load()))], + type_ignores=[]) + + +Expressions +^^^^^^^^^^^ + +.. class:: Expr(value) + + When an expression, such as a function call, appears as a statement by itself + with its return value not used or stored, it is wrapped in this container. + ``value`` holds one of the other nodes in this section, a :class:`Constant`, a + :class:`Name`, a :class:`Lambda`, a :class:`Yield` or :class:`YieldFrom` node. + + .. doctest:: + + >>> print(ast.dump(ast.parse('-a'), indent=4)) + Module( + body=[ + Expr( + value=UnaryOp( + op=USub(), + operand=Name(id='a', ctx=Load())))], + type_ignores=[]) + + +.. class:: UnaryOp(op, operand) + + A unary operation. ``op`` is the operator, and ``operand`` any expression + node. + + +.. class:: UAdd + USub + Not + Invert + + Unary operator tokens. :class:`Not` is the ``not`` keyword, :class:`Invert` + is the ``~`` operator. + + .. doctest:: + + >>> print(ast.dump(ast.parse('not x', mode='eval'), indent=4)) + Expression( + body=UnaryOp( + op=Not(), + operand=Name(id='x', ctx=Load()))) + + +.. class:: BinOp(left, op, right) + + A binary operation (like addition or division). ``op`` is the operator, and + ``left`` and ``right`` are any expression nodes. + + .. doctest:: + + >>> print(ast.dump(ast.parse('x + y', mode='eval'), indent=4)) + Expression( + body=BinOp( + left=Name(id='x', ctx=Load()), + op=Add(), + right=Name(id='y', ctx=Load()))) + + +.. class:: Add + Sub + Mult + Div + FloorDiv + Mod + Pow + LShift + RShift + BitOr + BitXor + BitAnd + MatMult + + Binary operator tokens. + + +.. class:: BoolOp(op, values) + + A boolean operation, 'or' or 'and'. ``op`` is :class:`Or` or :class:`And`. + ``values`` are the values involved. Consecutive operations with the same + operator, such as ``a or b or c``, are collapsed into one node with several + values. + + This doesn't include ``not``, which is a :class:`UnaryOp`. + + .. doctest:: + + >>> print(ast.dump(ast.parse('x or y', mode='eval'), indent=4)) + Expression( + body=BoolOp( + op=Or(), + values=[ + Name(id='x', ctx=Load()), + Name(id='y', ctx=Load())])) + + +.. class:: And + Or + + Boolean operator tokens. + + +.. class:: Compare(left, ops, comparators) + + A comparison of two or more values. ``left`` is the first value in the + comparison, ``ops`` the list of operators, and ``comparators`` the list + of values after the first element in the comparison. + + .. doctest:: + + >>> print(ast.dump(ast.parse('1 <= a < 10', mode='eval'), indent=4)) + Expression( + body=Compare( + left=Constant(value=1), + ops=[ + LtE(), + Lt()], + comparators=[ + Name(id='a', ctx=Load()), + Constant(value=10)])) + + +.. class:: Eq + NotEq + Lt + LtE + Gt + GtE + Is + IsNot + In + NotIn + + Comparison operator tokens. + + +.. class:: Call(func, args, keywords, starargs, kwargs) + + A function call. ``func`` is the function, which will often be a + :class:`Name` or :class:`Attribute` object. Of the arguments: + + * ``args`` holds a list of the arguments passed by position. + * ``keywords`` holds a list of :class:`keyword` objects representing + arguments passed by keyword. + + When creating a ``Call`` node, ``args`` and ``keywords`` are required, but + they can be empty lists. ``starargs`` and ``kwargs`` are optional. + + .. doctest:: + + >>> print(ast.dump(ast.parse('func(a, b=c, *d, **e)', mode='eval'), indent=4)) + Expression( + body=Call( + func=Name(id='func', ctx=Load()), + args=[ + Name(id='a', ctx=Load()), + Starred( + value=Name(id='d', ctx=Load()), + ctx=Load())], + keywords=[ + keyword( + arg='b', + value=Name(id='c', ctx=Load())), + keyword( + value=Name(id='e', ctx=Load()))])) + + +.. class:: keyword(arg, value) + + A keyword argument to a function call or class definition. ``arg`` is a raw + string of the parameter name, ``value`` is a node to pass in. + + +.. class:: IfExp(test, body, orelse) + + An expression such as ``a if b else c``. Each field holds a single node, so + in the following example, all three are :class:`Name` nodes. + + .. doctest:: + + >>> print(ast.dump(ast.parse('a if b else c', mode='eval'), indent=4)) + Expression( + body=IfExp( + test=Name(id='b', ctx=Load()), + body=Name(id='a', ctx=Load()), + orelse=Name(id='c', ctx=Load()))) + + +.. class:: Attribute(value, attr, ctx) + + Attribute access, e.g. ``d.keys``. ``value`` is a node, typically a + :class:`Name`. ``attr`` is a bare string giving the name of the attribute, + and ``ctx`` is :class:`Load`, :class:`Store` or :class:`Del` according to how + the attribute is acted on. + + .. doctest:: + + >>> print(ast.dump(ast.parse('snake.colour', mode='eval'), indent=4)) + Expression( + body=Attribute( + value=Name(id='snake', ctx=Load()), + attr='colour', + ctx=Load())) + + +.. class:: NamedExpr(target, value) + + A named expression. This AST node is produced by the assignment expressions + operator (also known as the walrus operator). As opposed to the :class:`Assign` + node in which the first argument can be multiple nodes, in this case both + ``target`` and ``value`` must be single nodes. + + .. doctest:: + + >>> print(ast.dump(ast.parse('(x := 4)', mode='eval'), indent=4)) + Expression( + body=NamedExpr( + target=Name(id='x', ctx=Store()), + value=Constant(value=4))) + + +Subscripting +~~~~~~~~~~~~ + +.. class:: Subscript(value, slice, ctx) + + A subscript, such as ``l[1]``. ``value`` is the subscripted object + (usually sequence or mapping). ``slice`` is an index, slice or key. + It can be a :class:`Tuple` and contain a :class:`Slice`. + ``ctx`` is :class:`Load`, :class:`Store` or :class:`Del` + according to the action performed with the subscript. + + .. doctest:: + + >>> print(ast.dump(ast.parse('l[1:2, 3]', mode='eval'), indent=4)) + Expression( + body=Subscript( + value=Name(id='l', ctx=Load()), + slice=Tuple( + elts=[ + Slice( + lower=Constant(value=1), + upper=Constant(value=2)), + Constant(value=3)], + ctx=Load()), + ctx=Load())) + + +.. class:: Slice(lower, upper, step) + + Regular slicing (on the form ``lower:upper`` or ``lower:upper:step``). + Can occur only inside the *slice* field of :class:`Subscript`, either + directly or as an element of :class:`Tuple`. + + .. doctest:: + + >>> print(ast.dump(ast.parse('l[1:2]', mode='eval'), indent=4)) + Expression( + body=Subscript( + value=Name(id='l', ctx=Load()), + slice=Slice( + lower=Constant(value=1), + upper=Constant(value=2)), + ctx=Load())) + + +Comprehensions +~~~~~~~~~~~~~~ + +.. class:: ListComp(elt, generators) + SetComp(elt, generators) + GeneratorExp(elt, generators) + DictComp(key, value, generators) + + List and set comprehensions, generator expressions, and dictionary + comprehensions. ``elt`` (or ``key`` and ``value``) is a single node + representing the part that will be evaluated for each item. + + ``generators`` is a list of :class:`comprehension` nodes. + + .. doctest:: + + >>> print(ast.dump(ast.parse('[x for x in numbers]', mode='eval'), indent=4)) + Expression( + body=ListComp( + elt=Name(id='x', ctx=Load()), + generators=[ + comprehension( + target=Name(id='x', ctx=Store()), + iter=Name(id='numbers', ctx=Load()), + ifs=[], + is_async=0)])) + >>> print(ast.dump(ast.parse('{x: x**2 for x in numbers}', mode='eval'), indent=4)) + Expression( + body=DictComp( + key=Name(id='x', ctx=Load()), + value=BinOp( + left=Name(id='x', ctx=Load()), + op=Pow(), + right=Constant(value=2)), + generators=[ + comprehension( + target=Name(id='x', ctx=Store()), + iter=Name(id='numbers', ctx=Load()), + ifs=[], + is_async=0)])) + >>> print(ast.dump(ast.parse('{x for x in numbers}', mode='eval'), indent=4)) + Expression( + body=SetComp( + elt=Name(id='x', ctx=Load()), + generators=[ + comprehension( + target=Name(id='x', ctx=Store()), + iter=Name(id='numbers', ctx=Load()), + ifs=[], + is_async=0)])) + + +.. class:: comprehension(target, iter, ifs, is_async) + + One ``for`` clause in a comprehension. ``target`` is the reference to use for + each element - typically a :class:`Name` or :class:`Tuple` node. ``iter`` + is the object to iterate over. ``ifs`` is a list of test expressions: each + ``for`` clause can have multiple ``ifs``. + + ``is_async`` indicates a comprehension is asynchronous (using an + ``async for`` instead of ``for``). The value is an integer (0 or 1). + + .. doctest:: + + >>> print(ast.dump(ast.parse('[ord(c) for line in file for c in line]', mode='eval'), + ... indent=4)) # Multiple comprehensions in one. + Expression( + body=ListComp( + elt=Call( + func=Name(id='ord', ctx=Load()), + args=[ + Name(id='c', ctx=Load())], + keywords=[]), + generators=[ + comprehension( + target=Name(id='line', ctx=Store()), + iter=Name(id='file', ctx=Load()), + ifs=[], + is_async=0), + comprehension( + target=Name(id='c', ctx=Store()), + iter=Name(id='line', ctx=Load()), + ifs=[], + is_async=0)])) + + >>> print(ast.dump(ast.parse('(n**2 for n in it if n>5 if n<10)', mode='eval'), + ... indent=4)) # generator comprehension + Expression( + body=GeneratorExp( + elt=BinOp( + left=Name(id='n', ctx=Load()), + op=Pow(), + right=Constant(value=2)), + generators=[ + comprehension( + target=Name(id='n', ctx=Store()), + iter=Name(id='it', ctx=Load()), + ifs=[ + Compare( + left=Name(id='n', ctx=Load()), + ops=[ + Gt()], + comparators=[ + Constant(value=5)]), + Compare( + left=Name(id='n', ctx=Load()), + ops=[ + Lt()], + comparators=[ + Constant(value=10)])], + is_async=0)])) + + >>> print(ast.dump(ast.parse('[i async for i in soc]', mode='eval'), + ... indent=4)) # Async comprehension + Expression( + body=ListComp( + elt=Name(id='i', ctx=Load()), + generators=[ + comprehension( + target=Name(id='i', ctx=Store()), + iter=Name(id='soc', ctx=Load()), + ifs=[], + is_async=1)])) + +Statements +^^^^^^^^^^ + +.. class:: Assign(targets, value, type_comment) + + An assignment. ``targets`` is a list of nodes, and ``value`` is a single node. + + Multiple nodes in ``targets`` represents assigning the same value to each. + Unpacking is represented by putting a :class:`Tuple` or :class:`List` + within ``targets``. + + .. attribute:: type_comment + + ``type_comment`` is an optional string with the type annotation as a comment. + + .. doctest:: + + >>> print(ast.dump(ast.parse('a = b = 1'), indent=4)) # Multiple assignment + Module( + body=[ + Assign( + targets=[ + Name(id='a', ctx=Store()), + Name(id='b', ctx=Store())], + value=Constant(value=1))], + type_ignores=[]) + + >>> print(ast.dump(ast.parse('a,b = c'), indent=4)) # Unpacking + Module( + body=[ + Assign( + targets=[ + Tuple( + elts=[ + Name(id='a', ctx=Store()), + Name(id='b', ctx=Store())], + ctx=Store())], + value=Name(id='c', ctx=Load()))], + type_ignores=[]) + + +.. class:: AnnAssign(target, annotation, value, simple) + + An assignment with a type annotation. ``target`` is a single node and can + be a :class:`Name`, a :class:`Attribute` or a :class:`Subscript`. + ``annotation`` is the annotation, such as a :class:`Constant` or :class:`Name` + node. ``value`` is a single optional node. ``simple`` is a boolean integer + set to True for a :class:`Name` node in ``target`` that do not appear in + between parenthesis and are hence pure names and not expressions. + + .. doctest:: + + >>> print(ast.dump(ast.parse('c: int'), indent=4)) + Module( + body=[ + AnnAssign( + target=Name(id='c', ctx=Store()), + annotation=Name(id='int', ctx=Load()), + simple=1)], + type_ignores=[]) + + >>> print(ast.dump(ast.parse('(a): int = 1'), indent=4)) # Annotation with parenthesis + Module( + body=[ + AnnAssign( + target=Name(id='a', ctx=Store()), + annotation=Name(id='int', ctx=Load()), + value=Constant(value=1), + simple=0)], + type_ignores=[]) + + >>> print(ast.dump(ast.parse('a.b: int'), indent=4)) # Attribute annotation + Module( + body=[ + AnnAssign( + target=Attribute( + value=Name(id='a', ctx=Load()), + attr='b', + ctx=Store()), + annotation=Name(id='int', ctx=Load()), + simple=0)], + type_ignores=[]) + + >>> print(ast.dump(ast.parse('a[1]: int'), indent=4)) # Subscript annotation + Module( + body=[ + AnnAssign( + target=Subscript( + value=Name(id='a', ctx=Load()), + slice=Constant(value=1), + ctx=Store()), + annotation=Name(id='int', ctx=Load()), + simple=0)], + type_ignores=[]) + + +.. class:: AugAssign(target, op, value) + + Augmented assignment, such as ``a += 1``. In the following example, + ``target`` is a :class:`Name` node for ``x`` (with the :class:`Store` + context), ``op`` is :class:`Add`, and ``value`` is a :class:`Constant` with + value for 1. + + The ``target`` attribute connot be of class :class:`Tuple` or :class:`List`, + unlike the targets of :class:`Assign`. + + .. doctest:: + + >>> print(ast.dump(ast.parse('x += 2'), indent=4)) + Module( + body=[ + AugAssign( + target=Name(id='x', ctx=Store()), + op=Add(), + value=Constant(value=2))], + type_ignores=[]) + + +.. class:: Raise(exc, cause) + + A ``raise`` statement. ``exc`` is the exception object to be raised, normally a + :class:`Call` or :class:`Name`, or ``None`` for a standalone ``raise``. + ``cause`` is the optional part for ``y`` in ``raise x from y``. + + .. doctest:: + + >>> print(ast.dump(ast.parse('raise x from y'), indent=4)) + Module( + body=[ + Raise( + exc=Name(id='x', ctx=Load()), + cause=Name(id='y', ctx=Load()))], + type_ignores=[]) + + +.. class:: Assert(test, msg) + + An assertion. ``test`` holds the condition, such as a :class:`Compare` node. + ``msg`` holds the failure message. + + .. doctest:: + + >>> print(ast.dump(ast.parse('assert x,y'), indent=4)) + Module( + body=[ + Assert( + test=Name(id='x', ctx=Load()), + msg=Name(id='y', ctx=Load()))], + type_ignores=[]) + + +.. class:: Delete(targets) + + Represents a ``del`` statement. ``targets`` is a list of nodes, such as + :class:`Name`, :class:`Attribute` or :class:`Subscript` nodes. + + .. doctest:: + + >>> print(ast.dump(ast.parse('del x,y,z'), indent=4)) + Module( + body=[ + Delete( + targets=[ + Name(id='x', ctx=Del()), + Name(id='y', ctx=Del()), + Name(id='z', ctx=Del())])], + type_ignores=[]) + + +.. class:: Pass() + + A ``pass`` statement. + + .. doctest:: + + >>> print(ast.dump(ast.parse('pass'), indent=4)) + Module( + body=[ + Pass()], + type_ignores=[]) + + +Other statements which are only applicable inside functions or loops are +described in other sections. + +Imports +~~~~~~~ + +.. class:: Import(names) + + An import statement. ``names`` is a list of :class:`alias` nodes. + + .. doctest:: + + >>> print(ast.dump(ast.parse('import x,y,z'), indent=4)) + Module( + body=[ + Import( + names=[ + alias(name='x'), + alias(name='y'), + alias(name='z')])], + type_ignores=[]) + + +.. class:: ImportFrom(module, names, level) + + Represents ``from x import y``. ``module`` is a raw string of the 'from' name, + without any leading dots, or ``None`` for statements such as ``from . import foo``. + ``level`` is an integer holding the level of the relative import (0 means + absolute import). + + .. doctest:: + + >>> print(ast.dump(ast.parse('from y import x,y,z'), indent=4)) + Module( + body=[ + ImportFrom( + module='y', + names=[ + alias(name='x'), + alias(name='y'), + alias(name='z')], + level=0)], + type_ignores=[]) + + +.. class:: alias(name, asname) + + Both parameters are raw strings of the names. ``asname`` can be ``None`` if + the regular name is to be used. + + .. doctest:: + + >>> print(ast.dump(ast.parse('from ..foo.bar import a as b, c'), indent=4)) + Module( + body=[ + ImportFrom( + module='foo.bar', + names=[ + alias(name='a', asname='b'), + alias(name='c')], + level=2)], + type_ignores=[]) + +Control flow +^^^^^^^^^^^^ + +.. note:: + Optional clauses such as ``else`` are stored as an empty list if they're + not present. + +.. class:: If(test, body, orelse) + + An ``if`` statement. ``test`` holds a single node, such as a :class:`Compare` + node. ``body`` and ``orelse`` each hold a list of nodes. + + ``elif`` clauses don't have a special representation in the AST, but rather + appear as extra :class:`If` nodes within the ``orelse`` section of the + previous one. + + .. doctest:: + + >>> print(ast.dump(ast.parse(""" + ... if x: + ... ... + ... elif y: + ... ... + ... else: + ... ... + ... """), indent=4)) + Module( + body=[ + If( + test=Name(id='x', ctx=Load()), + body=[ + Expr( + value=Constant(value=Ellipsis))], + orelse=[ + If( + test=Name(id='y', ctx=Load()), + body=[ + Expr( + value=Constant(value=Ellipsis))], + orelse=[ + Expr( + value=Constant(value=Ellipsis))])])], + type_ignores=[]) + + +.. class:: For(target, iter, body, orelse, type_comment) + + A ``for`` loop. ``target`` holds the variable(s) the loop assigns to, as a + single :class:`Name`, :class:`Tuple` or :class:`List` node. ``iter`` holds + the item to be looped over, again as a single node. ``body`` and ``orelse`` + contain lists of nodes to execute. Those in ``orelse`` are executed if the + loop finishes normally, rather than via a ``break`` statement. + + .. attribute:: type_comment + + ``type_comment`` is an optional string with the type annotation as a comment. + + .. doctest:: + + >>> print(ast.dump(ast.parse(""" + ... for x in y: + ... ... + ... else: + ... ... + ... """), indent=4)) + Module( + body=[ + For( + target=Name(id='x', ctx=Store()), + iter=Name(id='y', ctx=Load()), + body=[ + Expr( + value=Constant(value=Ellipsis))], + orelse=[ + Expr( + value=Constant(value=Ellipsis))])], + type_ignores=[]) + + +.. class:: While(test, body, orelse) + + A ``while`` loop. ``test`` holds the condition, such as a :class:`Compare` + node. + + .. doctest:: + + >> print(ast.dump(ast.parse(""" + ... while x: + ... ... + ... else: + ... ... + ... """), indent=4)) + Module( + body=[ + While( + test=Name(id='x', ctx=Load()), + body=[ + Expr( + value=Constant(value=Ellipsis))], + orelse=[ + Expr( + value=Constant(value=Ellipsis))])], + type_ignores=[]) + + +.. class:: Break + Continue + + The ``break`` and ``continue`` statements. + + .. doctest:: + + >>> print(ast.dump(ast.parse("""\ + ... for a in b: + ... if a > 5: + ... break + ... else: + ... continue + ... + ... """), indent=4)) + Module( + body=[ + For( + target=Name(id='a', ctx=Store()), + iter=Name(id='b', ctx=Load()), + body=[ + If( + test=Compare( + left=Name(id='a', ctx=Load()), + ops=[ + Gt()], + comparators=[ + Constant(value=5)]), + body=[ + Break()], + orelse=[ + Continue()])], + orelse=[])], + type_ignores=[]) + + +.. class:: Try(body, handlers, orelse, finalbody) + + ``try`` blocks. All attributes are list of nodes to execute, except for + ``handlers``, which is a list of :class:`ExceptHandler` nodes. + + .. doctest:: + + >>> print(ast.dump(ast.parse(""" + ... try: + ... ... + ... except Exception: + ... ... + ... except OtherException as e: + ... ... + ... else: + ... ... + ... finally: + ... ... + ... """), indent=4)) + Module( + body=[ + Try( + body=[ + Expr( + value=Constant(value=Ellipsis))], + handlers=[ + ExceptHandler( + type=Name(id='Exception', ctx=Load()), + body=[ + Expr( + value=Constant(value=Ellipsis))]), + ExceptHandler( + type=Name(id='OtherException', ctx=Load()), + name='e', + body=[ + Expr( + value=Constant(value=Ellipsis))])], + orelse=[ + Expr( + value=Constant(value=Ellipsis))], + finalbody=[ + Expr( + value=Constant(value=Ellipsis))])], + type_ignores=[]) + + +.. class:: ExceptHandler(type, name, body) + + A single ``except`` clause. ``type`` is the exception type it will match, + typically a :class:`Name` node (or ``None`` for a catch-all ``except:`` clause). + ``name`` is a raw string for the name to hold the exception, or ``None`` if + the clause doesn't have ``as foo``. ``body`` is a list of nodes. + + .. doctest:: + + >>> print(ast.dump(ast.parse("""\ + ... try: + ... a + 1 + ... except TypeError: + ... pass + ... """), indent=4)) + Module( + body=[ + Try( + body=[ + Expr( + value=BinOp( + left=Name(id='a', ctx=Load()), + op=Add(), + right=Constant(value=1)))], + handlers=[ + ExceptHandler( + type=Name(id='TypeError', ctx=Load()), + body=[ + Pass()])], + orelse=[], + finalbody=[])], + type_ignores=[]) + + +.. class:: With(items, body, type_comment) + + A ``with`` block. ``items`` is a list of :class:`withitem` nodes representing + the context managers, and ``body`` is the indented block inside the context. + + .. attribute:: type_comment + + ``type_comment`` is an optional string with the type annotation as a comment. + + +.. class:: withitem(context_expr, optional_vars) + + A single context manager in a ``with`` block. ``context_expr`` is the context + manager, often a :class:`Call` node. ``optional_vars`` is a :class:`Name`, + :class:`Tuple` or :class:`List` for the ``as foo`` part, or ``None`` if that + isn't used. + + .. doctest:: + + >>> print(ast.dump(ast.parse("""\ + ... with a as b, c as d: + ... something(b, d) + ... """), indent=4)) + Module( + body=[ + With( + items=[ + withitem( + context_expr=Name(id='a', ctx=Load()), + optional_vars=Name(id='b', ctx=Store())), + withitem( + context_expr=Name(id='c', ctx=Load()), + optional_vars=Name(id='d', ctx=Store()))], + body=[ + Expr( + value=Call( + func=Name(id='something', ctx=Load()), + args=[ + Name(id='b', ctx=Load()), + Name(id='d', ctx=Load())], + keywords=[]))])], + type_ignores=[]) + + +Function and class definitions +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. class:: FunctionDef(name, args, body, decorator_list, returns, type_comment) + + A function definition. + + * ``name`` is a raw string of the function name. + * ``args`` is a :class:`arguments` node. + * ``body`` is the list of nodes inside the function. + * ``decorator_list`` is the list of decorators to be applied, stored outermost + first (i.e. the first in the list will be applied last). + * ``returns`` is the return annotation. + + .. attribute:: type_comment + + ``type_comment`` is an optional string with the type annotation as a comment. + + +.. class:: Lambda(args, body) + + ``lambda`` is a minimal function definition that can be used inside an + expression. Unlike :class:`FunctionDef`, ``body`` holds a single node. + + .. doctest:: + + >>> print(ast.dump(ast.parse('lambda x,y: ...'), indent=4)) + Module( + body=[ + Expr( + value=Lambda( + args=arguments( + posonlyargs=[], + args=[ + arg(arg='x'), + arg(arg='y')], + kwonlyargs=[], + kw_defaults=[], + defaults=[]), + body=Constant(value=Ellipsis)))], + type_ignores=[]) + + +.. class:: arguments(posonlyargs, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults) + + The arguments for a function. + + * ``posonlyargs``, ``args`` and ``kwonlyargs`` are lists of :class:`arg` nodes. + * ``vararg`` and ``kwarg`` are single :class:`arg` nodes, referring to the + ``*args, **kwargs`` parameters. + * ``kw_defaults`` is a list of default values for keyword-only arguments. If + one is ``None``, the corresponding argument is required. + * ``defaults`` is a list of default values for arguments that can be passed + positionally. If there are fewer defaults, they correspond to the last n + arguments. + + +.. class:: arg(arg, annotation, type_comment) + + A single argument in a list. ``arg`` is a raw string of the argument + name, ``annotation`` is its annotation, such as a :class:`Str` or + :class:`Name` node. + + .. attribute:: type_comment + + ``type_comment`` is an optional string with the type annotation as a comment + + .. doctest:: + + >>> print(ast.dump(ast.parse("""\ + ... @decorator1 + ... @decorator2 + ... def f(a: 'annotation', b=1, c=2, *d, e, f=3, **g) -> 'return annotation': + ... pass + ... """), indent=4)) + Module( + body=[ + FunctionDef( + name='f', + args=arguments( + posonlyargs=[], + args=[ + arg( + arg='a', + annotation=Constant(value='annotation')), + arg(arg='b'), + arg(arg='c')], + vararg=arg(arg='d'), + kwonlyargs=[ + arg(arg='e'), + arg(arg='f')], + kw_defaults=[ + None, + Constant(value=3)], + kwarg=arg(arg='g'), + defaults=[ + Constant(value=1), + Constant(value=2)]), + body=[ + Pass()], + decorator_list=[ + Name(id='decorator1', ctx=Load()), + Name(id='decorator2', ctx=Load())], + returns=Constant(value='return annotation'))], + type_ignores=[]) + + +.. class:: Return(value) + + A ``return`` statement. + + .. doctest:: + + >>> print(ast.dump(ast.parse('return 4'), indent=4)) + Module( + body=[ + Return( + value=Constant(value=4))], + type_ignores=[]) + + +.. class:: Yield(value) + YieldFrom(value) + + A ``yield`` or ``yield from`` expression. Because these are expressions, they + must be wrapped in a :class:`Expr` node if the value sent back is not used. + + .. doctest:: + + >>> print(ast.dump(ast.parse('yield x'), indent=4)) + Module( + body=[ + Expr( + value=Yield( + value=Name(id='x', ctx=Load())))], + type_ignores=[]) + + >>> print(ast.dump(ast.parse('yield from x'), indent=4)) + Module( + body=[ + Expr( + value=YieldFrom( + value=Name(id='x', ctx=Load())))], + type_ignores=[]) + + +.. class:: Global(names) + Nonlocal(names) + + ``global`` and ``nonlocal`` statements. ``names`` is a list of raw strings. + + .. doctest:: + + >>> print(ast.dump(ast.parse('global x,y,z'), indent=4)) + Module( + body=[ + Global( + names=[ + 'x', + 'y', + 'z'])], + type_ignores=[]) + + >>> print(ast.dump(ast.parse('nonlocal x,y,z'), indent=4)) + Module( + body=[ + Nonlocal( + names=[ + 'x', + 'y', + 'z'])], + type_ignores=[]) + + +.. class:: ClassDef(name, bases, keywords, starargs, kwargs, body, decorator_list) + + A class definition. + + * ``name`` is a raw string for the class name + * ``bases`` is a list of nodes for explicitly specified base classes. + * ``keywords`` is a list of :class:`keyword` nodes, principally for 'metaclass'. + Other keywords will be passed to the metaclass, as per `PEP-3115 + `_. + * ``starargs`` and ``kwargs`` are each a single node, as in a function call. + starargs will be expanded to join the list of base classes, and kwargs will + be passed to the metaclass. + * ``body`` is a list of nodes representing the code within the class + definition. + * ``decorator_list`` is a list of nodes, as in :class:`FunctionDef`. + + .. doctest:: + + >>> print(ast.dump(ast.parse("""\ + ... @decorator1 + ... @decorator2 + ... class Foo(base1, base2, metaclass=meta): + ... pass + ... """), indent=4)) + Module( + body=[ + ClassDef( + name='Foo', + bases=[ + Name(id='base1', ctx=Load()), + Name(id='base2', ctx=Load())], + keywords=[ + keyword( + arg='metaclass', + value=Name(id='meta', ctx=Load()))], + body=[ + Pass()], + decorator_list=[ + Name(id='decorator1', ctx=Load()), + Name(id='decorator2', ctx=Load())])], + type_ignores=[]) + +Async and await +^^^^^^^^^^^^^^^ + +.. class:: AsyncFunctionDef(name, args, body, decorator_list, returns, type_comment) + + An ``async def`` function definition. Has the same fields as + :class:`FunctionDef`. + + +.. class:: Await(value) + + An ``await`` expression. ``value`` is what it waits for. + Only valid in the body of an :class:`AsyncFunctionDef`. + +.. doctest:: + + >>> print(ast.dump(ast.parse("""\ + ... async def f(): + ... await other_func() + ... """), indent=4)) + Module( + body=[ + AsyncFunctionDef( + name='f', + args=arguments( + posonlyargs=[], + args=[], + kwonlyargs=[], + kw_defaults=[], + defaults=[]), + body=[ + Expr( + value=Await( + value=Call( + func=Name(id='other_func', ctx=Load()), + args=[], + keywords=[])))], + decorator_list=[])], + type_ignores=[]) + + +.. class:: AsyncFor(target, iter, body, orelse, type_comment) + AsyncWith(items, body, type_comment) + + ``async for`` loops and ``async with`` context managers. They have the same + fields as :class:`For` and :class:`With`, respectively. Only valid in the + body of an :class:`AsyncFunctionDef`. + + +:mod:`ast` Helpers +------------------ + +Apart from the node classes, the :mod:`ast` module defines these utility functions +and classes for traversing abstract syntax trees: + +.. function:: parse(source, filename='', mode='exec', *, type_comments=False, feature_version=None) + + Parse the source into an AST node. Equivalent to ``compile(source, + filename, mode, ast.PyCF_ONLY_AST)``. + + If ``type_comments=True`` is given, the parser is modified to check + and return type comments as specified by :pep:`484` and :pep:`526`. + This is equivalent to adding :data:`ast.PyCF_TYPE_COMMENTS` to the + flags passed to :func:`compile()`. This will report syntax errors + for misplaced type comments. Without this flag, type comments will + be ignored, and the ``type_comment`` field on selected AST nodes + will always be ``None``. In addition, the locations of ``# type: + ignore`` comments will be returned as the ``type_ignores`` + attribute of :class:`Module` (otherwise it is always an empty list). + + In addition, if ``mode`` is ``'func_type'``, the input syntax is + modified to correspond to :pep:`484` "signature type comments", + e.g. ``(str, int) -> List[str]``. + + Also, setting ``feature_version`` to a tuple ``(major, minor)`` + will attempt to parse using that Python version's grammar. + Currently ``major`` must equal to ``3``. For example, setting + ``feature_version=(3, 4)`` will allow the use of ``async`` and + ``await`` as variable names. The lowest supported version is + ``(3, 4)``; the highest is ``sys.version_info[0:2]``. + + .. warning:: + It is possible to crash the Python interpreter with a + sufficiently large/complex string due to stack depth limitations + in Python's AST compiler. + + .. versionchanged:: 3.8 + Added ``type_comments``, ``mode='func_type'`` and ``feature_version``. + + +.. function:: unparse(ast_obj) + + Unparse an :class:`ast.AST` object and generate a string with code + that would produce an equivalent :class:`ast.AST` object if parsed + back with :func:`ast.parse`. + + .. warning:: + The produced code string will not necessarily be equal to the original + code that generated the :class:`ast.AST` object. + + .. versionadded:: 3.9 + + +.. function:: literal_eval(node_or_string) + + Safely evaluate an expression node or a string containing a Python literal or + container display. The string or node provided may only consist of the + following Python literal structures: strings, bytes, numbers, tuples, lists, + dicts, sets, booleans, and ``None``. + + This can be used for safely evaluating strings containing Python values from + untrusted sources without the need to parse the values oneself. It is not + capable of evaluating arbitrarily complex expressions, for example involving + operators or indexing. + + .. warning:: + It is possible to crash the Python interpreter with a + sufficiently large/complex string due to stack depth limitations + in Python's AST compiler. + + .. versionchanged:: 3.2 + Now allows bytes and set literals. + + .. versionchanged:: 3.9 + Now supports creating empty sets with ``'set()'``. + + +.. function:: get_docstring(node, clean=True) + + Return the docstring of the given *node* (which must be a + :class:`FunctionDef`, :class:`AsyncFunctionDef`, :class:`ClassDef`, + or :class:`Module` node), or ``None`` if it has no docstring. + If *clean* is true, clean up the docstring's indentation with + :func:`inspect.cleandoc`. + + .. versionchanged:: 3.5 + :class:`AsyncFunctionDef` is now supported. + + +.. function:: get_source_segment(source, node, *, padded=False) + + Get source code segment of the *source* that generated *node*. + If some location information (:attr:`lineno`, :attr:`end_lineno`, + :attr:`col_offset`, or :attr:`end_col_offset`) is missing, return ``None``. + + If *padded* is ``True``, the first line of a multi-line statement will + be padded with spaces to match its original position. + + .. versionadded:: 3.8 + + +.. function:: fix_missing_locations(node) + + When you compile a node tree with :func:`compile`, the compiler expects + :attr:`lineno` and :attr:`col_offset` attributes for every node that supports + them. This is rather tedious to fill in for generated nodes, so this helper + adds these attributes recursively where not already set, by setting them to + the values of the parent node. It works recursively starting at *node*. + + +.. function:: increment_lineno(node, n=1) + + Increment the line number and end line number of each node in the tree + starting at *node* by *n*. This is useful to "move code" to a different + location in a file. + + +.. function:: copy_location(new_node, old_node) + + Copy source location (:attr:`lineno`, :attr:`col_offset`, :attr:`end_lineno`, + and :attr:`end_col_offset`) from *old_node* to *new_node* if possible, + and return *new_node*. + + +.. function:: iter_fields(node) + + Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` + that is present on *node*. + + +.. function:: iter_child_nodes(node) + + Yield all direct child nodes of *node*, that is, all fields that are nodes + and all items of fields that are lists of nodes. + + +.. function:: walk(node) + + Recursively yield all descendant nodes in the tree starting at *node* + (including *node* itself), in no specified order. This is useful if you only + want to modify nodes in place and don't care about the context. + + +.. class:: NodeVisitor() + + A node visitor base class that walks the abstract syntax tree and calls a + visitor function for every node found. This function may return a value + which is forwarded by the :meth:`visit` method. + + This class is meant to be subclassed, with the subclass adding visitor + methods. + + .. method:: visit(node) + + Visit a node. The default implementation calls the method called + :samp:`self.visit_{classname}` where *classname* is the name of the node + class, or :meth:`generic_visit` if that method doesn't exist. + + .. method:: generic_visit(node) + + This visitor calls :meth:`visit` on all children of the node. + + Note that child nodes of nodes that have a custom visitor method won't be + visited unless the visitor calls :meth:`generic_visit` or visits them + itself. + + Don't use the :class:`NodeVisitor` if you want to apply changes to nodes + during traversal. For this a special visitor exists + (:class:`NodeTransformer`) that allows modifications. + + .. deprecated:: 3.8 + + Methods :meth:`visit_Num`, :meth:`visit_Str`, :meth:`visit_Bytes`, + :meth:`visit_NameConstant` and :meth:`visit_Ellipsis` are deprecated + now and will not be called in future Python versions. Add the + :meth:`visit_Constant` method to handle all constant nodes. + + +.. class:: NodeTransformer() + + A :class:`NodeVisitor` subclass that walks the abstract syntax tree and + allows modification of nodes. + + The :class:`NodeTransformer` will walk the AST and use the return value of + the visitor methods to replace or remove the old node. If the return value + of the visitor method is ``None``, the node will be removed from its + location, otherwise it is replaced with the return value. The return value + may be the original node in which case no replacement takes place. + + Here is an example transformer that rewrites all occurrences of name lookups + (``foo``) to ``data['foo']``:: + + class RewriteName(NodeTransformer): + + def visit_Name(self, node): + return Subscript( + value=Name(id='data', ctx=Load()), + slice=Constant(value=node.id), + ctx=node.ctx + ) + + Keep in mind that if the node you're operating on has child nodes you must + either transform the child nodes yourself or call the :meth:`generic_visit` + method for the node first. + + For nodes that were part of a collection of statements (that applies to all + statement nodes), the visitor may also return a list of nodes rather than + just a single node. + + If :class:`NodeTransformer` introduces new nodes (that weren't part of + original tree) without giving them location information (such as + :attr:`lineno`), :func:`fix_missing_locations` should be called with + the new sub-tree to recalculate the location information:: + + tree = ast.parse('foo', mode='eval') + new_tree = fix_missing_locations(RewriteName().visit(tree)) + + Usually you use the transformer like this:: + + node = YourTransformer().visit(node) + + +.. function:: dump(node, annotate_fields=True, include_attributes=False, *, indent=None) + + Return a formatted dump of the tree in *node*. This is mainly useful for + debugging purposes. If *annotate_fields* is true (by default), + the returned string will show the names and the values for fields. + If *annotate_fields* is false, the result string will be more compact by + omitting unambiguous field names. Attributes such as line + numbers and column offsets are not dumped by default. If this is wanted, + *include_attributes* can be set to true. + + If *indent* is a non-negative integer or string, then the tree will be + pretty-printed with that indent level. An indent level + of 0, negative, or ``""`` will only insert newlines. ``None`` (the default) + selects the single line representation. Using a positive integer indent + indents that many spaces per level. If *indent* is a string (such as ``"\t"``), + that string is used to indent each level. + + .. versionchanged:: 3.9 + Added the *indent* option. + + +.. _ast-cli: + +Command-Line Usage +------------------ + +.. versionadded:: 3.9 + +The :mod:`ast` module can be executed as a script from the command line. +It is as simple as: + +.. code-block:: sh + + python -m ast [-m ] [-a] [infile] + +The following options are accepted: + +.. program:: ast + +.. cmdoption:: -h, --help + + Show the help message and exit. + +.. cmdoption:: -m + --mode + + Specify what kind of code must be compiled, like the *mode* argument + in :func:`parse`. + +.. cmdoption:: --no-type-comments + + Don't parse type comments. + +.. cmdoption:: -a, --include-attributes + + Include attributes such as line numbers and column offsets. + +.. cmdoption:: -i + --indent + + Indentation of nodes in AST (number of spaces). + +If :file:`infile` is specified its contents are parsed to AST and dumped +to stdout. Otherwise, the content is read from stdin. + + +.. seealso:: + + `Green Tree Snakes `_, an external documentation resource, has good + details on working with Python ASTs. diff --git a/cpython_2/environment/repo/Doc/library/asynchat.rst b/cpython_2/environment/repo/Doc/library/asynchat.rst new file mode 100644 index 0000000000000000000000000000000000000000..9e51416b83a570b45964431e85ef8b07070b27f5 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/asynchat.rst @@ -0,0 +1,213 @@ +:mod:`asynchat` --- Asynchronous socket command/response handler +================================================================ + +.. module:: asynchat + :synopsis: Support for asynchronous command/response protocols. + +.. moduleauthor:: Sam Rushing +.. sectionauthor:: Steve Holden + +**Source code:** :source:`Lib/asynchat.py` + +.. deprecated:: 3.6 + Please use :mod:`asyncio` instead. + +-------------- + +.. note:: + + This module exists for backwards compatibility only. For new code we + recommend using :mod:`asyncio`. + +This module builds on the :mod:`asyncore` infrastructure, simplifying +asynchronous clients and servers and making it easier to handle protocols +whose elements are terminated by arbitrary strings, or are of variable length. +:mod:`asynchat` defines the abstract class :class:`async_chat` that you +subclass, providing implementations of the :meth:`collect_incoming_data` and +:meth:`found_terminator` methods. It uses the same asynchronous loop as +:mod:`asyncore`, and the two types of channel, :class:`asyncore.dispatcher` +and :class:`asynchat.async_chat`, can freely be mixed in the channel map. +Typically an :class:`asyncore.dispatcher` server channel generates new +:class:`asynchat.async_chat` channel objects as it receives incoming +connection requests. + + +.. class:: async_chat() + + This class is an abstract subclass of :class:`asyncore.dispatcher`. To make + practical use of the code you must subclass :class:`async_chat`, providing + meaningful :meth:`collect_incoming_data` and :meth:`found_terminator` + methods. + The :class:`asyncore.dispatcher` methods can be used, although not all make + sense in a message/response context. + + Like :class:`asyncore.dispatcher`, :class:`async_chat` defines a set of + events that are generated by an analysis of socket conditions after a + :c:func:`select` call. Once the polling loop has been started the + :class:`async_chat` object's methods are called by the event-processing + framework with no action on the part of the programmer. + + Two class attributes can be modified, to improve performance, or possibly + even to conserve memory. + + + .. data:: ac_in_buffer_size + + The asynchronous input buffer size (default ``4096``). + + + .. data:: ac_out_buffer_size + + The asynchronous output buffer size (default ``4096``). + + Unlike :class:`asyncore.dispatcher`, :class:`async_chat` allows you to + define a :abbr:`FIFO (first-in, first-out)` queue of *producers*. A producer need + have only one method, :meth:`more`, which should return data to be + transmitted on the channel. + The producer indicates exhaustion (*i.e.* that it contains no more data) by + having its :meth:`more` method return the empty bytes object. At this point + the :class:`async_chat` object removes the producer from the queue and starts + using the next producer, if any. When the producer queue is empty the + :meth:`handle_write` method does nothing. You use the channel object's + :meth:`set_terminator` method to describe how to recognize the end of, or + an important breakpoint in, an incoming transmission from the remote + endpoint. + + To build a functioning :class:`async_chat` subclass your input methods + :meth:`collect_incoming_data` and :meth:`found_terminator` must handle the + data that the channel receives asynchronously. The methods are described + below. + + +.. method:: async_chat.close_when_done() + + Pushes a ``None`` on to the producer queue. When this producer is popped off + the queue it causes the channel to be closed. + + +.. method:: async_chat.collect_incoming_data(data) + + Called with *data* holding an arbitrary amount of received data. The + default method, which must be overridden, raises a + :exc:`NotImplementedError` exception. + + +.. method:: async_chat.discard_buffers() + + In emergencies this method will discard any data held in the input and/or + output buffers and the producer queue. + + +.. method:: async_chat.found_terminator() + + Called when the incoming data stream matches the termination condition set + by :meth:`set_terminator`. The default method, which must be overridden, + raises a :exc:`NotImplementedError` exception. The buffered input data + should be available via an instance attribute. + + +.. method:: async_chat.get_terminator() + + Returns the current terminator for the channel. + + +.. method:: async_chat.push(data) + + Pushes data on to the channel's queue to ensure its transmission. + This is all you need to do to have the channel write the data out to the + network, although it is possible to use your own producers in more complex + schemes to implement encryption and chunking, for example. + + +.. method:: async_chat.push_with_producer(producer) + + Takes a producer object and adds it to the producer queue associated with + the channel. When all currently-pushed producers have been exhausted the + channel will consume this producer's data by calling its :meth:`more` + method and send the data to the remote endpoint. + + +.. method:: async_chat.set_terminator(term) + + Sets the terminating condition to be recognized on the channel. ``term`` + may be any of three types of value, corresponding to three different ways + to handle incoming protocol data. + + +-----------+---------------------------------------------+ + | term | Description | + +===========+=============================================+ + | *string* | Will call :meth:`found_terminator` when the | + | | string is found in the input stream | + +-----------+---------------------------------------------+ + | *integer* | Will call :meth:`found_terminator` when the | + | | indicated number of characters have been | + | | received | + +-----------+---------------------------------------------+ + | ``None`` | The channel continues to collect data | + | | forever | + +-----------+---------------------------------------------+ + + Note that any data following the terminator will be available for reading + by the channel after :meth:`found_terminator` is called. + + +.. _asynchat-example: + +asynchat Example +---------------- + +The following partial example shows how HTTP requests can be read with +:class:`async_chat`. A web server might create an +:class:`http_request_handler` object for each incoming client connection. +Notice that initially the channel terminator is set to match the blank line at +the end of the HTTP headers, and a flag indicates that the headers are being +read. + +Once the headers have been read, if the request is of type POST (indicating +that further data are present in the input stream) then the +``Content-Length:`` header is used to set a numeric terminator to read the +right amount of data from the channel. + +The :meth:`handle_request` method is called once all relevant input has been +marshalled, after setting the channel terminator to ``None`` to ensure that +any extraneous data sent by the web client are ignored. :: + + + import asynchat + + class http_request_handler(asynchat.async_chat): + + def __init__(self, sock, addr, sessions, log): + asynchat.async_chat.__init__(self, sock=sock) + self.addr = addr + self.sessions = sessions + self.ibuffer = [] + self.obuffer = b"" + self.set_terminator(b"\r\n\r\n") + self.reading_headers = True + self.handling = False + self.cgi_data = None + self.log = log + + def collect_incoming_data(self, data): + """Buffer the data""" + self.ibuffer.append(data) + + def found_terminator(self): + if self.reading_headers: + self.reading_headers = False + self.parse_headers(b"".join(self.ibuffer)) + self.ibuffer = [] + if self.op.upper() == b"POST": + clen = self.headers.getheader("content-length") + self.set_terminator(int(clen)) + else: + self.handling = True + self.set_terminator(None) + self.handle_request() + elif not self.handling: + self.set_terminator(None) # browsers sometimes over-send + self.cgi_data = parse(self.headers, b"".join(self.ibuffer)) + self.handling = True + self.ibuffer = [] + self.handle_request() diff --git a/cpython_2/environment/repo/Doc/library/asyncio-api-index.rst b/cpython_2/environment/repo/Doc/library/asyncio-api-index.rst new file mode 100644 index 0000000000000000000000000000000000000000..d5b5659abc65e2fa4e1ec513996ebcdb20042e49 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/asyncio-api-index.rst @@ -0,0 +1,218 @@ +.. currentmodule:: asyncio + + +==================== +High-level API Index +==================== + +This page lists all high-level async/await enabled asyncio APIs. + + +Tasks +===== + +Utilities to run asyncio programs, create Tasks, and +await on multiple things with timeouts. + +.. list-table:: + :widths: 50 50 + :class: full-width-table + + * - :func:`run` + - Create event loop, run a coroutine, close the loop. + + * - :func:`create_task` + - Start an asyncio Task. + + * - ``await`` :func:`sleep` + - Sleep for a number of seconds. + + * - ``await`` :func:`gather` + - Schedule and wait for things concurrently. + + * - ``await`` :func:`wait_for` + - Run with a timeout. + + * - ``await`` :func:`shield` + - Shield from cancellation. + + * - ``await`` :func:`wait` + - Monitor for completion. + + * - :func:`current_task` + - Return the current Task. + + * - :func:`all_tasks` + - Return all tasks for an event loop. + + * - :class:`Task` + - Task object. + + * - :func:`run_coroutine_threadsafe` + - Schedule a coroutine from another OS thread. + + * - ``for in`` :func:`as_completed` + - Monitor for completion with a ``for`` loop. + + +.. rubric:: Examples + +* :ref:`Using asyncio.gather() to run things in parallel + `. + +* :ref:`Using asyncio.wait_for() to enforce a timeout + `. + +* :ref:`Cancellation `. + +* :ref:`Using asyncio.sleep() `. + +* See also the main :ref:`Tasks documentation page `. + + +Queues +====== + +Queues should be used to distribute work amongst multiple asyncio Tasks, +implement connection pools, and pub/sub patterns. + + +.. list-table:: + :widths: 50 50 + :class: full-width-table + + * - :class:`Queue` + - A FIFO queue. + + * - :class:`PriorityQueue` + - A priority queue. + + * - :class:`LifoQueue` + - A LIFO queue. + + +.. rubric:: Examples + +* :ref:`Using asyncio.Queue to distribute workload between several + Tasks `. + +* See also the :ref:`Queues documentation page `. + + +Subprocesses +============ + +Utilities to spawn subprocesses and run shell commands. + +.. list-table:: + :widths: 50 50 + :class: full-width-table + + * - ``await`` :func:`create_subprocess_exec` + - Create a subprocess. + + * - ``await`` :func:`create_subprocess_shell` + - Run a shell command. + + +.. rubric:: Examples + +* :ref:`Executing a shell command `. + +* See also the :ref:`subprocess APIs ` + documentation. + + +Streams +======= + +High-level APIs to work with network IO. + +.. list-table:: + :widths: 50 50 + :class: full-width-table + + * - ``await`` :func:`open_connection` + - Establish a TCP connection. + + * - ``await`` :func:`open_unix_connection` + - Establish a Unix socket connection. + + * - ``await`` :func:`start_server` + - Start a TCP server. + + * - ``await`` :func:`start_unix_server` + - Start a Unix socket server. + + * - :class:`StreamReader` + - High-level async/await object to receive network data. + + * - :class:`StreamWriter` + - High-level async/await object to send network data. + + +.. rubric:: Examples + +* :ref:`Example TCP client `. + +* See also the :ref:`streams APIs ` + documentation. + + +Synchronization +=============== + +Threading-like synchronization primitives that can be used in Tasks. + +.. list-table:: + :widths: 50 50 + :class: full-width-table + + * - :class:`Lock` + - A mutex lock. + + * - :class:`Event` + - An event object. + + * - :class:`Condition` + - A condition object. + + * - :class:`Semaphore` + - A semaphore. + + * - :class:`BoundedSemaphore` + - A bounded semaphore. + + +.. rubric:: Examples + +* :ref:`Using asyncio.Event `. + +* See also the documentation of asyncio + :ref:`synchronization primitives `. + + +Exceptions +========== + +.. list-table:: + :widths: 50 50 + :class: full-width-table + + + * - :exc:`asyncio.TimeoutError` + - Raised on timeout by functions like :func:`wait_for`. + Keep in mind that ``asyncio.TimeoutError`` is **unrelated** + to the built-in :exc:`TimeoutError` exception. + + * - :exc:`asyncio.CancelledError` + - Raised when a Task is cancelled. See also :meth:`Task.cancel`. + + +.. rubric:: Examples + +* :ref:`Handling CancelledError to run code on cancellation request + `. + +* See also the full list of + :ref:`asyncio-specific exceptions `. diff --git a/cpython_2/environment/repo/Doc/library/asyncio-dev.rst b/cpython_2/environment/repo/Doc/library/asyncio-dev.rst new file mode 100644 index 0000000000000000000000000000000000000000..ff51c4fa3b20f47ca2b01e289f1874f17ff20196 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/asyncio-dev.rst @@ -0,0 +1,237 @@ +.. currentmodule:: asyncio + +.. _asyncio-dev: + +======================= +Developing with asyncio +======================= + +Asynchronous programming is different from classic "sequential" +programming. + +This page lists common mistakes and traps and explains how +to avoid them. + + +.. _asyncio-debug-mode: + +Debug Mode +========== + +By default asyncio runs in production mode. In order to ease +the development asyncio has a *debug mode*. + +There are several ways to enable asyncio debug mode: + +* Setting the :envvar:`PYTHONASYNCIODEBUG` environment variable to ``1``. + +* Using the :ref:`Python Development Mode `. + +* Passing ``debug=True`` to :func:`asyncio.run`. + +* Calling :meth:`loop.set_debug`. + +In addition to enabling the debug mode, consider also: + +* setting the log level of the :ref:`asyncio logger ` to + :py:data:`logging.DEBUG`, for example the following snippet of code + can be run at startup of the application:: + + logging.basicConfig(level=logging.DEBUG) + +* configuring the :mod:`warnings` module to display + :exc:`ResourceWarning` warnings. One way of doing that is by + using the :option:`-W` ``default`` command line option. + + +When the debug mode is enabled: + +* asyncio checks for :ref:`coroutines that were not awaited + ` and logs them; this mitigates + the "forgotten await" pitfall. + +* Many non-threadsafe asyncio APIs (such as :meth:`loop.call_soon` and + :meth:`loop.call_at` methods) raise an exception if they are called + from a wrong thread. + +* The execution time of the I/O selector is logged if it takes too long to + perform an I/O operation. + +* Callbacks taking longer than 100ms are logged. The + :attr:`loop.slow_callback_duration` attribute can be used to set the + minimum execution duration in seconds that is considered "slow". + + +.. _asyncio-multithreading: + +Concurrency and Multithreading +============================== + +An event loop runs in a thread (typically the main thread) and executes +all callbacks and Tasks in its thread. While a Task is running in the +event loop, no other Tasks can run in the same thread. When a Task +executes an ``await`` expression, the running Task gets suspended, and +the event loop executes the next Task. + +To schedule a callback from a different OS thread, the +:meth:`loop.call_soon_threadsafe` method should be used. Example:: + + loop.call_soon_threadsafe(callback, *args) + +Almost all asyncio objects are not thread safe, which is typically +not a problem unless there is code that works with them from outside +of a Task or a callback. If there's a need for such code to call a +low-level asyncio API, the :meth:`loop.call_soon_threadsafe` method +should be used, e.g.:: + + loop.call_soon_threadsafe(fut.cancel) + +To schedule a coroutine object from a different OS thread, the +:func:`run_coroutine_threadsafe` function should be used. It returns a +:class:`concurrent.futures.Future` to access the result:: + + async def coro_func(): + return await asyncio.sleep(1, 42) + + # Later in another OS thread: + + future = asyncio.run_coroutine_threadsafe(coro_func(), loop) + # Wait for the result: + result = future.result() + +To handle signals and to execute subprocesses, the event loop must be +run in the main thread. + +The :meth:`loop.run_in_executor` method can be used with a +:class:`concurrent.futures.ThreadPoolExecutor` to execute +blocking code in a different OS thread without blocking the OS thread +that the event loop runs in. + + +.. _asyncio-handle-blocking: + +Running Blocking Code +===================== + +Blocking (CPU-bound) code should not be called directly. For example, +if a function performs a CPU-intensive calculation for 1 second, +all concurrent asyncio Tasks and IO operations would be delayed +by 1 second. + +An executor can be used to run a task in a different thread or even in +a different process to avoid blocking the OS thread with the +event loop. See the :meth:`loop.run_in_executor` method for more +details. + + +.. _asyncio-logger: + +Logging +======= + +asyncio uses the :mod:`logging` module and all logging is performed +via the ``"asyncio"`` logger. + +The default log level is :py:data:`logging.INFO`, which can be easily +adjusted:: + + logging.getLogger("asyncio").setLevel(logging.WARNING) + + +.. _asyncio-coroutine-not-scheduled: + +Detect never-awaited coroutines +=============================== + +When a coroutine function is called, but not awaited +(e.g. ``coro()`` instead of ``await coro()``) +or the coroutine is not scheduled with :meth:`asyncio.create_task`, asyncio +will emit a :exc:`RuntimeWarning`:: + + import asyncio + + async def test(): + print("never scheduled") + + async def main(): + test() + + asyncio.run(main()) + +Output:: + + test.py:7: RuntimeWarning: coroutine 'test' was never awaited + test() + +Output in debug mode:: + + test.py:7: RuntimeWarning: coroutine 'test' was never awaited + Coroutine created at (most recent call last) + File "../t.py", line 9, in + asyncio.run(main(), debug=True) + + < .. > + + File "../t.py", line 7, in main + test() + test() + +The usual fix is to either await the coroutine or call the +:meth:`asyncio.create_task` function:: + + async def main(): + await test() + + +Detect never-retrieved exceptions +================================= + +If a :meth:`Future.set_exception` is called but the Future object is +never awaited on, the exception would never be propagated to the +user code. In this case, asyncio would emit a log message when the +Future object is garbage collected. + +Example of an unhandled exception:: + + import asyncio + + async def bug(): + raise Exception("not consumed") + + async def main(): + asyncio.create_task(bug()) + + asyncio.run(main()) + +Output:: + + Task exception was never retrieved + future: + exception=Exception('not consumed')> + + Traceback (most recent call last): + File "test.py", line 4, in bug + raise Exception("not consumed") + Exception: not consumed + +:ref:`Enable the debug mode ` to get the +traceback where the task was created:: + + asyncio.run(main(), debug=True) + +Output in debug mode:: + + Task exception was never retrieved + future: + exception=Exception('not consumed') created at asyncio/tasks.py:321> + + source_traceback: Object created at (most recent call last): + File "../t.py", line 9, in + asyncio.run(main(), debug=True) + + < .. > + + Traceback (most recent call last): + File "../t.py", line 4, in bug + raise Exception("not consumed") + Exception: not consumed diff --git a/cpython_2/environment/repo/Doc/library/asyncio-eventloop.rst b/cpython_2/environment/repo/Doc/library/asyncio-eventloop.rst new file mode 100644 index 0000000000000000000000000000000000000000..d60a6ce95cdd87c0a318bb3dcfede61e164d6ec2 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/asyncio-eventloop.rst @@ -0,0 +1,1708 @@ +.. currentmodule:: asyncio + + +========== +Event Loop +========== + +**Source code:** :source:`Lib/asyncio/events.py`, +:source:`Lib/asyncio/base_events.py` + +------------------------------------ + +.. rubric:: Preface + +The event loop is the core of every asyncio application. +Event loops run asynchronous tasks and callbacks, perform network +IO operations, and run subprocesses. + +Application developers should typically use the high-level asyncio functions, +such as :func:`asyncio.run`, and should rarely need to reference the loop +object or call its methods. This section is intended mostly for authors +of lower-level code, libraries, and frameworks, who need finer control over +the event loop behavior. + +.. rubric:: Obtaining the Event Loop + +The following low-level functions can be used to get, set, or create +an event loop: + +.. function:: get_running_loop() + + Return the running event loop in the current OS thread. + + If there is no running event loop a :exc:`RuntimeError` is raised. + This function can only be called from a coroutine or a callback. + + .. versionadded:: 3.7 + +.. function:: get_event_loop() + + Get the current event loop. + + If there is no current event loop set in the current OS thread, + the OS thread is main, and :func:`set_event_loop` has not yet + been called, asyncio will create a new event loop and set it as the + current one. + + Because this function has rather complex behavior (especially + when custom event loop policies are in use), using the + :func:`get_running_loop` function is preferred to :func:`get_event_loop` + in coroutines and callbacks. + + Consider also using the :func:`asyncio.run` function instead of using + lower level functions to manually create and close an event loop. + +.. function:: set_event_loop(loop) + + Set *loop* as a current event loop for the current OS thread. + +.. function:: new_event_loop() + + Create a new event loop object. + +Note that the behaviour of :func:`get_event_loop`, :func:`set_event_loop`, +and :func:`new_event_loop` functions can be altered by +:ref:`setting a custom event loop policy `. + + +.. rubric:: Contents + +This documentation page contains the following sections: + +* The `Event Loop Methods`_ section is the reference documentation of + the event loop APIs; + +* The `Callback Handles`_ section documents the :class:`Handle` and + :class:`TimerHandle` instances which are returned from scheduling + methods such as :meth:`loop.call_soon` and :meth:`loop.call_later`; + +* The `Server Objects`_ section documents types returned from + event loop methods like :meth:`loop.create_server`; + +* The `Event Loop Implementations`_ section documents the + :class:`SelectorEventLoop` and :class:`ProactorEventLoop` classes; + +* The `Examples`_ section showcases how to work with some event + loop APIs. + + +.. _asyncio-event-loop: + +Event Loop Methods +================== + +Event loops have **low-level** APIs for the following: + +.. contents:: + :depth: 1 + :local: + + +Running and stopping the loop +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. method:: loop.run_until_complete(future) + + Run until the *future* (an instance of :class:`Future`) has + completed. + + If the argument is a :ref:`coroutine object ` it + is implicitly scheduled to run as a :class:`asyncio.Task`. + + Return the Future's result or raise its exception. + +.. method:: loop.run_forever() + + Run the event loop until :meth:`stop` is called. + + If :meth:`stop` is called before :meth:`run_forever()` is called, + the loop will poll the I/O selector once with a timeout of zero, + run all callbacks scheduled in response to I/O events (and + those that were already scheduled), and then exit. + + If :meth:`stop` is called while :meth:`run_forever` is running, + the loop will run the current batch of callbacks and then exit. + Note that new callbacks scheduled by callbacks will not run in this + case; instead, they will run the next time :meth:`run_forever` or + :meth:`run_until_complete` is called. + +.. method:: loop.stop() + + Stop the event loop. + +.. method:: loop.is_running() + + Return ``True`` if the event loop is currently running. + +.. method:: loop.is_closed() + + Return ``True`` if the event loop was closed. + +.. method:: loop.close() + + Close the event loop. + + The loop must not be running when this function is called. + Any pending callbacks will be discarded. + + This method clears all queues and shuts down the executor, but does + not wait for the executor to finish. + + This method is idempotent and irreversible. No other methods + should be called after the event loop is closed. + +.. coroutinemethod:: loop.shutdown_asyncgens() + + Schedule all currently open :term:`asynchronous generator` objects to + close with an :meth:`~agen.aclose()` call. After calling this method, + the event loop will issue a warning if a new asynchronous generator + is iterated. This should be used to reliably finalize all scheduled + asynchronous generators. + + Note that there is no need to call this function when + :func:`asyncio.run` is used. + + Example:: + + try: + loop.run_forever() + finally: + loop.run_until_complete(loop.shutdown_asyncgens()) + loop.close() + + .. versionadded:: 3.6 + +.. coroutinemethod:: loop.shutdown_default_executor() + + Schedule the closure of the default executor and wait for it to join all of + the threads in the :class:`ThreadPoolExecutor`. After calling this method, a + :exc:`RuntimeError` will be raised if :meth:`loop.run_in_executor` is called + while using the default executor. + + Note that there is no need to call this function when + :func:`asyncio.run` is used. + + .. versionadded:: 3.9 + + +Scheduling callbacks +^^^^^^^^^^^^^^^^^^^^ + +.. method:: loop.call_soon(callback, *args, context=None) + + Schedule a *callback* to be called with *args* arguments at + the next iteration of the event loop. + + Callbacks are called in the order in which they are registered. + Each callback will be called exactly once. + + An optional keyword-only *context* argument allows specifying a + custom :class:`contextvars.Context` for the *callback* to run in. + The current context is used when no *context* is provided. + + An instance of :class:`asyncio.Handle` is returned, which can be + used later to cancel the callback. + + This method is not thread-safe. + +.. method:: loop.call_soon_threadsafe(callback, *args, context=None) + + A thread-safe variant of :meth:`call_soon`. Must be used to + schedule callbacks *from another thread*. + + See the :ref:`concurrency and multithreading ` + section of the documentation. + +.. versionchanged:: 3.7 + The *context* keyword-only parameter was added. See :pep:`567` + for more details. + +.. _asyncio-pass-keywords: + +.. note:: + + Most :mod:`asyncio` scheduling functions don't allow passing + keyword arguments. To do that, use :func:`functools.partial`:: + + # will schedule "print("Hello", flush=True)" + loop.call_soon( + functools.partial(print, "Hello", flush=True)) + + Using partial objects is usually more convenient than using lambdas, + as asyncio can render partial objects better in debug and error + messages. + + +.. _asyncio-delayed-calls: + +Scheduling delayed callbacks +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Event loop provides mechanisms to schedule callback functions +to be called at some point in the future. Event loop uses monotonic +clocks to track time. + + +.. method:: loop.call_later(delay, callback, *args, context=None) + + Schedule *callback* to be called after the given *delay* + number of seconds (can be either an int or a float). + + An instance of :class:`asyncio.TimerHandle` is returned which can + be used to cancel the callback. + + *callback* will be called exactly once. If two callbacks are + scheduled for exactly the same time, the order in which they + are called is undefined. + + The optional positional *args* will be passed to the callback when + it is called. If you want the callback to be called with keyword + arguments use :func:`functools.partial`. + + An optional keyword-only *context* argument allows specifying a + custom :class:`contextvars.Context` for the *callback* to run in. + The current context is used when no *context* is provided. + + .. versionchanged:: 3.7 + The *context* keyword-only parameter was added. See :pep:`567` + for more details. + + .. versionchanged:: 3.8 + In Python 3.7 and earlier with the default event loop implementation, + the *delay* could not exceed one day. + This has been fixed in Python 3.8. + +.. method:: loop.call_at(when, callback, *args, context=None) + + Schedule *callback* to be called at the given absolute timestamp + *when* (an int or a float), using the same time reference as + :meth:`loop.time`. + + This method's behavior is the same as :meth:`call_later`. + + An instance of :class:`asyncio.TimerHandle` is returned which can + be used to cancel the callback. + + .. versionchanged:: 3.7 + The *context* keyword-only parameter was added. See :pep:`567` + for more details. + + .. versionchanged:: 3.8 + In Python 3.7 and earlier with the default event loop implementation, + the difference between *when* and the current time could not exceed + one day. This has been fixed in Python 3.8. + +.. method:: loop.time() + + Return the current time, as a :class:`float` value, according to + the event loop's internal monotonic clock. + +.. note:: + .. versionchanged:: 3.8 + In Python 3.7 and earlier timeouts (relative *delay* or absolute *when*) + should not exceed one day. This has been fixed in Python 3.8. + +.. seealso:: + + The :func:`asyncio.sleep` function. + + +Creating Futures and Tasks +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. method:: loop.create_future() + + Create an :class:`asyncio.Future` object attached to the event loop. + + This is the preferred way to create Futures in asyncio. This lets + third-party event loops provide alternative implementations of + the Future object (with better performance or instrumentation). + + .. versionadded:: 3.5.2 + +.. method:: loop.create_task(coro, \*, name=None) + + Schedule the execution of a :ref:`coroutine`. + Return a :class:`Task` object. + + Third-party event loops can use their own subclass of :class:`Task` + for interoperability. In this case, the result type is a subclass + of :class:`Task`. + + If the *name* argument is provided and not ``None``, it is set as + the name of the task using :meth:`Task.set_name`. + + .. versionchanged:: 3.8 + Added the ``name`` parameter. + +.. method:: loop.set_task_factory(factory) + + Set a task factory that will be used by + :meth:`loop.create_task`. + + If *factory* is ``None`` the default task factory will be set. + Otherwise, *factory* must be a *callable* with the signature matching + ``(loop, coro)``, where *loop* is a reference to the active + event loop, and *coro* is a coroutine object. The callable + must return a :class:`asyncio.Future`-compatible object. + +.. method:: loop.get_task_factory() + + Return a task factory or ``None`` if the default one is in use. + + +Opening network connections +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. coroutinemethod:: loop.create_connection(protocol_factory, \ + host=None, port=None, \*, ssl=None, \ + family=0, proto=0, flags=0, sock=None, \ + local_addr=None, server_hostname=None, \ + ssl_handshake_timeout=None, \ + happy_eyeballs_delay=None, interleave=None) + + Open a streaming transport connection to a given + address specified by *host* and *port*. + + The socket family can be either :py:data:`~socket.AF_INET` or + :py:data:`~socket.AF_INET6` depending on *host* (or the *family* + argument, if provided). + + The socket type will be :py:data:`~socket.SOCK_STREAM`. + + *protocol_factory* must be a callable returning an + :ref:`asyncio protocol ` implementation. + + This method will try to establish the connection in the background. + When successful, it returns a ``(transport, protocol)`` pair. + + The chronological synopsis of the underlying operation is as follows: + + #. The connection is established and a :ref:`transport ` + is created for it. + + #. *protocol_factory* is called without arguments and is expected to + return a :ref:`protocol ` instance. + + #. The protocol instance is coupled with the transport by calling its + :meth:`~BaseProtocol.connection_made` method. + + #. A ``(transport, protocol)`` tuple is returned on success. + + The created transport is an implementation-dependent bidirectional + stream. + + Other arguments: + + * *ssl*: if given and not false, a SSL/TLS transport is created + (by default a plain TCP transport is created). If *ssl* is + a :class:`ssl.SSLContext` object, this context is used to create + the transport; if *ssl* is :const:`True`, a default context returned + from :func:`ssl.create_default_context` is used. + + .. seealso:: :ref:`SSL/TLS security considerations ` + + * *server_hostname* sets or overrides the hostname that the target + server's certificate will be matched against. Should only be passed + if *ssl* is not ``None``. By default the value of the *host* argument + is used. If *host* is empty, there is no default and you must pass a + value for *server_hostname*. If *server_hostname* is an empty + string, hostname matching is disabled (which is a serious security + risk, allowing for potential man-in-the-middle attacks). + + * *family*, *proto*, *flags* are the optional address family, protocol + and flags to be passed through to getaddrinfo() for *host* resolution. + If given, these should all be integers from the corresponding + :mod:`socket` module constants. + + * *happy_eyeballs_delay*, if given, enables Happy Eyeballs for this + connection. It should + be a floating-point number representing the amount of time in seconds + to wait for a connection attempt to complete, before starting the next + attempt in parallel. This is the "Connection Attempt Delay" as defined + in :rfc:`8305`. A sensible default value recommended by the RFC is ``0.25`` + (250 milliseconds). + + * *interleave* controls address reordering when a host name resolves to + multiple IP addresses. + If ``0`` or unspecified, no reordering is done, and addresses are + tried in the order returned by :meth:`getaddrinfo`. If a positive integer + is specified, the addresses are interleaved by address family, and the + given integer is interpreted as "First Address Family Count" as defined + in :rfc:`8305`. The default is ``0`` if *happy_eyeballs_delay* is not + specified, and ``1`` if it is. + + * *sock*, if given, should be an existing, already connected + :class:`socket.socket` object to be used by the transport. + If *sock* is given, none of *host*, *port*, *family*, *proto*, *flags*, + *happy_eyeballs_delay*, *interleave* + and *local_addr* should be specified. + + * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used + to bind the socket to locally. The *local_host* and *local_port* + are looked up using ``getaddrinfo()``, similarly to *host* and *port*. + + * *ssl_handshake_timeout* is (for a TLS connection) the time in seconds + to wait for the TLS handshake to complete before aborting the connection. + ``60.0`` seconds if ``None`` (default). + + .. versionadded:: 3.8 + + Added the *happy_eyeballs_delay* and *interleave* parameters. + + Happy Eyeballs Algorithm: Success with Dual-Stack Hosts. + When a server's IPv4 path and protocol are working, but the server's + IPv6 path and protocol are not working, a dual-stack client + application experiences significant connection delay compared to an + IPv4-only client. This is undesirable because it causes the dual- + stack client to have a worse user experience. This document + specifies requirements for algorithms that reduce this user-visible + delay and provides an algorithm. + + For more information: https://tools.ietf.org/html/rfc6555 + + .. versionadded:: 3.7 + + The *ssl_handshake_timeout* parameter. + + .. versionchanged:: 3.6 + + The socket option :py:data:`~socket.TCP_NODELAY` is set by default + for all TCP connections. + + .. versionchanged:: 3.5 + + Added support for SSL/TLS in :class:`ProactorEventLoop`. + + .. seealso:: + + The :func:`open_connection` function is a high-level alternative + API. It returns a pair of (:class:`StreamReader`, :class:`StreamWriter`) + that can be used directly in async/await code. + +.. coroutinemethod:: loop.create_datagram_endpoint(protocol_factory, \ + local_addr=None, remote_addr=None, \*, \ + family=0, proto=0, flags=0, \ + reuse_address=None, reuse_port=None, \ + allow_broadcast=None, sock=None) + + .. note:: + The parameter *reuse_address* is no longer supported, as using + :py:data:`~sockets.SO_REUSEADDR` poses a significant security concern for + UDP. Explicitly passing ``reuse_address=True`` will raise an exception. + + When multiple processes with differing UIDs assign sockets to an + identical UDP socket address with ``SO_REUSEADDR``, incoming packets can + become randomly distributed among the sockets. + + For supported platforms, *reuse_port* can be used as a replacement for + similar functionality. With *reuse_port*, + :py:data:`~sockets.SO_REUSEPORT` is used instead, which specifically + prevents processes with differing UIDs from assigning sockets to the same + socket address. + + Create a datagram connection. + + The socket family can be either :py:data:`~socket.AF_INET`, + :py:data:`~socket.AF_INET6`, or :py:data:`~socket.AF_UNIX`, + depending on *host* (or the *family* argument, if provided). + + The socket type will be :py:data:`~socket.SOCK_DGRAM`. + + *protocol_factory* must be a callable returning a + :ref:`protocol ` implementation. + + A tuple of ``(transport, protocol)`` is returned on success. + + Other arguments: + + * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used + to bind the socket to locally. The *local_host* and *local_port* + are looked up using :meth:`getaddrinfo`. + + * *remote_addr*, if given, is a ``(remote_host, remote_port)`` tuple used + to connect the socket to a remote address. The *remote_host* and + *remote_port* are looked up using :meth:`getaddrinfo`. + + * *family*, *proto*, *flags* are the optional address family, protocol + and flags to be passed through to :meth:`getaddrinfo` for *host* + resolution. If given, these should all be integers from the + corresponding :mod:`socket` module constants. + + * *reuse_port* tells the kernel to allow this endpoint to be bound to the + same port as other existing endpoints are bound to, so long as they all + set this flag when being created. This option is not supported on Windows + and some Unixes. If the :py:data:`~socket.SO_REUSEPORT` constant is not + defined then this capability is unsupported. + + * *allow_broadcast* tells the kernel to allow this endpoint to send + messages to the broadcast address. + + * *sock* can optionally be specified in order to use a preexisting, + already connected, :class:`socket.socket` object to be used by the + transport. If specified, *local_addr* and *remote_addr* should be omitted + (must be :const:`None`). + + See :ref:`UDP echo client protocol ` and + :ref:`UDP echo server protocol ` examples. + + .. versionchanged:: 3.4.4 + The *family*, *proto*, *flags*, *reuse_address*, *reuse_port, + *allow_broadcast*, and *sock* parameters were added. + + .. versionchanged:: 3.8.1 + The *reuse_address* parameter is no longer supported due to security + concerns. + + .. versionchanged:: 3.8 + Added support for Windows. + +.. coroutinemethod:: loop.create_unix_connection(protocol_factory, \ + path=None, \*, ssl=None, sock=None, \ + server_hostname=None, ssl_handshake_timeout=None) + + Create a Unix connection. + + The socket family will be :py:data:`~socket.AF_UNIX`; socket + type will be :py:data:`~socket.SOCK_STREAM`. + + A tuple of ``(transport, protocol)`` is returned on success. + + *path* is the name of a Unix domain socket and is required, + unless a *sock* parameter is specified. Abstract Unix sockets, + :class:`str`, :class:`bytes`, and :class:`~pathlib.Path` paths are + supported. + + See the documentation of the :meth:`loop.create_connection` method + for information about arguments to this method. + + .. availability:: Unix. + + .. versionadded:: 3.7 + + The *ssl_handshake_timeout* parameter. + + .. versionchanged:: 3.7 + + The *path* parameter can now be a :term:`path-like object`. + + +Creating network servers +^^^^^^^^^^^^^^^^^^^^^^^^ + +.. coroutinemethod:: loop.create_server(protocol_factory, \ + host=None, port=None, \*, \ + family=socket.AF_UNSPEC, \ + flags=socket.AI_PASSIVE, \ + sock=None, backlog=100, ssl=None, \ + reuse_address=None, reuse_port=None, \ + ssl_handshake_timeout=None, start_serving=True) + + Create a TCP server (socket type :data:`~socket.SOCK_STREAM`) listening + on *port* of the *host* address. + + Returns a :class:`Server` object. + + Arguments: + + * *protocol_factory* must be a callable returning a + :ref:`protocol ` implementation. + + * The *host* parameter can be set to several types which determine where + the server would be listening: + + - If *host* is a string, the TCP server is bound to a single network + interface specified by *host*. + + - If *host* is a sequence of strings, the TCP server is bound to all + network interfaces specified by the sequence. + + - If *host* is an empty string or ``None``, all interfaces are + assumed and a list of multiple sockets will be returned (most likely + one for IPv4 and another one for IPv6). + + * *family* can be set to either :data:`socket.AF_INET` or + :data:`~socket.AF_INET6` to force the socket to use IPv4 or IPv6. + If not set, the *family* will be determined from host name + (defaults to :data:`~socket.AF_UNSPEC`). + + * *flags* is a bitmask for :meth:`getaddrinfo`. + + * *sock* can optionally be specified in order to use a preexisting + socket object. If specified, *host* and *port* must not be specified. + + * *backlog* is the maximum number of queued connections passed to + :meth:`~socket.socket.listen` (defaults to 100). + + * *ssl* can be set to an :class:`~ssl.SSLContext` instance to enable + TLS over the accepted connections. + + * *reuse_address* tells the kernel to reuse a local socket in + ``TIME_WAIT`` state, without waiting for its natural timeout to + expire. If not specified will automatically be set to ``True`` on + Unix. + + * *reuse_port* tells the kernel to allow this endpoint to be bound to the + same port as other existing endpoints are bound to, so long as they all + set this flag when being created. This option is not supported on + Windows. + + * *ssl_handshake_timeout* is (for a TLS server) the time in seconds to wait + for the TLS handshake to complete before aborting the connection. + ``60.0`` seconds if ``None`` (default). + + * *start_serving* set to ``True`` (the default) causes the created server + to start accepting connections immediately. When set to ``False``, + the user should await on :meth:`Server.start_serving` or + :meth:`Server.serve_forever` to make the server to start accepting + connections. + + .. versionadded:: 3.7 + + Added *ssl_handshake_timeout* and *start_serving* parameters. + + .. versionchanged:: 3.6 + + The socket option :py:data:`~socket.TCP_NODELAY` is set by default + for all TCP connections. + + .. versionchanged:: 3.5 + + Added support for SSL/TLS in :class:`ProactorEventLoop`. + + .. versionchanged:: 3.5.1 + + The *host* parameter can be a sequence of strings. + + .. seealso:: + + The :func:`start_server` function is a higher-level alternative API + that returns a pair of :class:`StreamReader` and :class:`StreamWriter` + that can be used in an async/await code. + + +.. coroutinemethod:: loop.create_unix_server(protocol_factory, path=None, \ + \*, sock=None, backlog=100, ssl=None, \ + ssl_handshake_timeout=None, start_serving=True) + + Similar to :meth:`loop.create_server` but works with the + :py:data:`~socket.AF_UNIX` socket family. + + *path* is the name of a Unix domain socket, and is required, + unless a *sock* argument is provided. Abstract Unix sockets, + :class:`str`, :class:`bytes`, and :class:`~pathlib.Path` paths + are supported. + + See the documentation of the :meth:`loop.create_server` method + for information about arguments to this method. + + .. availability:: Unix. + + .. versionadded:: 3.7 + + The *ssl_handshake_timeout* and *start_serving* parameters. + + .. versionchanged:: 3.7 + + The *path* parameter can now be a :class:`~pathlib.Path` object. + +.. coroutinemethod:: loop.connect_accepted_socket(protocol_factory, \ + sock, \*, ssl=None, ssl_handshake_timeout=None) + + Wrap an already accepted connection into a transport/protocol pair. + + This method can be used by servers that accept connections outside + of asyncio but that use asyncio to handle them. + + Parameters: + + * *protocol_factory* must be a callable returning a + :ref:`protocol ` implementation. + + * *sock* is a preexisting socket object returned from + :meth:`socket.accept `. + + * *ssl* can be set to an :class:`~ssl.SSLContext` to enable SSL over + the accepted connections. + + * *ssl_handshake_timeout* is (for an SSL connection) the time in seconds to + wait for the SSL handshake to complete before aborting the connection. + ``60.0`` seconds if ``None`` (default). + + Returns a ``(transport, protocol)`` pair. + + .. versionadded:: 3.7 + + The *ssl_handshake_timeout* parameter. + + .. versionadded:: 3.5.3 + + +Transferring files +^^^^^^^^^^^^^^^^^^ + +.. coroutinemethod:: loop.sendfile(transport, file, \ + offset=0, count=None, *, fallback=True) + + Send a *file* over a *transport*. Return the total number of bytes + sent. + + The method uses high-performance :meth:`os.sendfile` if available. + + *file* must be a regular file object opened in binary mode. + + *offset* tells from where to start reading the file. If specified, + *count* is the total number of bytes to transmit as opposed to + sending the file until EOF is reached. File position is always updated, + even when this method raises an error, and + :meth:`file.tell() ` can be used to obtain the actual + number of bytes sent. + + *fallback* set to ``True`` makes asyncio to manually read and send + the file when the platform does not support the sendfile system call + (e.g. Windows or SSL socket on Unix). + + Raise :exc:`SendfileNotAvailableError` if the system does not support + the *sendfile* syscall and *fallback* is ``False``. + + .. versionadded:: 3.7 + + +TLS Upgrade +^^^^^^^^^^^ + +.. coroutinemethod:: loop.start_tls(transport, protocol, \ + sslcontext, \*, server_side=False, \ + server_hostname=None, ssl_handshake_timeout=None) + + Upgrade an existing transport-based connection to TLS. + + Return a new transport instance, that the *protocol* must start using + immediately after the *await*. The *transport* instance passed to + the *start_tls* method should never be used again. + + Parameters: + + * *transport* and *protocol* instances that methods like + :meth:`~loop.create_server` and + :meth:`~loop.create_connection` return. + + * *sslcontext*: a configured instance of :class:`~ssl.SSLContext`. + + * *server_side* pass ``True`` when a server-side connection is being + upgraded (like the one created by :meth:`~loop.create_server`). + + * *server_hostname*: sets or overrides the host name that the target + server's certificate will be matched against. + + * *ssl_handshake_timeout* is (for a TLS connection) the time in seconds to + wait for the TLS handshake to complete before aborting the connection. + ``60.0`` seconds if ``None`` (default). + + .. versionadded:: 3.7 + + +Watching file descriptors +^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. method:: loop.add_reader(fd, callback, \*args) + + Start monitoring the *fd* file descriptor for read availability and + invoke *callback* with the specified arguments once *fd* is available for + reading. + +.. method:: loop.remove_reader(fd) + + Stop monitoring the *fd* file descriptor for read availability. + +.. method:: loop.add_writer(fd, callback, \*args) + + Start monitoring the *fd* file descriptor for write availability and + invoke *callback* with the specified arguments once *fd* is available for + writing. + + Use :func:`functools.partial` :ref:`to pass keyword arguments + ` to *callback*. + +.. method:: loop.remove_writer(fd) + + Stop monitoring the *fd* file descriptor for write availability. + +See also :ref:`Platform Support ` section +for some limitations of these methods. + + +Working with socket objects directly +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +In general, protocol implementations that use transport-based APIs +such as :meth:`loop.create_connection` and :meth:`loop.create_server` +are faster than implementations that work with sockets directly. +However, there are some use cases when performance is not critical, and +working with :class:`~socket.socket` objects directly is more +convenient. + +.. coroutinemethod:: loop.sock_recv(sock, nbytes) + + Receive up to *nbytes* from *sock*. Asynchronous version of + :meth:`socket.recv() `. + + Return the received data as a bytes object. + + *sock* must be a non-blocking socket. + + .. versionchanged:: 3.7 + Even though this method was always documented as a coroutine + method, releases before Python 3.7 returned a :class:`Future`. + Since Python 3.7 this is an ``async def`` method. + +.. coroutinemethod:: loop.sock_recv_into(sock, buf) + + Receive data from *sock* into the *buf* buffer. Modeled after the blocking + :meth:`socket.recv_into() ` method. + + Return the number of bytes written to the buffer. + + *sock* must be a non-blocking socket. + + .. versionadded:: 3.7 + +.. coroutinemethod:: loop.sock_sendall(sock, data) + + Send *data* to the *sock* socket. Asynchronous version of + :meth:`socket.sendall() `. + + This method continues to send to the socket until either all data + in *data* has been sent or an error occurs. ``None`` is returned + on success. On error, an exception is raised. Additionally, there is no way + to determine how much data, if any, was successfully processed by the + receiving end of the connection. + + *sock* must be a non-blocking socket. + + .. versionchanged:: 3.7 + Even though the method was always documented as a coroutine + method, before Python 3.7 it returned an :class:`Future`. + Since Python 3.7, this is an ``async def`` method. + +.. coroutinemethod:: loop.sock_connect(sock, address) + + Connect *sock* to a remote socket at *address*. + + Asynchronous version of :meth:`socket.connect() `. + + *sock* must be a non-blocking socket. + + .. versionchanged:: 3.5.2 + ``address`` no longer needs to be resolved. ``sock_connect`` + will try to check if the *address* is already resolved by calling + :func:`socket.inet_pton`. If not, + :meth:`loop.getaddrinfo` will be used to resolve the + *address*. + + .. seealso:: + + :meth:`loop.create_connection` + and :func:`asyncio.open_connection() `. + + +.. coroutinemethod:: loop.sock_accept(sock) + + Accept a connection. Modeled after the blocking + :meth:`socket.accept() ` method. + + The socket must be bound to an address and listening + for connections. The return value is a pair ``(conn, address)`` where *conn* + is a *new* socket object usable to send and receive data on the connection, + and *address* is the address bound to the socket on the other end of the + connection. + + *sock* must be a non-blocking socket. + + .. versionchanged:: 3.7 + Even though the method was always documented as a coroutine + method, before Python 3.7 it returned a :class:`Future`. + Since Python 3.7, this is an ``async def`` method. + + .. seealso:: + + :meth:`loop.create_server` and :func:`start_server`. + +.. coroutinemethod:: loop.sock_sendfile(sock, file, offset=0, count=None, \ + \*, fallback=True) + + Send a file using high-performance :mod:`os.sendfile` if possible. + Return the total number of bytes sent. + + Asynchronous version of :meth:`socket.sendfile() `. + + *sock* must be a non-blocking :const:`socket.SOCK_STREAM` + :class:`~socket.socket`. + + *file* must be a regular file object open in binary mode. + + *offset* tells from where to start reading the file. If specified, + *count* is the total number of bytes to transmit as opposed to + sending the file until EOF is reached. File position is always updated, + even when this method raises an error, and + :meth:`file.tell() ` can be used to obtain the actual + number of bytes sent. + + *fallback*, when set to ``True``, makes asyncio manually read and send + the file when the platform does not support the sendfile syscall + (e.g. Windows or SSL socket on Unix). + + Raise :exc:`SendfileNotAvailableError` if the system does not support + *sendfile* syscall and *fallback* is ``False``. + + *sock* must be a non-blocking socket. + + .. versionadded:: 3.7 + + +DNS +^^^ + +.. coroutinemethod:: loop.getaddrinfo(host, port, \*, family=0, \ + type=0, proto=0, flags=0) + + Asynchronous version of :meth:`socket.getaddrinfo`. + +.. coroutinemethod:: loop.getnameinfo(sockaddr, flags=0) + + Asynchronous version of :meth:`socket.getnameinfo`. + +.. versionchanged:: 3.7 + Both *getaddrinfo* and *getnameinfo* methods were always documented + to return a coroutine, but prior to Python 3.7 they were, in fact, + returning :class:`asyncio.Future` objects. Starting with Python 3.7 + both methods are coroutines. + + +Working with pipes +^^^^^^^^^^^^^^^^^^ + +.. coroutinemethod:: loop.connect_read_pipe(protocol_factory, pipe) + + Register the read end of *pipe* in the event loop. + + *protocol_factory* must be a callable returning an + :ref:`asyncio protocol ` implementation. + + *pipe* is a :term:`file-like object `. + + Return pair ``(transport, protocol)``, where *transport* supports + the :class:`ReadTransport` interface and *protocol* is an object + instantiated by the *protocol_factory*. + + With :class:`SelectorEventLoop` event loop, the *pipe* is set to + non-blocking mode. + +.. coroutinemethod:: loop.connect_write_pipe(protocol_factory, pipe) + + Register the write end of *pipe* in the event loop. + + *protocol_factory* must be a callable returning an + :ref:`asyncio protocol ` implementation. + + *pipe* is :term:`file-like object `. + + Return pair ``(transport, protocol)``, where *transport* supports + :class:`WriteTransport` interface and *protocol* is an object + instantiated by the *protocol_factory*. + + With :class:`SelectorEventLoop` event loop, the *pipe* is set to + non-blocking mode. + +.. note:: + + :class:`SelectorEventLoop` does not support the above methods on + Windows. Use :class:`ProactorEventLoop` instead for Windows. + +.. seealso:: + + The :meth:`loop.subprocess_exec` and + :meth:`loop.subprocess_shell` methods. + + +Unix signals +^^^^^^^^^^^^ + +.. method:: loop.add_signal_handler(signum, callback, \*args) + + Set *callback* as the handler for the *signum* signal. + + The callback will be invoked by *loop*, along with other queued callbacks + and runnable coroutines of that event loop. Unlike signal handlers + registered using :func:`signal.signal`, a callback registered with this + function is allowed to interact with the event loop. + + Raise :exc:`ValueError` if the signal number is invalid or uncatchable. + Raise :exc:`RuntimeError` if there is a problem setting up the handler. + + Use :func:`functools.partial` :ref:`to pass keyword arguments + ` to *callback*. + + Like :func:`signal.signal`, this function must be invoked in the main + thread. + +.. method:: loop.remove_signal_handler(sig) + + Remove the handler for the *sig* signal. + + Return ``True`` if the signal handler was removed, or ``False`` if + no handler was set for the given signal. + + .. availability:: Unix. + +.. seealso:: + + The :mod:`signal` module. + + +Executing code in thread or process pools +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. awaitablemethod:: loop.run_in_executor(executor, func, \*args) + + Arrange for *func* to be called in the specified executor. + + The *executor* argument should be an :class:`concurrent.futures.Executor` + instance. The default executor is used if *executor* is ``None``. + + Example:: + + import asyncio + import concurrent.futures + + def blocking_io(): + # File operations (such as logging) can block the + # event loop: run them in a thread pool. + with open('/dev/urandom', 'rb') as f: + return f.read(100) + + def cpu_bound(): + # CPU-bound operations will block the event loop: + # in general it is preferable to run them in a + # process pool. + return sum(i * i for i in range(10 ** 7)) + + async def main(): + loop = asyncio.get_running_loop() + + ## Options: + + # 1. Run in the default loop's executor: + result = await loop.run_in_executor( + None, blocking_io) + print('default thread pool', result) + + # 2. Run in a custom thread pool: + with concurrent.futures.ThreadPoolExecutor() as pool: + result = await loop.run_in_executor( + pool, blocking_io) + print('custom thread pool', result) + + # 3. Run in a custom process pool: + with concurrent.futures.ProcessPoolExecutor() as pool: + result = await loop.run_in_executor( + pool, cpu_bound) + print('custom process pool', result) + + asyncio.run(main()) + + This method returns a :class:`asyncio.Future` object. + + Use :func:`functools.partial` :ref:`to pass keyword arguments + ` to *func*. + + .. versionchanged:: 3.5.3 + :meth:`loop.run_in_executor` no longer configures the + ``max_workers`` of the thread pool executor it creates, instead + leaving it up to the thread pool executor + (:class:`~concurrent.futures.ThreadPoolExecutor`) to set the + default. + +.. method:: loop.set_default_executor(executor) + + Set *executor* as the default executor used by :meth:`run_in_executor`. + *executor* should be an instance of + :class:`~concurrent.futures.ThreadPoolExecutor`. + + .. deprecated:: 3.8 + Using an executor that is not an instance of + :class:`~concurrent.futures.ThreadPoolExecutor` is deprecated and + will trigger an error in Python 3.9. + + *executor* must be an instance of + :class:`concurrent.futures.ThreadPoolExecutor`. + + +Error Handling API +^^^^^^^^^^^^^^^^^^ + +Allows customizing how exceptions are handled in the event loop. + +.. method:: loop.set_exception_handler(handler) + + Set *handler* as the new event loop exception handler. + + If *handler* is ``None``, the default exception handler will + be set. Otherwise, *handler* must be a callable with the signature + matching ``(loop, context)``, where ``loop`` + is a reference to the active event loop, and ``context`` + is a ``dict`` object containing the details of the exception + (see :meth:`call_exception_handler` documentation for details + about context). + +.. method:: loop.get_exception_handler() + + Return the current exception handler, or ``None`` if no custom + exception handler was set. + + .. versionadded:: 3.5.2 + +.. method:: loop.default_exception_handler(context) + + Default exception handler. + + This is called when an exception occurs and no exception + handler is set. This can be called by a custom exception + handler that wants to defer to the default handler behavior. + + *context* parameter has the same meaning as in + :meth:`call_exception_handler`. + +.. method:: loop.call_exception_handler(context) + + Call the current event loop exception handler. + + *context* is a ``dict`` object containing the following keys + (new keys may be introduced in future Python versions): + + * 'message': Error message; + * 'exception' (optional): Exception object; + * 'future' (optional): :class:`asyncio.Future` instance; + * 'handle' (optional): :class:`asyncio.Handle` instance; + * 'protocol' (optional): :ref:`Protocol ` instance; + * 'transport' (optional): :ref:`Transport ` instance; + * 'socket' (optional): :class:`socket.socket` instance. + + .. note:: + + This method should not be overloaded in subclassed + event loops. For custom exception handling, use + the :meth:`set_exception_handler()` method. + +Enabling debug mode +^^^^^^^^^^^^^^^^^^^ + +.. method:: loop.get_debug() + + Get the debug mode (:class:`bool`) of the event loop. + + The default value is ``True`` if the environment variable + :envvar:`PYTHONASYNCIODEBUG` is set to a non-empty string, ``False`` + otherwise. + +.. method:: loop.set_debug(enabled: bool) + + Set the debug mode of the event loop. + + .. versionchanged:: 3.7 + + The new :ref:`Python Development Mode ` can now also be used + to enable the debug mode. + +.. seealso:: + + The :ref:`debug mode of asyncio `. + + +Running Subprocesses +^^^^^^^^^^^^^^^^^^^^ + +Methods described in this subsections are low-level. In regular +async/await code consider using the high-level +:func:`asyncio.create_subprocess_shell` and +:func:`asyncio.create_subprocess_exec` convenience functions instead. + +.. note:: + + The default asyncio event loop on **Windows** does not support + subprocesses. See :ref:`Subprocess Support on Windows + ` for details. + +.. coroutinemethod:: loop.subprocess_exec(protocol_factory, \*args, \ + stdin=subprocess.PIPE, stdout=subprocess.PIPE, \ + stderr=subprocess.PIPE, \*\*kwargs) + + Create a subprocess from one or more string arguments specified by + *args*. + + *args* must be a list of strings represented by: + + * :class:`str`; + * or :class:`bytes`, encoded to the + :ref:`filesystem encoding `. + + The first string specifies the program executable, + and the remaining strings specify the arguments. Together, string + arguments form the ``argv`` of the program. + + This is similar to the standard library :class:`subprocess.Popen` + class called with ``shell=False`` and the list of strings passed as + the first argument; however, where :class:`~subprocess.Popen` takes + a single argument which is list of strings, *subprocess_exec* + takes multiple string arguments. + + The *protocol_factory* must be a callable returning a subclass of the + :class:`asyncio.SubprocessProtocol` class. + + Other parameters: + + * *stdin* can be any of these: + + * a file-like object representing a pipe to be connected to the + subprocess's standard input stream using + :meth:`~loop.connect_write_pipe` + * the :const:`subprocess.PIPE` constant (default) which will create a new + pipe and connect it, + * the value ``None`` which will make the subprocess inherit the file + descriptor from this process + * the :const:`subprocess.DEVNULL` constant which indicates that the + special :data:`os.devnull` file will be used + + * *stdout* can be any of these: + + * a file-like object representing a pipe to be connected to the + subprocess's standard output stream using + :meth:`~loop.connect_write_pipe` + * the :const:`subprocess.PIPE` constant (default) which will create a new + pipe and connect it, + * the value ``None`` which will make the subprocess inherit the file + descriptor from this process + * the :const:`subprocess.DEVNULL` constant which indicates that the + special :data:`os.devnull` file will be used + + * *stderr* can be any of these: + + * a file-like object representing a pipe to be connected to the + subprocess's standard error stream using + :meth:`~loop.connect_write_pipe` + * the :const:`subprocess.PIPE` constant (default) which will create a new + pipe and connect it, + * the value ``None`` which will make the subprocess inherit the file + descriptor from this process + * the :const:`subprocess.DEVNULL` constant which indicates that the + special :data:`os.devnull` file will be used + * the :const:`subprocess.STDOUT` constant which will connect the standard + error stream to the process' standard output stream + + * All other keyword arguments are passed to :class:`subprocess.Popen` + without interpretation, except for *bufsize*, *universal_newlines*, + *shell*, *text*, *encoding* and *errors*, which should not be specified + at all. + + The ``asyncio`` subprocess API does not support decoding the streams + as text. :func:`bytes.decode` can be used to convert the bytes returned + from the stream to text. + + See the constructor of the :class:`subprocess.Popen` class + for documentation on other arguments. + + Returns a pair of ``(transport, protocol)``, where *transport* + conforms to the :class:`asyncio.SubprocessTransport` base class and + *protocol* is an object instantiated by the *protocol_factory*. + +.. coroutinemethod:: loop.subprocess_shell(protocol_factory, cmd, \*, \ + stdin=subprocess.PIPE, stdout=subprocess.PIPE, \ + stderr=subprocess.PIPE, \*\*kwargs) + + Create a subprocess from *cmd*, which can be a :class:`str` or a + :class:`bytes` string encoded to the + :ref:`filesystem encoding `, + using the platform's "shell" syntax. + + This is similar to the standard library :class:`subprocess.Popen` + class called with ``shell=True``. + + The *protocol_factory* must be a callable returning a subclass of the + :class:`SubprocessProtocol` class. + + See :meth:`~loop.subprocess_exec` for more details about + the remaining arguments. + + Returns a pair of ``(transport, protocol)``, where *transport* + conforms to the :class:`SubprocessTransport` base class and + *protocol* is an object instantiated by the *protocol_factory*. + +.. note:: + It is the application's responsibility to ensure that all whitespace + and special characters are quoted appropriately to avoid `shell injection + `_ + vulnerabilities. The :func:`shlex.quote` function can be used to + properly escape whitespace and special characters in strings that + are going to be used to construct shell commands. + + +Callback Handles +================ + +.. class:: Handle + + A callback wrapper object returned by :meth:`loop.call_soon`, + :meth:`loop.call_soon_threadsafe`. + + .. method:: cancel() + + Cancel the callback. If the callback has already been canceled + or executed, this method has no effect. + + .. method:: cancelled() + + Return ``True`` if the callback was cancelled. + + .. versionadded:: 3.7 + +.. class:: TimerHandle + + A callback wrapper object returned by :meth:`loop.call_later`, + and :meth:`loop.call_at`. + + This class is a subclass of :class:`Handle`. + + .. method:: when() + + Return a scheduled callback time as :class:`float` seconds. + + The time is an absolute timestamp, using the same time + reference as :meth:`loop.time`. + + .. versionadded:: 3.7 + + +Server Objects +============== + +Server objects are created by :meth:`loop.create_server`, +:meth:`loop.create_unix_server`, :func:`start_server`, +and :func:`start_unix_server` functions. + +Do not instantiate the class directly. + +.. class:: Server + + *Server* objects are asynchronous context managers. When used in an + ``async with`` statement, it's guaranteed that the Server object is + closed and not accepting new connections when the ``async with`` + statement is completed:: + + srv = await loop.create_server(...) + + async with srv: + # some code + + # At this point, srv is closed and no longer accepts new connections. + + + .. versionchanged:: 3.7 + Server object is an asynchronous context manager since Python 3.7. + + .. method:: close() + + Stop serving: close listening sockets and set the :attr:`sockets` + attribute to ``None``. + + The sockets that represent existing incoming client connections + are left open. + + The server is closed asynchronously, use the :meth:`wait_closed` + coroutine to wait until the server is closed. + + .. method:: get_loop() + + Return the event loop associated with the server object. + + .. versionadded:: 3.7 + + .. coroutinemethod:: start_serving() + + Start accepting connections. + + This method is idempotent, so it can be called when + the server is already being serving. + + The *start_serving* keyword-only parameter to + :meth:`loop.create_server` and + :meth:`asyncio.start_server` allows creating a Server object + that is not accepting connections initially. In this case + ``Server.start_serving()``, or :meth:`Server.serve_forever` can be used + to make the Server start accepting connections. + + .. versionadded:: 3.7 + + .. coroutinemethod:: serve_forever() + + Start accepting connections until the coroutine is cancelled. + Cancellation of ``serve_forever`` task causes the server + to be closed. + + This method can be called if the server is already accepting + connections. Only one ``serve_forever`` task can exist per + one *Server* object. + + Example:: + + async def client_connected(reader, writer): + # Communicate with the client with + # reader/writer streams. For example: + await reader.readline() + + async def main(host, port): + srv = await asyncio.start_server( + client_connected, host, port) + await srv.serve_forever() + + asyncio.run(main('127.0.0.1', 0)) + + .. versionadded:: 3.7 + + .. method:: is_serving() + + Return ``True`` if the server is accepting new connections. + + .. versionadded:: 3.7 + + .. coroutinemethod:: wait_closed() + + Wait until the :meth:`close` method completes. + + .. attribute:: sockets + + List of :class:`socket.socket` objects the server is listening on. + + .. versionchanged:: 3.7 + Prior to Python 3.7 ``Server.sockets`` used to return an + internal list of server sockets directly. In 3.7 a copy + of that list is returned. + + +.. _asyncio-event-loops: + +Event Loop Implementations +========================== + +asyncio ships with two different event loop implementations: +:class:`SelectorEventLoop` and :class:`ProactorEventLoop`. + +By default asyncio is configured to use :class:`SelectorEventLoop` +on Unix and :class:`ProactorEventLoop` on Windows. + + +.. class:: SelectorEventLoop + + An event loop based on the :mod:`selectors` module. + + Uses the most efficient *selector* available for the given + platform. It is also possible to manually configure the + exact selector implementation to be used:: + + import asyncio + import selectors + + selector = selectors.SelectSelector() + loop = asyncio.SelectorEventLoop(selector) + asyncio.set_event_loop(loop) + + + .. availability:: Unix, Windows. + + +.. class:: ProactorEventLoop + + An event loop for Windows that uses "I/O Completion Ports" (IOCP). + + .. availability:: Windows. + + .. seealso:: + + `MSDN documentation on I/O Completion Ports + `_. + + +.. class:: AbstractEventLoop + + Abstract base class for asyncio-compliant event loops. + + The :ref:`Event Loop Methods ` section lists all + methods that an alternative implementation of ``AbstractEventLoop`` + should have defined. + + +Examples +======== + +Note that all examples in this section **purposefully** show how +to use the low-level event loop APIs, such as :meth:`loop.run_forever` +and :meth:`loop.call_soon`. Modern asyncio applications rarely +need to be written this way; consider using the high-level functions +like :func:`asyncio.run`. + + +.. _asyncio_example_lowlevel_helloworld: + +Hello World with call_soon() +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +An example using the :meth:`loop.call_soon` method to schedule a +callback. The callback displays ``"Hello World"`` and then stops the +event loop:: + + import asyncio + + def hello_world(loop): + """A callback to print 'Hello World' and stop the event loop""" + print('Hello World') + loop.stop() + + loop = asyncio.get_event_loop() + + # Schedule a call to hello_world() + loop.call_soon(hello_world, loop) + + # Blocking call interrupted by loop.stop() + try: + loop.run_forever() + finally: + loop.close() + +.. seealso:: + + A similar :ref:`Hello World ` + example created with a coroutine and the :func:`run` function. + + +.. _asyncio_example_call_later: + +Display the current date with call_later() +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +An example of a callback displaying the current date every second. The +callback uses the :meth:`loop.call_later` method to reschedule itself +after 5 seconds, and then stops the event loop:: + + import asyncio + import datetime + + def display_date(end_time, loop): + print(datetime.datetime.now()) + if (loop.time() + 1.0) < end_time: + loop.call_later(1, display_date, end_time, loop) + else: + loop.stop() + + loop = asyncio.get_event_loop() + + # Schedule the first call to display_date() + end_time = loop.time() + 5.0 + loop.call_soon(display_date, end_time, loop) + + # Blocking call interrupted by loop.stop() + try: + loop.run_forever() + finally: + loop.close() + +.. seealso:: + + A similar :ref:`current date ` example + created with a coroutine and the :func:`run` function. + + +.. _asyncio_example_watch_fd: + +Watch a file descriptor for read events +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Wait until a file descriptor received some data using the +:meth:`loop.add_reader` method and then close the event loop:: + + import asyncio + from socket import socketpair + + # Create a pair of connected file descriptors + rsock, wsock = socketpair() + + loop = asyncio.get_event_loop() + + def reader(): + data = rsock.recv(100) + print("Received:", data.decode()) + + # We are done: unregister the file descriptor + loop.remove_reader(rsock) + + # Stop the event loop + loop.stop() + + # Register the file descriptor for read event + loop.add_reader(rsock, reader) + + # Simulate the reception of data from the network + loop.call_soon(wsock.send, 'abc'.encode()) + + try: + # Run the event loop + loop.run_forever() + finally: + # We are done. Close sockets and the event loop. + rsock.close() + wsock.close() + loop.close() + +.. seealso:: + + * A similar :ref:`example ` + using transports, protocols, and the + :meth:`loop.create_connection` method. + + * Another similar :ref:`example ` + using the high-level :func:`asyncio.open_connection` function + and streams. + + +.. _asyncio_example_unix_signals: + +Set signal handlers for SIGINT and SIGTERM +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +(This ``signals`` example only works on Unix.) + +Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM` +using the :meth:`loop.add_signal_handler` method:: + + import asyncio + import functools + import os + import signal + + def ask_exit(signame, loop): + print("got signal %s: exit" % signame) + loop.stop() + + async def main(): + loop = asyncio.get_running_loop() + + for signame in {'SIGINT', 'SIGTERM'}: + loop.add_signal_handler( + getattr(signal, signame), + functools.partial(ask_exit, signame, loop)) + + await asyncio.sleep(3600) + + print("Event loop running for 1 hour, press Ctrl+C to interrupt.") + print(f"pid {os.getpid()}: send SIGINT or SIGTERM to exit.") + + asyncio.run(main()) diff --git a/cpython_2/environment/repo/Doc/library/asyncio-exceptions.rst b/cpython_2/environment/repo/Doc/library/asyncio-exceptions.rst new file mode 100644 index 0000000000000000000000000000000000000000..7166d5c4bd88f9b155b6665ba0b512c28863b526 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/asyncio-exceptions.rst @@ -0,0 +1,77 @@ +.. currentmodule:: asyncio + + +.. _asyncio-exceptions: + +========== +Exceptions +========== + +**Source code:** :source:`Lib/asyncio/exceptions.py` + +---------------------------------------------------- + +.. exception:: TimeoutError + + The operation has exceeded the given deadline. + + .. important:: + This exception is different from the builtin :exc:`TimeoutError` + exception. + + +.. exception:: CancelledError + + The operation has been cancelled. + + This exception can be caught to perform custom operations + when asyncio Tasks are cancelled. In almost all situations the + exception must be re-raised. + + .. versionchanged:: 3.8 + + :exc:`CancelledError` is now a subclass of :class:`BaseException`. + + +.. exception:: InvalidStateError + + Invalid internal state of :class:`Task` or :class:`Future`. + + Can be raised in situations like setting a result value for a + *Future* object that already has a result value set. + + +.. exception:: SendfileNotAvailableError + + The "sendfile" syscall is not available for the given + socket or file type. + + A subclass of :exc:`RuntimeError`. + + +.. exception:: IncompleteReadError + + The requested read operation did not complete fully. + + Raised by the :ref:`asyncio stream APIs`. + + This exception is a subclass of :exc:`EOFError`. + + .. attribute:: expected + + The total number (:class:`int`) of expected bytes. + + .. attribute:: partial + + A string of :class:`bytes` read before the end of stream was reached. + + +.. exception:: LimitOverrunError + + Reached the buffer size limit while looking for a separator. + + Raised by the :ref:`asyncio stream APIs `. + + .. attribute:: consumed + + The total number of to be consumed bytes. diff --git a/cpython_2/environment/repo/Doc/library/asyncio-future.rst b/cpython_2/environment/repo/Doc/library/asyncio-future.rst new file mode 100644 index 0000000000000000000000000000000000000000..e1ac18eaf0988280290f79788dff2962e398e86e --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/asyncio-future.rst @@ -0,0 +1,263 @@ +.. currentmodule:: asyncio + + +.. _asyncio-futures: + +======= +Futures +======= + +**Source code:** :source:`Lib/asyncio/futures.py`, +:source:`Lib/asyncio/base_futures.py` + +------------------------------------- + +*Future* objects are used to bridge **low-level callback-based code** +with high-level async/await code. + + +Future Functions +================ + +.. function:: isfuture(obj) + + Return ``True`` if *obj* is either of: + + * an instance of :class:`asyncio.Future`, + * an instance of :class:`asyncio.Task`, + * a Future-like object with a ``_asyncio_future_blocking`` + attribute. + + .. versionadded:: 3.5 + + +.. function:: ensure_future(obj, \*, loop=None) + + Return: + + * *obj* argument as is, if *obj* is a :class:`Future`, + a :class:`Task`, or a Future-like object (:func:`isfuture` + is used for the test.) + + * a :class:`Task` object wrapping *obj*, if *obj* is a + coroutine (:func:`iscoroutine` is used for the test); + in this case the coroutine will be scheduled by + ``ensure_future()``. + + * a :class:`Task` object that would await on *obj*, if *obj* is an + awaitable (:func:`inspect.isawaitable` is used for the test.) + + If *obj* is neither of the above a :exc:`TypeError` is raised. + + .. important:: + + See also the :func:`create_task` function which is the + preferred way for creating new Tasks. + + .. versionchanged:: 3.5.1 + The function accepts any :term:`awaitable` object. + + +.. function:: wrap_future(future, \*, loop=None) + + Wrap a :class:`concurrent.futures.Future` object in a + :class:`asyncio.Future` object. + + +Future Object +============= + +.. class:: Future(\*, loop=None) + + A Future represents an eventual result of an asynchronous + operation. Not thread-safe. + + Future is an :term:`awaitable` object. Coroutines can await on + Future objects until they either have a result or an exception + set, or until they are cancelled. + + Typically Futures are used to enable low-level + callback-based code (e.g. in protocols implemented using asyncio + :ref:`transports `) + to interoperate with high-level async/await code. + + The rule of thumb is to never expose Future objects in user-facing + APIs, and the recommended way to create a Future object is to call + :meth:`loop.create_future`. This way alternative event loop + implementations can inject their own optimized implementations + of a Future object. + + .. versionchanged:: 3.7 + Added support for the :mod:`contextvars` module. + + .. method:: result() + + Return the result of the Future. + + If the Future is *done* and has a result set by the + :meth:`set_result` method, the result value is returned. + + If the Future is *done* and has an exception set by the + :meth:`set_exception` method, this method raises the exception. + + If the Future has been *cancelled*, this method raises + a :exc:`CancelledError` exception. + + If the Future's result isn't yet available, this method raises + a :exc:`InvalidStateError` exception. + + .. method:: set_result(result) + + Mark the Future as *done* and set its result. + + Raises a :exc:`InvalidStateError` error if the Future is + already *done*. + + .. method:: set_exception(exception) + + Mark the Future as *done* and set an exception. + + Raises a :exc:`InvalidStateError` error if the Future is + already *done*. + + .. method:: done() + + Return ``True`` if the Future is *done*. + + A Future is *done* if it was *cancelled* or if it has a result + or an exception set with :meth:`set_result` or + :meth:`set_exception` calls. + + .. method:: cancelled() + + Return ``True`` if the Future was *cancelled*. + + The method is usually used to check if a Future is not + *cancelled* before setting a result or an exception for it:: + + if not fut.cancelled(): + fut.set_result(42) + + .. method:: add_done_callback(callback, *, context=None) + + Add a callback to be run when the Future is *done*. + + The *callback* is called with the Future object as its only + argument. + + If the Future is already *done* when this method is called, + the callback is scheduled with :meth:`loop.call_soon`. + + An optional keyword-only *context* argument allows specifying a + custom :class:`contextvars.Context` for the *callback* to run in. + The current context is used when no *context* is provided. + + :func:`functools.partial` can be used to pass parameters + to the callback, e.g.:: + + # Call 'print("Future:", fut)' when "fut" is done. + fut.add_done_callback( + functools.partial(print, "Future:")) + + .. versionchanged:: 3.7 + The *context* keyword-only parameter was added. + See :pep:`567` for more details. + + .. method:: remove_done_callback(callback) + + Remove *callback* from the callbacks list. + + Returns the number of callbacks removed, which is typically 1, + unless a callback was added more than once. + + .. method:: cancel(msg=None) + + Cancel the Future and schedule callbacks. + + If the Future is already *done* or *cancelled*, return ``False``. + Otherwise, change the Future's state to *cancelled*, + schedule the callbacks, and return ``True``. + + .. versionchanged:: 3.9 + Added the ``msg`` parameter. + + .. method:: exception() + + Return the exception that was set on this Future. + + The exception (or ``None`` if no exception was set) is + returned only if the Future is *done*. + + If the Future has been *cancelled*, this method raises a + :exc:`CancelledError` exception. + + If the Future isn't *done* yet, this method raises an + :exc:`InvalidStateError` exception. + + .. method:: get_loop() + + Return the event loop the Future object is bound to. + + .. versionadded:: 3.7 + + +.. _asyncio_example_future: + +This example creates a Future object, creates and schedules an +asynchronous Task to set result for the Future, and waits until +the Future has a result:: + + async def set_after(fut, delay, value): + # Sleep for *delay* seconds. + await asyncio.sleep(delay) + + # Set *value* as a result of *fut* Future. + fut.set_result(value) + + async def main(): + # Get the current event loop. + loop = asyncio.get_running_loop() + + # Create a new Future object. + fut = loop.create_future() + + # Run "set_after()" coroutine in a parallel Task. + # We are using the low-level "loop.create_task()" API here because + # we already have a reference to the event loop at hand. + # Otherwise we could have just used "asyncio.create_task()". + loop.create_task( + set_after(fut, 1, '... world')) + + print('hello ...') + + # Wait until *fut* has a result (1 second) and print it. + print(await fut) + + asyncio.run(main()) + + +.. important:: + + The Future object was designed to mimic + :class:`concurrent.futures.Future`. Key differences include: + + - unlike asyncio Futures, :class:`concurrent.futures.Future` + instances cannot be awaited. + + - :meth:`asyncio.Future.result` and :meth:`asyncio.Future.exception` + do not accept the *timeout* argument. + + - :meth:`asyncio.Future.result` and :meth:`asyncio.Future.exception` + raise an :exc:`InvalidStateError` exception when the Future is not + *done*. + + - Callbacks registered with :meth:`asyncio.Future.add_done_callback` + are not called immediately. They are scheduled with + :meth:`loop.call_soon` instead. + + - asyncio Future is not compatible with the + :func:`concurrent.futures.wait` and + :func:`concurrent.futures.as_completed` functions. + + - :meth:`asyncio.Future.cancel` accepts an optional ``msg`` argument, + but :func:`concurrent.futures.cancel` does not. diff --git a/cpython_2/environment/repo/Doc/library/asyncio-llapi-index.rst b/cpython_2/environment/repo/Doc/library/asyncio-llapi-index.rst new file mode 100644 index 0000000000000000000000000000000000000000..0ab322af6dc72da6ccf63da0c10927821029a823 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/asyncio-llapi-index.rst @@ -0,0 +1,510 @@ +.. currentmodule:: asyncio + + +=================== +Low-level API Index +=================== + +This page lists all low-level asyncio APIs. + + +Obtaining the Event Loop +======================== + +.. list-table:: + :widths: 50 50 + :class: full-width-table + + * - :func:`asyncio.get_running_loop` + - The **preferred** function to get the running event loop. + + * - :func:`asyncio.get_event_loop` + - Get an event loop instance (current or via the policy). + + * - :func:`asyncio.set_event_loop` + - Set the event loop as current via the current policy. + + * - :func:`asyncio.new_event_loop` + - Create a new event loop. + + +.. rubric:: Examples + +* :ref:`Using asyncio.get_running_loop() `. + + +Event Loop Methods +================== + +See also the main documentation section about the +:ref:`event loop methods `. + +.. rubric:: Lifecycle +.. list-table:: + :widths: 50 50 + :class: full-width-table + + * - :meth:`loop.run_until_complete` + - Run a Future/Task/awaitable until complete. + + * - :meth:`loop.run_forever` + - Run the event loop forever. + + * - :meth:`loop.stop` + - Stop the event loop. + + * - :meth:`loop.close` + - Close the event loop. + + * - :meth:`loop.is_running()` + - Return ``True`` if the event loop is running. + + * - :meth:`loop.is_closed()` + - Return ``True`` if the event loop is closed. + + * - ``await`` :meth:`loop.shutdown_asyncgens` + - Close asynchronous generators. + + +.. rubric:: Debugging +.. list-table:: + :widths: 50 50 + :class: full-width-table + + * - :meth:`loop.set_debug` + - Enable or disable the debug mode. + + * - :meth:`loop.get_debug` + - Get the current debug mode. + + +.. rubric:: Scheduling Callbacks +.. list-table:: + :widths: 50 50 + :class: full-width-table + + * - :meth:`loop.call_soon` + - Invoke a callback soon. + + * - :meth:`loop.call_soon_threadsafe` + - A thread-safe variant of :meth:`loop.call_soon`. + + * - :meth:`loop.call_later` + - Invoke a callback *after* the given time. + + * - :meth:`loop.call_at` + - Invoke a callback *at* the given time. + + +.. rubric:: Thread/Process Pool +.. list-table:: + :widths: 50 50 + :class: full-width-table + + * - ``await`` :meth:`loop.run_in_executor` + - Run a CPU-bound or other blocking function in + a :mod:`concurrent.futures` executor. + + * - :meth:`loop.set_default_executor` + - Set the default executor for :meth:`loop.run_in_executor`. + + +.. rubric:: Tasks and Futures +.. list-table:: + :widths: 50 50 + :class: full-width-table + + * - :meth:`loop.create_future` + - Create a :class:`Future` object. + + * - :meth:`loop.create_task` + - Schedule coroutine as a :class:`Task`. + + * - :meth:`loop.set_task_factory` + - Set a factory used by :meth:`loop.create_task` to + create :class:`Tasks `. + + * - :meth:`loop.get_task_factory` + - Get the factory :meth:`loop.create_task` uses + to create :class:`Tasks `. + + +.. rubric:: DNS +.. list-table:: + :widths: 50 50 + :class: full-width-table + + * - ``await`` :meth:`loop.getaddrinfo` + - Asynchronous version of :meth:`socket.getaddrinfo`. + + * - ``await`` :meth:`loop.getnameinfo` + - Asynchronous version of :meth:`socket.getnameinfo`. + + +.. rubric:: Networking and IPC +.. list-table:: + :widths: 50 50 + :class: full-width-table + + * - ``await`` :meth:`loop.create_connection` + - Open a TCP connection. + + * - ``await`` :meth:`loop.create_server` + - Create a TCP server. + + * - ``await`` :meth:`loop.create_unix_connection` + - Open a Unix socket connection. + + * - ``await`` :meth:`loop.create_unix_server` + - Create a Unix socket server. + + * - ``await`` :meth:`loop.connect_accepted_socket` + - Wrap a :class:`~socket.socket` into a ``(transport, protocol)`` + pair. + + * - ``await`` :meth:`loop.create_datagram_endpoint` + - Open a datagram (UDP) connection. + + * - ``await`` :meth:`loop.sendfile` + - Send a file over a transport. + + * - ``await`` :meth:`loop.start_tls` + - Upgrade an existing connection to TLS. + + * - ``await`` :meth:`loop.connect_read_pipe` + - Wrap a read end of a pipe into a ``(transport, protocol)`` pair. + + * - ``await`` :meth:`loop.connect_write_pipe` + - Wrap a write end of a pipe into a ``(transport, protocol)`` pair. + + +.. rubric:: Sockets +.. list-table:: + :widths: 50 50 + :class: full-width-table + + * - ``await`` :meth:`loop.sock_recv` + - Receive data from the :class:`~socket.socket`. + + * - ``await`` :meth:`loop.sock_recv_into` + - Receive data from the :class:`~socket.socket` into a buffer. + + * - ``await`` :meth:`loop.sock_sendall` + - Send data to the :class:`~socket.socket`. + + * - ``await`` :meth:`loop.sock_connect` + - Connect the :class:`~socket.socket`. + + * - ``await`` :meth:`loop.sock_accept` + - Accept a :class:`~socket.socket` connection. + + * - ``await`` :meth:`loop.sock_sendfile` + - Send a file over the :class:`~socket.socket`. + + * - :meth:`loop.add_reader` + - Start watching a file descriptor for read availability. + + * - :meth:`loop.remove_reader` + - Stop watching a file descriptor for read availability. + + * - :meth:`loop.add_writer` + - Start watching a file descriptor for write availability. + + * - :meth:`loop.remove_writer` + - Stop watching a file descriptor for write availability. + + +.. rubric:: Unix Signals +.. list-table:: + :widths: 50 50 + :class: full-width-table + + * - :meth:`loop.add_signal_handler` + - Add a handler for a :mod:`signal`. + + * - :meth:`loop.remove_signal_handler` + - Remove a handler for a :mod:`signal`. + + +.. rubric:: Subprocesses +.. list-table:: + :widths: 50 50 + :class: full-width-table + + * - :meth:`loop.subprocess_exec` + - Spawn a subprocess. + + * - :meth:`loop.subprocess_shell` + - Spawn a subprocess from a shell command. + + +.. rubric:: Error Handling +.. list-table:: + :widths: 50 50 + :class: full-width-table + + * - :meth:`loop.call_exception_handler` + - Call the exception handler. + + * - :meth:`loop.set_exception_handler` + - Set a new exception handler. + + * - :meth:`loop.get_exception_handler` + - Get the current exception handler. + + * - :meth:`loop.default_exception_handler` + - The default exception handler implementation. + + +.. rubric:: Examples + +* :ref:`Using asyncio.get_event_loop() and loop.run_forever() + `. + +* :ref:`Using loop.call_later() `. + +* Using ``loop.create_connection()`` to implement + :ref:`an echo-client `. + +* Using ``loop.create_connection()`` to + :ref:`connect a socket `. + +* :ref:`Using add_reader() to watch an FD for read events + `. + +* :ref:`Using loop.add_signal_handler() `. + +* :ref:`Using loop.subprocess_exec() `. + + +Transports +========== + +All transports implement the following methods: + +.. list-table:: + :widths: 50 50 + :class: full-width-table + + * - :meth:`transport.close() ` + - Close the transport. + + * - :meth:`transport.is_closing() ` + - Return ``True`` if the transport is closing or is closed. + + * - :meth:`transport.get_extra_info() ` + - Request for information about the transport. + + * - :meth:`transport.set_protocol() ` + - Set a new protocol. + + * - :meth:`transport.get_protocol() ` + - Return the current protocol. + + +Transports that can receive data (TCP and Unix connections, +pipes, etc). Returned from methods like +:meth:`loop.create_connection`, :meth:`loop.create_unix_connection`, +:meth:`loop.connect_read_pipe`, etc: + +.. rubric:: Read Transports +.. list-table:: + :widths: 50 50 + :class: full-width-table + + * - :meth:`transport.is_reading() ` + - Return ``True`` if the transport is receiving. + + * - :meth:`transport.pause_reading() ` + - Pause receiving. + + * - :meth:`transport.resume_reading() ` + - Resume receiving. + + +Transports that can Send data (TCP and Unix connections, +pipes, etc). Returned from methods like +:meth:`loop.create_connection`, :meth:`loop.create_unix_connection`, +:meth:`loop.connect_write_pipe`, etc: + +.. rubric:: Write Transports +.. list-table:: + :widths: 50 50 + :class: full-width-table + + * - :meth:`transport.write() ` + - Write data to the transport. + + * - :meth:`transport.writelines() ` + - Write buffers to the transport. + + * - :meth:`transport.can_write_eof() ` + - Return :const:`True` if the transport supports sending EOF. + + * - :meth:`transport.write_eof() ` + - Close and send EOF after flushing buffered data. + + * - :meth:`transport.abort() ` + - Close the transport immediately. + + * - :meth:`transport.get_write_buffer_size() + ` + - Return high and low water marks for write flow control. + + * - :meth:`transport.set_write_buffer_limits() + ` + - Set new high and low water marks for write flow control. + + +Transports returned by :meth:`loop.create_datagram_endpoint`: + +.. rubric:: Datagram Transports +.. list-table:: + :widths: 50 50 + :class: full-width-table + + * - :meth:`transport.sendto() ` + - Send data to the remote peer. + + * - :meth:`transport.abort() ` + - Close the transport immediately. + + +Low-level transport abstraction over subprocesses. +Returned by :meth:`loop.subprocess_exec` and +:meth:`loop.subprocess_shell`: + +.. rubric:: Subprocess Transports +.. list-table:: + :widths: 50 50 + :class: full-width-table + + * - :meth:`transport.get_pid() ` + - Return the subprocess process id. + + * - :meth:`transport.get_pipe_transport() + ` + - Return the transport for the requested communication pipe + (*stdin*, *stdout*, or *stderr*). + + * - :meth:`transport.get_returncode() ` + - Return the subprocess return code. + + * - :meth:`transport.kill() ` + - Kill the subprocess. + + * - :meth:`transport.send_signal() ` + - Send a signal to the subprocess. + + * - :meth:`transport.terminate() ` + - Stop the subprocess. + + * - :meth:`transport.close() ` + - Kill the subprocess and close all pipes. + + +Protocols +========= + +Protocol classes can implement the following **callback methods**: + +.. list-table:: + :widths: 50 50 + :class: full-width-table + + * - ``callback`` :meth:`connection_made() ` + - Called when a connection is made. + + * - ``callback`` :meth:`connection_lost() ` + - Called when the connection is lost or closed. + + * - ``callback`` :meth:`pause_writing() ` + - Called when the transport's buffer goes over the high water mark. + + * - ``callback`` :meth:`resume_writing() ` + - Called when the transport's buffer drains below the low water mark. + + +.. rubric:: Streaming Protocols (TCP, Unix Sockets, Pipes) +.. list-table:: + :widths: 50 50 + :class: full-width-table + + * - ``callback`` :meth:`data_received() ` + - Called when some data is received. + + * - ``callback`` :meth:`eof_received() ` + - Called when an EOF is received. + + +.. rubric:: Buffered Streaming Protocols +.. list-table:: + :widths: 50 50 + :class: full-width-table + + * - ``callback`` :meth:`get_buffer() ` + - Called to allocate a new receive buffer. + + * - ``callback`` :meth:`buffer_updated() ` + - Called when the buffer was updated with the received data. + + * - ``callback`` :meth:`eof_received() ` + - Called when an EOF is received. + + +.. rubric:: Datagram Protocols +.. list-table:: + :widths: 50 50 + :class: full-width-table + + * - ``callback`` :meth:`datagram_received() + ` + - Called when a datagram is received. + + * - ``callback`` :meth:`error_received() ` + - Called when a previous send or receive operation raises an + :class:`OSError`. + + +.. rubric:: Subprocess Protocols +.. list-table:: + :widths: 50 50 + :class: full-width-table + + * - ``callback`` :meth:`pipe_data_received() + ` + - Called when the child process writes data into its + *stdout* or *stderr* pipe. + + * - ``callback`` :meth:`pipe_connection_lost() + ` + - Called when one of the pipes communicating with + the child process is closed. + + * - ``callback`` :meth:`process_exited() + ` + - Called when the child process has exited. + + +Event Loop Policies +=================== + +Policies is a low-level mechanism to alter the behavior of +functions like :func:`asyncio.get_event_loop`. See also +the main :ref:`policies section ` for more +details. + + +.. rubric:: Accessing Policies +.. list-table:: + :widths: 50 50 + :class: full-width-table + + * - :meth:`asyncio.get_event_loop_policy` + - Return the current process-wide policy. + + * - :meth:`asyncio.set_event_loop_policy` + - Set a new process-wide policy. + + * - :class:`AbstractEventLoopPolicy` + - Base class for policy objects. diff --git a/cpython_2/environment/repo/Doc/library/asyncio-platforms.rst b/cpython_2/environment/repo/Doc/library/asyncio-platforms.rst new file mode 100644 index 0000000000000000000000000000000000000000..390ee1969d096f4109a6e127b9c0cc1714ac285c --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/asyncio-platforms.rst @@ -0,0 +1,105 @@ +.. currentmodule:: asyncio + + +.. _asyncio-platform-support: + + +================ +Platform Support +================ + +The :mod:`asyncio` module is designed to be portable, +but some platforms have subtle differences and limitations +due to the platforms' underlying architecture and capabilities. + + +All Platforms +============= + +* :meth:`loop.add_reader` and :meth:`loop.add_writer` + cannot be used to monitor file I/O. + + +Windows +======= + +**Source code:** :source:`Lib/asyncio/proactor_events.py`, +:source:`Lib/asyncio/windows_events.py`, +:source:`Lib/asyncio/windows_utils.py` + +-------------------------------------- + +.. versionchanged:: 3.8 + + On Windows, :class:`ProactorEventLoop` is now the default event loop. + +All event loops on Windows do not support the following methods: + +* :meth:`loop.create_unix_connection` and + :meth:`loop.create_unix_server` are not supported. + The :data:`socket.AF_UNIX` socket family is specific to Unix. + +* :meth:`loop.add_signal_handler` and + :meth:`loop.remove_signal_handler` are not supported. + +:class:`SelectorEventLoop` has the following limitations: + +* :class:`~selectors.SelectSelector` is used to wait on socket events: + it supports sockets and is limited to 512 sockets. + +* :meth:`loop.add_reader` and :meth:`loop.add_writer` only accept + socket handles (e.g. pipe file descriptors are not supported). + +* Pipes are not supported, so the :meth:`loop.connect_read_pipe` + and :meth:`loop.connect_write_pipe` methods are not implemented. + +* :ref:`Subprocesses ` are not supported, i.e. + :meth:`loop.subprocess_exec` and :meth:`loop.subprocess_shell` + methods are not implemented. + +:class:`ProactorEventLoop` has the following limitations: + +* The :meth:`loop.add_reader` and :meth:`loop.add_writer` + methods are not supported. + +The resolution of the monotonic clock on Windows is usually around 15.6 +msec. The best resolution is 0.5 msec. The resolution depends on the +hardware (availability of `HPET +`_) and on the +Windows configuration. + + +.. _asyncio-windows-subprocess: + +Subprocess Support on Windows +----------------------------- + +On Windows, the default event loop :class:`ProactorEventLoop` supports +subprocesses, whereas :class:`SelectorEventLoop` does not. + +The :meth:`policy.set_child_watcher() +` function is also +not supported, as :class:`ProactorEventLoop` has a different mechanism +to watch child processes. + + +macOS +===== + +Modern macOS versions are fully supported. + +.. rubric:: macOS <= 10.8 + +On macOS 10.6, 10.7 and 10.8, the default event loop +uses :class:`selectors.KqueueSelector`, which does not support +character devices on these versions. The :class:`SelectorEventLoop` +can be manually configured to use :class:`~selectors.SelectSelector` +or :class:`~selectors.PollSelector` to support character devices on +these older versions of macOS. Example:: + + import asyncio + import selectors + + selector = selectors.SelectSelector() + loop = asyncio.SelectorEventLoop(selector) + asyncio.set_event_loop(loop) diff --git a/cpython_2/environment/repo/Doc/library/asyncio-policy.rst b/cpython_2/environment/repo/Doc/library/asyncio-policy.rst new file mode 100644 index 0000000000000000000000000000000000000000..d9d3232d2408b38132031b3d083517ec7c77e084 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/asyncio-policy.rst @@ -0,0 +1,291 @@ +.. currentmodule:: asyncio + + +.. _asyncio-policies: + +======== +Policies +======== + +An event loop policy is a global per-process object that controls +the management of the event loop. Each event loop has a default +policy, which can be changed and customized using the policy API. + +A policy defines the notion of *context* and manages a +separate event loop per context. The default policy +defines *context* to be the current thread. + +By using a custom event loop policy, the behavior of +:func:`get_event_loop`, :func:`set_event_loop`, and +:func:`new_event_loop` functions can be customized. + +Policy objects should implement the APIs defined +in the :class:`AbstractEventLoopPolicy` abstract base class. + + +Getting and Setting the Policy +============================== + +The following functions can be used to get and set the policy +for the current process: + +.. function:: get_event_loop_policy() + + Return the current process-wide policy. + +.. function:: set_event_loop_policy(policy) + + Set the current process-wide policy to *policy*. + + If *policy* is set to ``None``, the default policy is restored. + + +Policy Objects +============== + +The abstract event loop policy base class is defined as follows: + +.. class:: AbstractEventLoopPolicy + + An abstract base class for asyncio policies. + + .. method:: get_event_loop() + + Get the event loop for the current context. + + Return an event loop object implementing the + :class:`AbstractEventLoop` interface. + + This method should never return ``None``. + + .. versionchanged:: 3.6 + + .. method:: set_event_loop(loop) + + Set the event loop for the current context to *loop*. + + .. method:: new_event_loop() + + Create and return a new event loop object. + + This method should never return ``None``. + + .. method:: get_child_watcher() + + Get a child process watcher object. + + Return a watcher object implementing the + :class:`AbstractChildWatcher` interface. + + This function is Unix specific. + + .. method:: set_child_watcher(watcher) + + Set the current child process watcher to *watcher*. + + This function is Unix specific. + + +asyncio ships with the following built-in policies: + + +.. class:: DefaultEventLoopPolicy + + The default asyncio policy. Uses :class:`SelectorEventLoop` + on Unix and :class:`ProactorEventLoop` on Windows. + + There is no need to install the default policy manually. asyncio + is configured to use the default policy automatically. + + .. versionchanged:: 3.8 + + On Windows, :class:`ProactorEventLoop` is now used by default. + + +.. class:: WindowsSelectorEventLoopPolicy + + An alternative event loop policy that uses the + :class:`SelectorEventLoop` event loop implementation. + + .. availability:: Windows. + + +.. class:: WindowsProactorEventLoopPolicy + + An alternative event loop policy that uses the + :class:`ProactorEventLoop` event loop implementation. + + .. availability:: Windows. + +.. _asyncio-watchers: + +Process Watchers +================ + +A process watcher allows customization of how an event loop monitors +child processes on Unix. Specifically, the event loop needs to know +when a child process has exited. + +In asyncio, child processes are created with +:func:`create_subprocess_exec` and :meth:`loop.subprocess_exec` +functions. + +asyncio defines the :class:`AbstractChildWatcher` abstract base class, which child +watchers should implement, and has four different implementations: +:class:`ThreadedChildWatcher` (configured to be used by default), +:class:`MultiLoopChildWatcher`, :class:`SafeChildWatcher`, and +:class:`FastChildWatcher`. + +See also the :ref:`Subprocess and Threads ` +section. + +The following two functions can be used to customize the child process watcher +implementation used by the asyncio event loop: + +.. function:: get_child_watcher() + + Return the current child watcher for the current policy. + +.. function:: set_child_watcher(watcher) + + Set the current child watcher to *watcher* for the current + policy. *watcher* must implement methods defined in the + :class:`AbstractChildWatcher` base class. + +.. note:: + Third-party event loops implementations might not support + custom child watchers. For such event loops, using + :func:`set_child_watcher` might be prohibited or have no effect. + +.. class:: AbstractChildWatcher + + .. method:: add_child_handler(pid, callback, \*args) + + Register a new child handler. + + Arrange for ``callback(pid, returncode, *args)`` to be called + when a process with PID equal to *pid* terminates. Specifying + another callback for the same process replaces the previous + handler. + + The *callback* callable must be thread-safe. + + .. method:: remove_child_handler(pid) + + Removes the handler for process with PID equal to *pid*. + + The function returns ``True`` if the handler was successfully + removed, ``False`` if there was nothing to remove. + + .. method:: attach_loop(loop) + + Attach the watcher to an event loop. + + If the watcher was previously attached to an event loop, then + it is first detached before attaching to the new loop. + + Note: loop may be ``None``. + + .. method:: is_active() + + Return ``True`` if the watcher is ready to use. + + Spawning a subprocess with *inactive* current child watcher raises + :exc:`RuntimeError`. + + .. versionadded:: 3.8 + + .. method:: close() + + Close the watcher. + + This method has to be called to ensure that underlying + resources are cleaned-up. + +.. class:: ThreadedChildWatcher + + This implementation starts a new waiting thread for every subprocess spawn. + + It works reliably even when the asyncio event loop is run in a non-main OS thread. + + There is no noticeable overhead when handling a big number of children (*O(1)* each + time a child terminates), but stating a thread per process requires extra memory. + + This watcher is used by default. + + .. versionadded:: 3.8 + +.. class:: MultiLoopChildWatcher + + This implementation registers a :py:data:`SIGCHLD` signal handler on + instantiation. That can break third-party code that installs a custom handler for + `SIGCHLD`. signal). + + The watcher avoids disrupting other code spawning processes + by polling every process explicitly on a :py:data:`SIGCHLD` signal. + + There is no limitation for running subprocesses from different threads once the + watcher is installed. + + The solution is safe but it has a significant overhead when + handling a big number of processes (*O(n)* each time a + :py:data:`SIGCHLD` is received). + + .. versionadded:: 3.8 + +.. class:: SafeChildWatcher + + This implementation uses active event loop from the main thread to handle + :py:data:`SIGCHLD` signal. If the main thread has no running event loop another + thread cannot spawn a subprocess (:exc:`RuntimeError` is raised). + + The watcher avoids disrupting other code spawning processes + by polling every process explicitly on a :py:data:`SIGCHLD` signal. + + This solution is as safe as :class:`MultiLoopChildWatcher` and has the same *O(N)* + complexity but requires a running event loop in the main thread to work. + +.. class:: FastChildWatcher + + This implementation reaps every terminated processes by calling + ``os.waitpid(-1)`` directly, possibly breaking other code spawning + processes and waiting for their termination. + + There is no noticeable overhead when handling a big number of + children (*O(1)* each time a child terminates). + + This solution requires a running event loop in the main thread to work, as + :class:`SafeChildWatcher`. + +.. class:: PidfdChildWatcher + + This implementation polls process file descriptors (pidfds) to await child + process termination. In some respects, :class:`PidfdChildWatcher` is a + "Goldilocks" child watcher implementation. It doesn't require signals or + threads, doesn't interfere with any processes launched outside the event + loop, and scales linearly with the number of subprocesses launched by the + event loop. The main disadvantage is that pidfds are specific to Linux, and + only work on recent (5.3+) kernels. + + .. versionadded:: 3.9 + + +Custom Policies +=============== + +To implement a new event loop policy, it is recommended to subclass +:class:`DefaultEventLoopPolicy` and override the methods for which +custom behavior is wanted, e.g.:: + + class MyEventLoopPolicy(asyncio.DefaultEventLoopPolicy): + + def get_event_loop(self): + """Get the event loop. + + This may be None or an instance of EventLoop. + """ + loop = super().get_event_loop() + # Do something with loop ... + return loop + + asyncio.set_event_loop_policy(MyEventLoopPolicy()) diff --git a/cpython_2/environment/repo/Doc/library/asyncio-protocol.rst b/cpython_2/environment/repo/Doc/library/asyncio-protocol.rst new file mode 100644 index 0000000000000000000000000000000000000000..3079716f03ecc0bd7852f99cdf094c30084fdfbd --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/asyncio-protocol.rst @@ -0,0 +1,1043 @@ +.. currentmodule:: asyncio + + +.. _asyncio-transports-protocols: + + +======================== +Transports and Protocols +======================== + +.. rubric:: Preface + +Transports and Protocols are used by the **low-level** event loop +APIs such as :meth:`loop.create_connection`. They use +callback-based programming style and enable high-performance +implementations of network or IPC protocols (e.g. HTTP). + +Essentially, transports and protocols should only be used in +libraries and frameworks and never in high-level asyncio +applications. + +This documentation page covers both `Transports`_ and `Protocols`_. + +.. rubric:: Introduction + +At the highest level, the transport is concerned with *how* bytes +are transmitted, while the protocol determines *which* bytes to +transmit (and to some extent when). + +A different way of saying the same thing: a transport is an +abstraction for a socket (or similar I/O endpoint) while a protocol +is an abstraction for an application, from the transport's point +of view. + +Yet another view is the transport and protocol interfaces +together define an abstract interface for using network I/O and +interprocess I/O. + +There is always a 1:1 relationship between transport and protocol +objects: the protocol calls transport methods to send data, +while the transport calls protocol methods to pass it data that +has been received. + +Most of connection oriented event loop methods +(such as :meth:`loop.create_connection`) usually accept a +*protocol_factory* argument used to create a *Protocol* object +for an accepted connection, represented by a *Transport* object. +Such methods usually return a tuple of ``(transport, protocol)``. + +.. rubric:: Contents + +This documentation page contains the following sections: + +* The `Transports`_ section documents asyncio :class:`BaseTransport`, + :class:`ReadTransport`, :class:`WriteTransport`, :class:`Transport`, + :class:`DatagramTransport`, and :class:`SubprocessTransport` + classes. + +* The `Protocols`_ section documents asyncio :class:`BaseProtocol`, + :class:`Protocol`, :class:`BufferedProtocol`, + :class:`DatagramProtocol`, and :class:`SubprocessProtocol` classes. + +* The `Examples`_ section showcases how to work with transports, + protocols, and low-level event loop APIs. + + +.. _asyncio-transport: + +Transports +========== + +**Source code:** :source:`Lib/asyncio/transports.py` + +---------------------------------------------------- + +Transports are classes provided by :mod:`asyncio` in order to abstract +various kinds of communication channels. + +Transport objects are always instantiated by an +:ref:`asyncio event loop `. + +asyncio implements transports for TCP, UDP, SSL, and subprocess pipes. +The methods available on a transport depend on the transport's kind. + +The transport classes are :ref:`not thread safe `. + + +Transports Hierarchy +-------------------- + +.. class:: BaseTransport + + Base class for all transports. Contains methods that all + asyncio transports share. + +.. class:: WriteTransport(BaseTransport) + + A base transport for write-only connections. + + Instances of the *WriteTransport* class are returned from + the :meth:`loop.connect_write_pipe` event loop method and + are also used by subprocess-related methods like + :meth:`loop.subprocess_exec`. + +.. class:: ReadTransport(BaseTransport) + + A base transport for read-only connections. + + Instances of the *ReadTransport* class are returned from + the :meth:`loop.connect_read_pipe` event loop method and + are also used by subprocess-related methods like + :meth:`loop.subprocess_exec`. + +.. class:: Transport(WriteTransport, ReadTransport) + + Interface representing a bidirectional transport, such as a + TCP connection. + + The user does not instantiate a transport directly; they call a + utility function, passing it a protocol factory and other + information necessary to create the transport and protocol. + + Instances of the *Transport* class are returned from or used by + event loop methods like :meth:`loop.create_connection`, + :meth:`loop.create_unix_connection`, + :meth:`loop.create_server`, :meth:`loop.sendfile`, etc. + + +.. class:: DatagramTransport(BaseTransport) + + A transport for datagram (UDP) connections. + + Instances of the *DatagramTransport* class are returned from + the :meth:`loop.create_datagram_endpoint` event loop method. + + +.. class:: SubprocessTransport(BaseTransport) + + An abstraction to represent a connection between a parent and its + child OS process. + + Instances of the *SubprocessTransport* class are returned from + event loop methods :meth:`loop.subprocess_shell` and + :meth:`loop.subprocess_exec`. + + +Base Transport +-------------- + +.. method:: BaseTransport.close() + + Close the transport. + + If the transport has a buffer for outgoing + data, buffered data will be flushed asynchronously. No more data + will be received. After all buffered data is flushed, the + protocol's :meth:`protocol.connection_lost() + ` method will be called with + :const:`None` as its argument. + +.. method:: BaseTransport.is_closing() + + Return ``True`` if the transport is closing or is closed. + +.. method:: BaseTransport.get_extra_info(name, default=None) + + Return information about the transport or underlying resources + it uses. + + *name* is a string representing the piece of transport-specific + information to get. + + *default* is the value to return if the information is not + available, or if the transport does not support querying it + with the given third-party event loop implementation or on the + current platform. + + For example, the following code attempts to get the underlying + socket object of the transport:: + + sock = transport.get_extra_info('socket') + if sock is not None: + print(sock.getsockopt(...)) + + Categories of information that can be queried on some transports: + + * socket: + + - ``'peername'``: the remote address to which the socket is + connected, result of :meth:`socket.socket.getpeername` + (``None`` on error) + + - ``'socket'``: :class:`socket.socket` instance + + - ``'sockname'``: the socket's own address, + result of :meth:`socket.socket.getsockname` + + * SSL socket: + + - ``'compression'``: the compression algorithm being used as a + string, or ``None`` if the connection isn't compressed; result + of :meth:`ssl.SSLSocket.compression` + + - ``'cipher'``: a three-value tuple containing the name of the + cipher being used, the version of the SSL protocol that defines + its use, and the number of secret bits being used; result of + :meth:`ssl.SSLSocket.cipher` + + - ``'peercert'``: peer certificate; result of + :meth:`ssl.SSLSocket.getpeercert` + + - ``'sslcontext'``: :class:`ssl.SSLContext` instance + + - ``'ssl_object'``: :class:`ssl.SSLObject` or + :class:`ssl.SSLSocket` instance + + * pipe: + + - ``'pipe'``: pipe object + + * subprocess: + + - ``'subprocess'``: :class:`subprocess.Popen` instance + +.. method:: BaseTransport.set_protocol(protocol) + + Set a new protocol. + + Switching protocol should only be done when both + protocols are documented to support the switch. + +.. method:: BaseTransport.get_protocol() + + Return the current protocol. + + +Read-only Transports +-------------------- + +.. method:: ReadTransport.is_reading() + + Return ``True`` if the transport is receiving new data. + + .. versionadded:: 3.7 + +.. method:: ReadTransport.pause_reading() + + Pause the receiving end of the transport. No data will be passed to + the protocol's :meth:`protocol.data_received() ` + method until :meth:`resume_reading` is called. + + .. versionchanged:: 3.7 + The method is idempotent, i.e. it can be called when the + transport is already paused or closed. + +.. method:: ReadTransport.resume_reading() + + Resume the receiving end. The protocol's + :meth:`protocol.data_received() ` method + will be called once again if some data is available for reading. + + .. versionchanged:: 3.7 + The method is idempotent, i.e. it can be called when the + transport is already reading. + + +Write-only Transports +--------------------- + +.. method:: WriteTransport.abort() + + Close the transport immediately, without waiting for pending operations + to complete. Buffered data will be lost. No more data will be received. + The protocol's :meth:`protocol.connection_lost() + ` method will eventually be + called with :const:`None` as its argument. + +.. method:: WriteTransport.can_write_eof() + + Return :const:`True` if the transport supports + :meth:`~WriteTransport.write_eof`, :const:`False` if not. + +.. method:: WriteTransport.get_write_buffer_size() + + Return the current size of the output buffer used by the transport. + +.. method:: WriteTransport.get_write_buffer_limits() + + Get the *high* and *low* watermarks for write flow control. Return a + tuple ``(low, high)`` where *low* and *high* are positive number of + bytes. + + Use :meth:`set_write_buffer_limits` to set the limits. + + .. versionadded:: 3.4.2 + +.. method:: WriteTransport.set_write_buffer_limits(high=None, low=None) + + Set the *high* and *low* watermarks for write flow control. + + These two values (measured in number of + bytes) control when the protocol's + :meth:`protocol.pause_writing() ` + and :meth:`protocol.resume_writing() ` + methods are called. If specified, the low watermark must be less + than or equal to the high watermark. Neither *high* nor *low* + can be negative. + + :meth:`~BaseProtocol.pause_writing` is called when the buffer size + becomes greater than or equal to the *high* value. If writing has + been paused, :meth:`~BaseProtocol.resume_writing` is called when + the buffer size becomes less than or equal to the *low* value. + + The defaults are implementation-specific. If only the + high watermark is given, the low watermark defaults to an + implementation-specific value less than or equal to the + high watermark. Setting *high* to zero forces *low* to zero as + well, and causes :meth:`~BaseProtocol.pause_writing` to be called + whenever the buffer becomes non-empty. Setting *low* to zero causes + :meth:`~BaseProtocol.resume_writing` to be called only once the + buffer is empty. Use of zero for either limit is generally + sub-optimal as it reduces opportunities for doing I/O and + computation concurrently. + + Use :meth:`~WriteTransport.get_write_buffer_limits` + to get the limits. + +.. method:: WriteTransport.write(data) + + Write some *data* bytes to the transport. + + This method does not block; it buffers the data and arranges for it + to be sent out asynchronously. + +.. method:: WriteTransport.writelines(list_of_data) + + Write a list (or any iterable) of data bytes to the transport. + This is functionally equivalent to calling :meth:`write` on each + element yielded by the iterable, but may be implemented more + efficiently. + +.. method:: WriteTransport.write_eof() + + Close the write end of the transport after flushing all buffered data. + Data may still be received. + + This method can raise :exc:`NotImplementedError` if the transport + (e.g. SSL) doesn't support half-closed connections. + + +Datagram Transports +------------------- + +.. method:: DatagramTransport.sendto(data, addr=None) + + Send the *data* bytes to the remote peer given by *addr* (a + transport-dependent target address). If *addr* is :const:`None`, + the data is sent to the target address given on transport + creation. + + This method does not block; it buffers the data and arranges + for it to be sent out asynchronously. + +.. method:: DatagramTransport.abort() + + Close the transport immediately, without waiting for pending + operations to complete. Buffered data will be lost. + No more data will be received. The protocol's + :meth:`protocol.connection_lost() ` + method will eventually be called with :const:`None` as its argument. + + +.. _asyncio-subprocess-transports: + +Subprocess Transports +--------------------- + +.. method:: SubprocessTransport.get_pid() + + Return the subprocess process id as an integer. + +.. method:: SubprocessTransport.get_pipe_transport(fd) + + Return the transport for the communication pipe corresponding to the + integer file descriptor *fd*: + + * ``0``: readable streaming transport of the standard input (*stdin*), + or :const:`None` if the subprocess was not created with ``stdin=PIPE`` + * ``1``: writable streaming transport of the standard output (*stdout*), + or :const:`None` if the subprocess was not created with ``stdout=PIPE`` + * ``2``: writable streaming transport of the standard error (*stderr*), + or :const:`None` if the subprocess was not created with ``stderr=PIPE`` + * other *fd*: :const:`None` + +.. method:: SubprocessTransport.get_returncode() + + Return the subprocess return code as an integer or :const:`None` + if it hasn't returned, which is similar to the + :attr:`subprocess.Popen.returncode` attribute. + +.. method:: SubprocessTransport.kill() + + Kill the subprocess. + + On POSIX systems, the function sends SIGKILL to the subprocess. + On Windows, this method is an alias for :meth:`terminate`. + + See also :meth:`subprocess.Popen.kill`. + +.. method:: SubprocessTransport.send_signal(signal) + + Send the *signal* number to the subprocess, as in + :meth:`subprocess.Popen.send_signal`. + +.. method:: SubprocessTransport.terminate() + + Stop the subprocess. + + On POSIX systems, this method sends SIGTERM to the subprocess. + On Windows, the Windows API function TerminateProcess() is called to + stop the subprocess. + + See also :meth:`subprocess.Popen.terminate`. + +.. method:: SubprocessTransport.close() + + Kill the subprocess by calling the :meth:`kill` method. + + If the subprocess hasn't returned yet, and close transports of + *stdin*, *stdout*, and *stderr* pipes. + + +.. _asyncio-protocol: + +Protocols +========= + +**Source code:** :source:`Lib/asyncio/protocols.py` + +--------------------------------------------------- + +asyncio provides a set of abstract base classes that should be used +to implement network protocols. Those classes are meant to be used +together with :ref:`transports `. + +Subclasses of abstract base protocol classes may implement some or +all methods. All these methods are callbacks: they are called by +transports on certain events, for example when some data is received. +A base protocol method should be called by the corresponding transport. + + +Base Protocols +-------------- + +.. class:: BaseProtocol + + Base protocol with methods that all protocols share. + +.. class:: Protocol(BaseProtocol) + + The base class for implementing streaming protocols + (TCP, Unix sockets, etc). + +.. class:: BufferedProtocol(BaseProtocol) + + A base class for implementing streaming protocols with manual + control of the receive buffer. + +.. class:: DatagramProtocol(BaseProtocol) + + The base class for implementing datagram (UDP) protocols. + +.. class:: SubprocessProtocol(BaseProtocol) + + The base class for implementing protocols communicating with child + processes (unidirectional pipes). + + +Base Protocol +------------- + +All asyncio protocols can implement Base Protocol callbacks. + +.. rubric:: Connection Callbacks + +Connection callbacks are called on all protocols, exactly once per +a successful connection. All other protocol callbacks can only be +called between those two methods. + +.. method:: BaseProtocol.connection_made(transport) + + Called when a connection is made. + + The *transport* argument is the transport representing the + connection. The protocol is responsible for storing the reference + to its transport. + +.. method:: BaseProtocol.connection_lost(exc) + + Called when the connection is lost or closed. + + The argument is either an exception object or :const:`None`. + The latter means a regular EOF is received, or the connection was + aborted or closed by this side of the connection. + + +.. rubric:: Flow Control Callbacks + +Flow control callbacks can be called by transports to pause or +resume writing performed by the protocol. + +See the documentation of the :meth:`~WriteTransport.set_write_buffer_limits` +method for more details. + +.. method:: BaseProtocol.pause_writing() + + Called when the transport's buffer goes over the high watermark. + +.. method:: BaseProtocol.resume_writing() + + Called when the transport's buffer drains below the low watermark. + +If the buffer size equals the high watermark, +:meth:`~BaseProtocol.pause_writing` is not called: the buffer size must +go strictly over. + +Conversely, :meth:`~BaseProtocol.resume_writing` is called when the +buffer size is equal or lower than the low watermark. These end +conditions are important to ensure that things go as expected when +either mark is zero. + + +Streaming Protocols +------------------- + +Event methods, such as :meth:`loop.create_server`, +:meth:`loop.create_unix_server`, :meth:`loop.create_connection`, +:meth:`loop.create_unix_connection`, :meth:`loop.connect_accepted_socket`, +:meth:`loop.connect_read_pipe`, and :meth:`loop.connect_write_pipe` +accept factories that return streaming protocols. + +.. method:: Protocol.data_received(data) + + Called when some data is received. *data* is a non-empty bytes + object containing the incoming data. + + Whether the data is buffered, chunked or reassembled depends on + the transport. In general, you shouldn't rely on specific semantics + and instead make your parsing generic and flexible. However, + data is always received in the correct order. + + The method can be called an arbitrary number of times while + a connection is open. + + However, :meth:`protocol.eof_received() ` + is called at most once. Once `eof_received()` is called, + ``data_received()`` is not called anymore. + +.. method:: Protocol.eof_received() + + Called when the other end signals it won't send any more data + (for example by calling :meth:`transport.write_eof() + `, if the other end also uses + asyncio). + + This method may return a false value (including ``None``), in which case + the transport will close itself. Conversely, if this method returns a + true value, the protocol used determines whether to close the transport. + Since the default implementation returns ``None``, it implicitly closes the + connection. + + Some transports, including SSL, don't support half-closed connections, + in which case returning true from this method will result in the connection + being closed. + + +State machine: + +.. code-block:: none + + start -> connection_made + [-> data_received]* + [-> eof_received]? + -> connection_lost -> end + + +Buffered Streaming Protocols +---------------------------- + +.. versionadded:: 3.7 + +Buffered Protocols can be used with any event loop method +that supports `Streaming Protocols`_. + +``BufferedProtocol`` implementations allow explicit manual allocation +and control of the receive buffer. Event loops can then use the buffer +provided by the protocol to avoid unnecessary data copies. This +can result in noticeable performance improvement for protocols that +receive big amounts of data. Sophisticated protocol implementations +can significantly reduce the number of buffer allocations. + +The following callbacks are called on :class:`BufferedProtocol` +instances: + +.. method:: BufferedProtocol.get_buffer(sizehint) + + Called to allocate a new receive buffer. + + *sizehint* is the recommended minimum size for the returned + buffer. It is acceptable to return smaller or larger buffers + than what *sizehint* suggests. When set to -1, the buffer size + can be arbitrary. It is an error to return a buffer with a zero size. + + ``get_buffer()`` must return an object implementing the + :ref:`buffer protocol `. + +.. method:: BufferedProtocol.buffer_updated(nbytes) + + Called when the buffer was updated with the received data. + + *nbytes* is the total number of bytes that were written to the buffer. + +.. method:: BufferedProtocol.eof_received() + + See the documentation of the :meth:`protocol.eof_received() + ` method. + + +:meth:`~BufferedProtocol.get_buffer` can be called an arbitrary number +of times during a connection. However, :meth:`protocol.eof_received() +` is called at most once +and, if called, :meth:`~BufferedProtocol.get_buffer` and +:meth:`~BufferedProtocol.buffer_updated` won't be called after it. + +State machine: + +.. code-block:: none + + start -> connection_made + [-> get_buffer + [-> buffer_updated]? + ]* + [-> eof_received]? + -> connection_lost -> end + + +Datagram Protocols +------------------ + +Datagram Protocol instances should be constructed by protocol +factories passed to the :meth:`loop.create_datagram_endpoint` method. + +.. method:: DatagramProtocol.datagram_received(data, addr) + + Called when a datagram is received. *data* is a bytes object containing + the incoming data. *addr* is the address of the peer sending the data; + the exact format depends on the transport. + +.. method:: DatagramProtocol.error_received(exc) + + Called when a previous send or receive operation raises an + :class:`OSError`. *exc* is the :class:`OSError` instance. + + This method is called in rare conditions, when the transport (e.g. UDP) + detects that a datagram could not be delivered to its recipient. + In many conditions though, undeliverable datagrams will be silently + dropped. + +.. note:: + + On BSD systems (macOS, FreeBSD, etc.) flow control is not supported + for datagram protocols, because there is no reliable way to detect send + failures caused by writing too many packets. + + The socket always appears 'ready' and excess packets are dropped. An + :class:`OSError` with ``errno`` set to :const:`errno.ENOBUFS` may + or may not be raised; if it is raised, it will be reported to + :meth:`DatagramProtocol.error_received` but otherwise ignored. + + +.. _asyncio-subprocess-protocols: + +Subprocess Protocols +-------------------- + +Datagram Protocol instances should be constructed by protocol +factories passed to the :meth:`loop.subprocess_exec` and +:meth:`loop.subprocess_shell` methods. + +.. method:: SubprocessProtocol.pipe_data_received(fd, data) + + Called when the child process writes data into its stdout or stderr + pipe. + + *fd* is the integer file descriptor of the pipe. + + *data* is a non-empty bytes object containing the received data. + +.. method:: SubprocessProtocol.pipe_connection_lost(fd, exc) + + Called when one of the pipes communicating with the child process + is closed. + + *fd* is the integer file descriptor that was closed. + +.. method:: SubprocessProtocol.process_exited() + + Called when the child process has exited. + + +Examples +======== + +.. _asyncio_example_tcp_echo_server_protocol: + +TCP Echo Server +--------------- + +Create a TCP echo server using the :meth:`loop.create_server` method, send back +received data, and close the connection:: + + import asyncio + + + class EchoServerProtocol(asyncio.Protocol): + def connection_made(self, transport): + peername = transport.get_extra_info('peername') + print('Connection from {}'.format(peername)) + self.transport = transport + + def data_received(self, data): + message = data.decode() + print('Data received: {!r}'.format(message)) + + print('Send: {!r}'.format(message)) + self.transport.write(data) + + print('Close the client socket') + self.transport.close() + + + async def main(): + # Get a reference to the event loop as we plan to use + # low-level APIs. + loop = asyncio.get_running_loop() + + server = await loop.create_server( + lambda: EchoServerProtocol(), + '127.0.0.1', 8888) + + async with server: + await server.serve_forever() + + + asyncio.run(main()) + + +.. seealso:: + + The :ref:`TCP echo server using streams ` + example uses the high-level :func:`asyncio.start_server` function. + +.. _asyncio_example_tcp_echo_client_protocol: + +TCP Echo Client +--------------- + +A TCP echo client using the :meth:`loop.create_connection` method, sends +data, and waits until the connection is closed:: + + import asyncio + + + class EchoClientProtocol(asyncio.Protocol): + def __init__(self, message, on_con_lost): + self.message = message + self.on_con_lost = on_con_lost + + def connection_made(self, transport): + transport.write(self.message.encode()) + print('Data sent: {!r}'.format(self.message)) + + def data_received(self, data): + print('Data received: {!r}'.format(data.decode())) + + def connection_lost(self, exc): + print('The server closed the connection') + self.on_con_lost.set_result(True) + + + async def main(): + # Get a reference to the event loop as we plan to use + # low-level APIs. + loop = asyncio.get_running_loop() + + on_con_lost = loop.create_future() + message = 'Hello World!' + + transport, protocol = await loop.create_connection( + lambda: EchoClientProtocol(message, on_con_lost), + '127.0.0.1', 8888) + + # Wait until the protocol signals that the connection + # is lost and close the transport. + try: + await on_con_lost + finally: + transport.close() + + + asyncio.run(main()) + + +.. seealso:: + + The :ref:`TCP echo client using streams ` + example uses the high-level :func:`asyncio.open_connection` function. + + +.. _asyncio-udp-echo-server-protocol: + +UDP Echo Server +--------------- + +A UDP echo server, using the :meth:`loop.create_datagram_endpoint` +method, sends back received data:: + + import asyncio + + + class EchoServerProtocol: + def connection_made(self, transport): + self.transport = transport + + def datagram_received(self, data, addr): + message = data.decode() + print('Received %r from %s' % (message, addr)) + print('Send %r to %s' % (message, addr)) + self.transport.sendto(data, addr) + + + async def main(): + print("Starting UDP server") + + # Get a reference to the event loop as we plan to use + # low-level APIs. + loop = asyncio.get_running_loop() + + # One protocol instance will be created to serve all + # client requests. + transport, protocol = await loop.create_datagram_endpoint( + lambda: EchoServerProtocol(), + local_addr=('127.0.0.1', 9999)) + + try: + await asyncio.sleep(3600) # Serve for 1 hour. + finally: + transport.close() + + + asyncio.run(main()) + + +.. _asyncio-udp-echo-client-protocol: + +UDP Echo Client +--------------- + +A UDP echo client, using the :meth:`loop.create_datagram_endpoint` +method, sends data and closes the transport when it receives the answer:: + + import asyncio + + + class EchoClientProtocol: + def __init__(self, message, on_con_lost): + self.message = message + self.on_con_lost = on_con_lost + self.transport = None + + def connection_made(self, transport): + self.transport = transport + print('Send:', self.message) + self.transport.sendto(self.message.encode()) + + def datagram_received(self, data, addr): + print("Received:", data.decode()) + + print("Close the socket") + self.transport.close() + + def error_received(self, exc): + print('Error received:', exc) + + def connection_lost(self, exc): + print("Connection closed") + self.on_con_lost.set_result(True) + + + async def main(): + # Get a reference to the event loop as we plan to use + # low-level APIs. + loop = asyncio.get_running_loop() + + on_con_lost = loop.create_future() + message = "Hello World!" + + transport, protocol = await loop.create_datagram_endpoint( + lambda: EchoClientProtocol(message, on_con_lost), + remote_addr=('127.0.0.1', 9999)) + + try: + await on_con_lost + finally: + transport.close() + + + asyncio.run(main()) + + +.. _asyncio_example_create_connection: + +Connecting Existing Sockets +--------------------------- + +Wait until a socket receives data using the +:meth:`loop.create_connection` method with a protocol:: + + import asyncio + import socket + + + class MyProtocol(asyncio.Protocol): + + def __init__(self, on_con_lost): + self.transport = None + self.on_con_lost = on_con_lost + + def connection_made(self, transport): + self.transport = transport + + def data_received(self, data): + print("Received:", data.decode()) + + # We are done: close the transport; + # connection_lost() will be called automatically. + self.transport.close() + + def connection_lost(self, exc): + # The socket has been closed + self.on_con_lost.set_result(True) + + + async def main(): + # Get a reference to the event loop as we plan to use + # low-level APIs. + loop = asyncio.get_running_loop() + on_con_lost = loop.create_future() + + # Create a pair of connected sockets + rsock, wsock = socket.socketpair() + + # Register the socket to wait for data. + transport, protocol = await loop.create_connection( + lambda: MyProtocol(on_con_lost), sock=rsock) + + # Simulate the reception of data from the network. + loop.call_soon(wsock.send, 'abc'.encode()) + + try: + await protocol.on_con_lost + finally: + transport.close() + wsock.close() + + asyncio.run(main()) + +.. seealso:: + + The :ref:`watch a file descriptor for read events + ` example uses the low-level + :meth:`loop.add_reader` method to register an FD. + + The :ref:`register an open socket to wait for data using streams + ` example uses high-level streams + created by the :func:`open_connection` function in a coroutine. + +.. _asyncio_example_subprocess_proto: + +loop.subprocess_exec() and SubprocessProtocol +--------------------------------------------- + +An example of a subprocess protocol used to get the output of a +subprocess and to wait for the subprocess exit. + +The subprocess is created by th :meth:`loop.subprocess_exec` method:: + + import asyncio + import sys + + class DateProtocol(asyncio.SubprocessProtocol): + def __init__(self, exit_future): + self.exit_future = exit_future + self.output = bytearray() + + def pipe_data_received(self, fd, data): + self.output.extend(data) + + def process_exited(self): + self.exit_future.set_result(True) + + async def get_date(): + # Get a reference to the event loop as we plan to use + # low-level APIs. + loop = asyncio.get_running_loop() + + code = 'import datetime; print(datetime.datetime.now())' + exit_future = asyncio.Future(loop=loop) + + # Create the subprocess controlled by DateProtocol; + # redirect the standard output into a pipe. + transport, protocol = await loop.subprocess_exec( + lambda: DateProtocol(exit_future), + sys.executable, '-c', code, + stdin=None, stderr=None) + + # Wait for the subprocess exit using the process_exited() + # method of the protocol. + await exit_future + + # Close the stdout pipe. + transport.close() + + # Read the output which was collected by the + # pipe_data_received() method of the protocol. + data = bytes(protocol.output) + return data.decode('ascii').rstrip() + + date = asyncio.run(get_date()) + print(f"Current date: {date}") + +See also the :ref:`same example ` +written using high-level APIs. diff --git a/cpython_2/environment/repo/Doc/library/asyncio-queue.rst b/cpython_2/environment/repo/Doc/library/asyncio-queue.rst new file mode 100644 index 0000000000000000000000000000000000000000..524560b691d720d6bf39a6aab2517e0a19c57d3d --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/asyncio-queue.rst @@ -0,0 +1,208 @@ +.. currentmodule:: asyncio + +.. _asyncio-queues: + +====== +Queues +====== + +**Source code:** :source:`Lib/asyncio/queues.py` + +------------------------------------------------ + +asyncio queues are designed to be similar to classes of the +:mod:`queue` module. Although asyncio queues are not thread-safe, +they are designed to be used specifically in async/await code. + +Note that methods of asyncio queues don't have a *timeout* parameter; +use :func:`asyncio.wait_for` function to do queue operations with a +timeout. + +See also the `Examples`_ section below. + +Queue +===== + +.. class:: Queue(maxsize=0, \*, loop=None) + + A first in, first out (FIFO) queue. + + If *maxsize* is less than or equal to zero, the queue size is + infinite. If it is an integer greater than ``0``, then + ``await put()`` blocks when the queue reaches *maxsize* + until an item is removed by :meth:`get`. + + Unlike the standard library threading :mod:`queue`, the size of + the queue is always known and can be returned by calling the + :meth:`qsize` method. + + .. deprecated-removed:: 3.8 3.10 + The *loop* parameter. + + + This class is :ref:`not thread safe `. + + .. attribute:: maxsize + + Number of items allowed in the queue. + + .. method:: empty() + + Return ``True`` if the queue is empty, ``False`` otherwise. + + .. method:: full() + + Return ``True`` if there are :attr:`maxsize` items in the queue. + + If the queue was initialized with ``maxsize=0`` (the default), + then :meth:`full()` never returns ``True``. + + .. coroutinemethod:: get() + + Remove and return an item from the queue. If queue is empty, + wait until an item is available. + + .. method:: get_nowait() + + Return an item if one is immediately available, else raise + :exc:`QueueEmpty`. + + .. coroutinemethod:: join() + + Block until all items in the queue have been received and processed. + + The count of unfinished tasks goes up whenever an item is added + to the queue. The count goes down whenever a consumer coroutine calls + :meth:`task_done` to indicate that the item was retrieved and all + work on it is complete. When the count of unfinished tasks drops + to zero, :meth:`join` unblocks. + + .. coroutinemethod:: put(item) + + Put an item into the queue. If the queue is full, wait until a + free slot is available before adding the item. + + .. method:: put_nowait(item) + + Put an item into the queue without blocking. + + If no free slot is immediately available, raise :exc:`QueueFull`. + + .. method:: qsize() + + Return the number of items in the queue. + + .. method:: task_done() + + Indicate that a formerly enqueued task is complete. + + Used by queue consumers. For each :meth:`~Queue.get` used to + fetch a task, a subsequent call to :meth:`task_done` tells the + queue that the processing on the task is complete. + + If a :meth:`join` is currently blocking, it will resume when all + items have been processed (meaning that a :meth:`task_done` + call was received for every item that had been :meth:`~Queue.put` + into the queue). + + Raises :exc:`ValueError` if called more times than there were + items placed in the queue. + + +Priority Queue +============== + +.. class:: PriorityQueue + + A variant of :class:`Queue`; retrieves entries in priority order + (lowest first). + + Entries are typically tuples of the form + ``(priority_number, data)``. + + +LIFO Queue +========== + +.. class:: LifoQueue + + A variant of :class:`Queue` that retrieves most recently added + entries first (last in, first out). + + +Exceptions +========== + +.. exception:: QueueEmpty + + This exception is raised when the :meth:`~Queue.get_nowait` method + is called on an empty queue. + + +.. exception:: QueueFull + + Exception raised when the :meth:`~Queue.put_nowait` method is called + on a queue that has reached its *maxsize*. + + +Examples +======== + +.. _asyncio_example_queue_dist: + +Queues can be used to distribute workload between several +concurrent tasks:: + + import asyncio + import random + import time + + + async def worker(name, queue): + while True: + # Get a "work item" out of the queue. + sleep_for = await queue.get() + + # Sleep for the "sleep_for" seconds. + await asyncio.sleep(sleep_for) + + # Notify the queue that the "work item" has been processed. + queue.task_done() + + print(f'{name} has slept for {sleep_for:.2f} seconds') + + + async def main(): + # Create a queue that we will use to store our "workload". + queue = asyncio.Queue() + + # Generate random timings and put them into the queue. + total_sleep_time = 0 + for _ in range(20): + sleep_for = random.uniform(0.05, 1.0) + total_sleep_time += sleep_for + queue.put_nowait(sleep_for) + + # Create three worker tasks to process the queue concurrently. + tasks = [] + for i in range(3): + task = asyncio.create_task(worker(f'worker-{i}', queue)) + tasks.append(task) + + # Wait until the queue is fully processed. + started_at = time.monotonic() + await queue.join() + total_slept_for = time.monotonic() - started_at + + # Cancel our worker tasks. + for task in tasks: + task.cancel() + # Wait until all worker tasks are cancelled. + await asyncio.gather(*tasks, return_exceptions=True) + + print('====') + print(f'3 workers slept in parallel for {total_slept_for:.2f} seconds') + print(f'total expected sleep time: {total_sleep_time:.2f} seconds') + + + asyncio.run(main()) diff --git a/cpython_2/environment/repo/Doc/library/asyncio-stream.rst b/cpython_2/environment/repo/Doc/library/asyncio-stream.rst new file mode 100644 index 0000000000000000000000000000000000000000..b76ed379c7f4c88d5bbeefd10c1b28cb590689b9 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/asyncio-stream.rst @@ -0,0 +1,486 @@ +.. currentmodule:: asyncio + +.. _asyncio-streams: + +======= +Streams +======= + +**Source code:** :source:`Lib/asyncio/streams.py` + +------------------------------------------------- + +Streams are high-level async/await-ready primitives to work with +network connections. Streams allow sending and receiving data without +using callbacks or low-level protocols and transports. + +.. _asyncio_example_stream: + +Here is an example of a TCP echo client written using asyncio +streams:: + + import asyncio + + async def tcp_echo_client(message): + reader, writer = await asyncio.open_connection( + '127.0.0.1', 8888) + + print(f'Send: {message!r}') + writer.write(message.encode()) + await writer.drain() + + data = await reader.read(100) + print(f'Received: {data.decode()!r}') + + print('Close the connection') + writer.close() + await writer.wait_closed() + + asyncio.run(tcp_echo_client('Hello World!')) + + +See also the `Examples`_ section below. + + +.. rubric:: Stream Functions + +The following top-level asyncio functions can be used to create +and work with streams: + + +.. coroutinefunction:: open_connection(host=None, port=None, \*, \ + loop=None, limit=None, ssl=None, family=0, \ + proto=0, flags=0, sock=None, local_addr=None, \ + server_hostname=None, ssl_handshake_timeout=None) + + Establish a network connection and return a pair of + ``(reader, writer)`` objects. + + The returned *reader* and *writer* objects are instances of + :class:`StreamReader` and :class:`StreamWriter` classes. + + The *loop* argument is optional and can always be determined + automatically when this function is awaited from a coroutine. + + *limit* determines the buffer size limit used by the + returned :class:`StreamReader` instance. By default the *limit* + is set to 64 KiB. + + The rest of the arguments are passed directly to + :meth:`loop.create_connection`. + + .. versionadded:: 3.7 + + The *ssl_handshake_timeout* parameter. + +.. coroutinefunction:: start_server(client_connected_cb, host=None, \ + port=None, \*, loop=None, limit=None, \ + family=socket.AF_UNSPEC, \ + flags=socket.AI_PASSIVE, sock=None, \ + backlog=100, ssl=None, reuse_address=None, \ + reuse_port=None, ssl_handshake_timeout=None, \ + start_serving=True) + + Start a socket server. + + The *client_connected_cb* callback is called whenever a new client + connection is established. It receives a ``(reader, writer)`` pair + as two arguments, instances of the :class:`StreamReader` and + :class:`StreamWriter` classes. + + *client_connected_cb* can be a plain callable or a + :ref:`coroutine function `; if it is a coroutine function, + it will be automatically scheduled as a :class:`Task`. + + The *loop* argument is optional and can always be determined + automatically when this method is awaited from a coroutine. + + *limit* determines the buffer size limit used by the + returned :class:`StreamReader` instance. By default the *limit* + is set to 64 KiB. + + The rest of the arguments are passed directly to + :meth:`loop.create_server`. + + .. versionadded:: 3.7 + + The *ssl_handshake_timeout* and *start_serving* parameters. + + +.. rubric:: Unix Sockets + +.. coroutinefunction:: open_unix_connection(path=None, \*, loop=None, \ + limit=None, ssl=None, sock=None, \ + server_hostname=None, ssl_handshake_timeout=None) + + Establish a Unix socket connection and return a pair of + ``(reader, writer)``. + + Similar to :func:`open_connection` but operates on Unix sockets. + + See also the documentation of :meth:`loop.create_unix_connection`. + + .. availability:: Unix. + + .. versionadded:: 3.7 + + The *ssl_handshake_timeout* parameter. + + .. versionchanged:: 3.7 + + The *path* parameter can now be a :term:`path-like object` + + +.. coroutinefunction:: start_unix_server(client_connected_cb, path=None, \ + \*, loop=None, limit=None, sock=None, \ + backlog=100, ssl=None, ssl_handshake_timeout=None, \ + start_serving=True) + + Start a Unix socket server. + + Similar to :func:`start_server` but works with Unix sockets. + + See also the documentation of :meth:`loop.create_unix_server`. + + .. availability:: Unix. + + .. versionadded:: 3.7 + + The *ssl_handshake_timeout* and *start_serving* parameters. + + .. versionchanged:: 3.7 + + The *path* parameter can now be a :term:`path-like object`. + + +StreamReader +============ + +.. class:: StreamReader + + Represents a reader object that provides APIs to read data + from the IO stream. + + It is not recommended to instantiate *StreamReader* objects + directly; use :func:`open_connection` and :func:`start_server` + instead. + + .. coroutinemethod:: read(n=-1) + + Read up to *n* bytes. If *n* is not provided, or set to ``-1``, + read until EOF and return all read bytes. + + If EOF was received and the internal buffer is empty, + return an empty ``bytes`` object. + + .. coroutinemethod:: readline() + + Read one line, where "line" is a sequence of bytes + ending with ``\n``. + + If EOF is received and ``\n`` was not found, the method + returns partially read data. + + If EOF is received and the internal buffer is empty, + return an empty ``bytes`` object. + + .. coroutinemethod:: readexactly(n) + + Read exactly *n* bytes. + + Raise an :exc:`IncompleteReadError` if EOF is reached before *n* + can be read. Use the :attr:`IncompleteReadError.partial` + attribute to get the partially read data. + + .. coroutinemethod:: readuntil(separator=b'\\n') + + Read data from the stream until *separator* is found. + + On success, the data and separator will be removed from the + internal buffer (consumed). Returned data will include the + separator at the end. + + If the amount of data read exceeds the configured stream limit, a + :exc:`LimitOverrunError` exception is raised, and the data + is left in the internal buffer and can be read again. + + If EOF is reached before the complete separator is found, + an :exc:`IncompleteReadError` exception is raised, and the internal + buffer is reset. The :attr:`IncompleteReadError.partial` attribute + may contain a portion of the separator. + + .. versionadded:: 3.5.2 + + .. method:: at_eof() + + Return ``True`` if the buffer is empty and :meth:`feed_eof` + was called. + + +StreamWriter +============ + +.. class:: StreamWriter + + Represents a writer object that provides APIs to write data + to the IO stream. + + It is not recommended to instantiate *StreamWriter* objects + directly; use :func:`open_connection` and :func:`start_server` + instead. + + .. method:: write(data) + + The method attempts to write the *data* to the underlying socket immediately. + If that fails, the data is queued in an internal write buffer until it can be + sent. + + The method should be used along with the ``drain()`` method:: + + stream.write(data) + await stream.drain() + + .. method:: writelines(data) + + The method writes a list (or any iterable) of bytes to the underlying socket + immediately. + If that fails, the data is queued in an internal write buffer until it can be + sent. + + The method should be used along with the ``drain()`` method:: + + stream.writelines(lines) + await stream.drain() + + .. method:: close() + + The method closes the stream and the underlying socket. + + The method should be used along with the ``wait_closed()`` method:: + + stream.close() + await stream.wait_closed() + + .. method:: can_write_eof() + + Return ``True`` if the underlying transport supports + the :meth:`write_eof` method, ``False`` otherwise. + + .. method:: write_eof() + + Close the write end of the stream after the buffered write + data is flushed. + + .. attribute:: transport + + Return the underlying asyncio transport. + + .. method:: get_extra_info(name, default=None) + + Access optional transport information; see + :meth:`BaseTransport.get_extra_info` for details. + + .. coroutinemethod:: drain() + + Wait until it is appropriate to resume writing to the stream. + Example:: + + writer.write(data) + await writer.drain() + + This is a flow control method that interacts with the underlying + IO write buffer. When the size of the buffer reaches + the high watermark, *drain()* blocks until the size of the + buffer is drained down to the low watermark and writing can + be resumed. When there is nothing to wait for, the :meth:`drain` + returns immediately. + + .. method:: is_closing() + + Return ``True`` if the stream is closed or in the process of + being closed. + + .. versionadded:: 3.7 + + .. coroutinemethod:: wait_closed() + + Wait until the stream is closed. + + Should be called after :meth:`close` to wait until the underlying + connection is closed. + + .. versionadded:: 3.7 + + +Examples +======== + +.. _asyncio-tcp-echo-client-streams: + +TCP echo client using streams +----------------------------- + +TCP echo client using the :func:`asyncio.open_connection` function:: + + import asyncio + + async def tcp_echo_client(message): + reader, writer = await asyncio.open_connection( + '127.0.0.1', 8888) + + print(f'Send: {message!r}') + writer.write(message.encode()) + + data = await reader.read(100) + print(f'Received: {data.decode()!r}') + + print('Close the connection') + writer.close() + + asyncio.run(tcp_echo_client('Hello World!')) + + +.. seealso:: + + The :ref:`TCP echo client protocol ` + example uses the low-level :meth:`loop.create_connection` method. + + +.. _asyncio-tcp-echo-server-streams: + +TCP echo server using streams +----------------------------- + +TCP echo server using the :func:`asyncio.start_server` function:: + + import asyncio + + async def handle_echo(reader, writer): + data = await reader.read(100) + message = data.decode() + addr = writer.get_extra_info('peername') + + print(f"Received {message!r} from {addr!r}") + + print(f"Send: {message!r}") + writer.write(data) + await writer.drain() + + print("Close the connection") + writer.close() + + async def main(): + server = await asyncio.start_server( + handle_echo, '127.0.0.1', 8888) + + addr = server.sockets[0].getsockname() + print(f'Serving on {addr}') + + async with server: + await server.serve_forever() + + asyncio.run(main()) + + +.. seealso:: + + The :ref:`TCP echo server protocol ` + example uses the :meth:`loop.create_server` method. + + +Get HTTP headers +---------------- + +Simple example querying HTTP headers of the URL passed on the command line:: + + import asyncio + import urllib.parse + import sys + + async def print_http_headers(url): + url = urllib.parse.urlsplit(url) + if url.scheme == 'https': + reader, writer = await asyncio.open_connection( + url.hostname, 443, ssl=True) + else: + reader, writer = await asyncio.open_connection( + url.hostname, 80) + + query = ( + f"HEAD {url.path or '/'} HTTP/1.0\r\n" + f"Host: {url.hostname}\r\n" + f"\r\n" + ) + + writer.write(query.encode('latin-1')) + while True: + line = await reader.readline() + if not line: + break + + line = line.decode('latin1').rstrip() + if line: + print(f'HTTP header> {line}') + + # Ignore the body, close the socket + writer.close() + + url = sys.argv[1] + asyncio.run(print_http_headers(url)) + + +Usage:: + + python example.py http://example.com/path/page.html + +or with HTTPS:: + + python example.py https://example.com/path/page.html + + +.. _asyncio_example_create_connection-streams: + +Register an open socket to wait for data using streams +------------------------------------------------------ + +Coroutine waiting until a socket receives data using the +:func:`open_connection` function:: + + import asyncio + import socket + + async def wait_for_data(): + # Get a reference to the current event loop because + # we want to access low-level APIs. + loop = asyncio.get_running_loop() + + # Create a pair of connected sockets. + rsock, wsock = socket.socketpair() + + # Register the open socket to wait for data. + reader, writer = await asyncio.open_connection(sock=rsock) + + # Simulate the reception of data from the network + loop.call_soon(wsock.send, 'abc'.encode()) + + # Wait for data + data = await reader.read(100) + + # Got data, we are done: close the socket + print("Received:", data.decode()) + writer.close() + + # Close the second socket + wsock.close() + + asyncio.run(wait_for_data()) + +.. seealso:: + + The :ref:`register an open socket to wait for data using a protocol + ` example uses a low-level protocol and + the :meth:`loop.create_connection` method. + + The :ref:`watch a file descriptor for read events + ` example uses the low-level + :meth:`loop.add_reader` method to watch a file descriptor. diff --git a/cpython_2/environment/repo/Doc/library/asyncio-subprocess.rst b/cpython_2/environment/repo/Doc/library/asyncio-subprocess.rst new file mode 100644 index 0000000000000000000000000000000000000000..1d87d2f8005ec6554fd276aa4bfe14a9d2c7202a --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/asyncio-subprocess.rst @@ -0,0 +1,373 @@ +.. currentmodule:: asyncio + +.. _asyncio-subprocess: + +============ +Subprocesses +============ + +**Source code:** :source:`Lib/asyncio/subprocess.py`, +:source:`Lib/asyncio/base_subprocess.py` + +---------------------------------------- + +This section describes high-level async/await asyncio APIs to +create and manage subprocesses. + +.. _asyncio_example_subprocess_shell: + +Here's an example of how asyncio can run a shell command and +obtain its result:: + + import asyncio + + async def run(cmd): + proc = await asyncio.create_subprocess_shell( + cmd, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE) + + stdout, stderr = await proc.communicate() + + print(f'[{cmd!r} exited with {proc.returncode}]') + if stdout: + print(f'[stdout]\n{stdout.decode()}') + if stderr: + print(f'[stderr]\n{stderr.decode()}') + + asyncio.run(run('ls /zzz')) + +will print:: + + ['ls /zzz' exited with 1] + [stderr] + ls: /zzz: No such file or directory + +Because all asyncio subprocess functions are asynchronous and asyncio +provides many tools to work with such functions, it is easy to execute +and monitor multiple subprocesses in parallel. It is indeed trivial +to modify the above example to run several commands simultaneously:: + + async def main(): + await asyncio.gather( + run('ls /zzz'), + run('sleep 1; echo "hello"')) + + asyncio.run(main()) + +See also the `Examples`_ subsection. + + +Creating Subprocesses +===================== + +.. coroutinefunction:: create_subprocess_exec(program, \*args, stdin=None, \ + stdout=None, stderr=None, loop=None, \ + limit=None, \*\*kwds) + + Create a subprocess. + + The *limit* argument sets the buffer limit for :class:`StreamReader` + wrappers for :attr:`Process.stdout` and :attr:`Process.stderr` + (if :attr:`subprocess.PIPE` is passed to *stdout* and *stderr* arguments). + + Return a :class:`~asyncio.subprocess.Process` instance. + + See the documentation of :meth:`loop.subprocess_exec` for other + parameters. + + .. deprecated-removed:: 3.8 3.10 + + The *loop* parameter. + +.. coroutinefunction:: create_subprocess_shell(cmd, stdin=None, \ + stdout=None, stderr=None, loop=None, \ + limit=None, \*\*kwds) + + Run the *cmd* shell command. + + The *limit* argument sets the buffer limit for :class:`StreamReader` + wrappers for :attr:`Process.stdout` and :attr:`Process.stderr` + (if :attr:`subprocess.PIPE` is passed to *stdout* and *stderr* arguments). + + Return a :class:`~asyncio.subprocess.Process` instance. + + See the documentation of :meth:`loop.subprocess_shell` for other + parameters. + +.. important:: + + It is the application's responsibility to ensure that all whitespace and + special characters are quoted appropriately to avoid `shell injection + `_ + vulnerabilities. The :func:`shlex.quote` function can be used to properly + escape whitespace and special shell characters in strings that are going + to be used to construct shell commands. + + .. deprecated-removed:: 3.8 3.10 + + The *loop* parameter. + +.. note:: + + The default asyncio event loop implementation on **Windows** does not + support subprocesses. Subprocesses are available for Windows if a + :class:`ProactorEventLoop` is used. + See :ref:`Subprocess Support on Windows ` + for details. + +.. seealso:: + + asyncio also has the following *low-level* APIs to work with subprocesses: + :meth:`loop.subprocess_exec`, :meth:`loop.subprocess_shell`, + :meth:`loop.connect_read_pipe`, :meth:`loop.connect_write_pipe`, + as well as the :ref:`Subprocess Transports ` + and :ref:`Subprocess Protocols `. + + +Constants +========= + +.. data:: asyncio.subprocess.PIPE + + Can be passed to the *stdin*, *stdout* or *stderr* parameters. + + If *PIPE* is passed to *stdin* argument, the + :attr:`Process.stdin ` attribute + will point to a :class:`StreamWriter` instance. + + If *PIPE* is passed to *stdout* or *stderr* arguments, the + :attr:`Process.stdout ` and + :attr:`Process.stderr ` + attributes will point to :class:`StreamReader` instances. + +.. data:: asyncio.subprocess.STDOUT + + Special value that can be used as the *stderr* argument and indicates + that standard error should be redirected into standard output. + +.. data:: asyncio.subprocess.DEVNULL + + Special value that can be used as the *stdin*, *stdout* or *stderr* argument + to process creation functions. It indicates that the special file + :data:`os.devnull` will be used for the corresponding subprocess stream. + + +Interacting with Subprocesses +============================= + +Both :func:`create_subprocess_exec` and :func:`create_subprocess_shell` +functions return instances of the *Process* class. *Process* is a high-level +wrapper that allows communicating with subprocesses and watching for +their completion. + +.. class:: asyncio.subprocess.Process + + An object that wraps OS processes created by the + :func:`create_subprocess_exec` and :func:`create_subprocess_shell` + functions. + + This class is designed to have a similar API to the + :class:`subprocess.Popen` class, but there are some + notable differences: + + * unlike Popen, Process instances do not have an equivalent to + the :meth:`~subprocess.Popen.poll` method; + + * the :meth:`~asyncio.subprocess.Process.communicate` and + :meth:`~asyncio.subprocess.Process.wait` methods don't have a + *timeout* parameter: use the :func:`wait_for` function; + + * the :meth:`Process.wait() ` method + is asynchronous, whereas :meth:`subprocess.Popen.wait` method + is implemented as a blocking busy loop; + + * the *universal_newlines* parameter is not supported. + + This class is :ref:`not thread safe `. + + See also the :ref:`Subprocess and Threads ` + section. + + .. coroutinemethod:: wait() + + Wait for the child process to terminate. + + Set and return the :attr:`returncode` attribute. + + .. note:: + + This method can deadlock when using ``stdout=PIPE`` or + ``stderr=PIPE`` and the child process generates so much output + that it blocks waiting for the OS pipe buffer to accept + more data. Use the :meth:`communicate` method when using pipes + to avoid this condition. + + .. coroutinemethod:: communicate(input=None) + + Interact with process: + + 1. send data to *stdin* (if *input* is not ``None``); + 2. read data from *stdout* and *stderr*, until EOF is reached; + 3. wait for process to terminate. + + The optional *input* argument is the data (:class:`bytes` object) + that will be sent to the child process. + + Return a tuple ``(stdout_data, stderr_data)``. + + If either :exc:`BrokenPipeError` or :exc:`ConnectionResetError` + exception is raised when writing *input* into *stdin*, the + exception is ignored. This condition occurs when the process + exits before all data are written into *stdin*. + + If it is desired to send data to the process' *stdin*, + the process needs to be created with ``stdin=PIPE``. Similarly, + to get anything other than ``None`` in the result tuple, the + process has to be created with ``stdout=PIPE`` and/or + ``stderr=PIPE`` arguments. + + Note, that the data read is buffered in memory, so do not use + this method if the data size is large or unlimited. + + .. method:: send_signal(signal) + + Sends the signal *signal* to the child process. + + .. note:: + + On Windows, :py:data:`SIGTERM` is an alias for :meth:`terminate`. + ``CTRL_C_EVENT`` and ``CTRL_BREAK_EVENT`` can be sent to processes + started with a *creationflags* parameter which includes + ``CREATE_NEW_PROCESS_GROUP``. + + .. method:: terminate() + + Stop the child process. + + On POSIX systems this method sends :py:data:`signal.SIGTERM` to the + child process. + + On Windows the Win32 API function :c:func:`TerminateProcess` is + called to stop the child process. + + .. method:: kill() + + Kill the child. + + On POSIX systems this method sends :py:data:`SIGKILL` to the child + process. + + On Windows this method is an alias for :meth:`terminate`. + + .. attribute:: stdin + + Standard input stream (:class:`StreamWriter`) or ``None`` + if the process was created with ``stdin=None``. + + .. attribute:: stdout + + Standard output stream (:class:`StreamReader`) or ``None`` + if the process was created with ``stdout=None``. + + .. attribute:: stderr + + Standard error stream (:class:`StreamReader`) or ``None`` + if the process was created with ``stderr=None``. + + .. warning:: + + Use the :meth:`communicate` method rather than + :attr:`process.stdin.write() `, + :attr:`await process.stdout.read() ` or + :attr:`await process.stderr.read `. + This avoids deadlocks due to streams pausing reading or writing + and blocking the child process. + + .. attribute:: pid + + Process identification number (PID). + + Note that for processes created by the :func:`create_subprocess_shell` + function, this attribute is the PID of the spawned shell. + + .. attribute:: returncode + + Return code of the process when it exits. + + A ``None`` value indicates that the process has not terminated yet. + + A negative value ``-N`` indicates that the child was terminated + by signal ``N`` (POSIX only). + + +.. _asyncio-subprocess-threads: + +Subprocess and Threads +---------------------- + +Standard asyncio event loop supports running subprocesses from different threads by +default. + +On Windows subprocesses are provided by :class:`ProactorEventLoop` only (default), +:class:`SelectorEventLoop` has no subprocess support. + +On UNIX *child watchers* are used for subprocess finish waiting, see +:ref:`asyncio-watchers` for more info. + + +.. versionchanged:: 3.8 + + UNIX switched to use :class:`ThreadedChildWatcher` for spawning subprocesses from + different threads without any limitation. + + Spawning a subprocess with *inactive* current child watcher raises + :exc:`RuntimeError`. + +Note that alternative event loop implementations might have own limitations; +please refer to their documentation. + +.. seealso:: + + The :ref:`Concurrency and multithreading in asyncio + ` section. + + +Examples +-------- + +An example using the :class:`~asyncio.subprocess.Process` class to +control a subprocess and the :class:`StreamReader` class to read from +its standard output. + +.. _asyncio_example_create_subprocess_exec: + +The subprocess is created by the :func:`create_subprocess_exec` +function:: + + import asyncio + import sys + + async def get_date(): + code = 'import datetime; print(datetime.datetime.now())' + + # Create the subprocess; redirect the standard output + # into a pipe. + proc = await asyncio.create_subprocess_exec( + sys.executable, '-c', code, + stdout=asyncio.subprocess.PIPE) + + # Read one line of output. + data = await proc.stdout.readline() + line = data.decode('ascii').rstrip() + + # Wait for the subprocess exit. + await proc.wait() + return line + + date = asyncio.run(get_date()) + print(f"Current date: {date}") + + +See also the :ref:`same example ` +written using low-level APIs. diff --git a/cpython_2/environment/repo/Doc/library/asyncio-sync.rst b/cpython_2/environment/repo/Doc/library/asyncio-sync.rst new file mode 100644 index 0000000000000000000000000000000000000000..84a52cb2d575710591308d1768a8f3c88209a806 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/asyncio-sync.rst @@ -0,0 +1,354 @@ +.. currentmodule:: asyncio + +.. _asyncio-sync: + +========================== +Synchronization Primitives +========================== + +**Source code:** :source:`Lib/asyncio/locks.py` + +----------------------------------------------- + +asyncio synchronization primitives are designed to be similar to +those of the :mod:`threading` module with two important caveats: + +* asyncio primitives are not thread-safe, therefore they should not + be used for OS thread synchronization (use :mod:`threading` for + that); + +* methods of these synchronization primitives do not accept the *timeout* + argument; use the :func:`asyncio.wait_for` function to perform + operations with timeouts. + +asyncio has the following basic synchronization primitives: + +* :class:`Lock` +* :class:`Event` +* :class:`Condition` +* :class:`Semaphore` +* :class:`BoundedSemaphore` + + +--------- + + +Lock +==== + +.. class:: Lock(\*, loop=None) + + Implements a mutex lock for asyncio tasks. Not thread-safe. + + An asyncio lock can be used to guarantee exclusive access to a + shared resource. + + The preferred way to use a Lock is an :keyword:`async with` + statement:: + + lock = asyncio.Lock() + + # ... later + async with lock: + # access shared state + + which is equivalent to:: + + lock = asyncio.Lock() + + # ... later + await lock.acquire() + try: + # access shared state + finally: + lock.release() + + .. deprecated-removed:: 3.8 3.10 + The *loop* parameter. + + .. coroutinemethod:: acquire() + + Acquire the lock. + + This method waits until the lock is *unlocked*, sets it to + *locked* and returns ``True``. + + When more than one coroutine is blocked in :meth:`acquire` + waiting for the lock to be unlocked, only one coroutine + eventually proceeds. + + Acquiring a lock is *fair*: the coroutine that proceeds will be + the first coroutine that started waiting on the lock. + + .. method:: release() + + Release the lock. + + When the lock is *locked*, reset it to *unlocked* and return. + + If the lock is *unlocked*, a :exc:`RuntimeError` is raised. + + .. method:: locked() + + Return ``True`` if the lock is *locked*. + + +Event +===== + +.. class:: Event(\*, loop=None) + + An event object. Not thread-safe. + + An asyncio event can be used to notify multiple asyncio tasks + that some event has happened. + + An Event object manages an internal flag that can be set to *true* + with the :meth:`set` method and reset to *false* with the + :meth:`clear` method. The :meth:`wait` method blocks until the + flag is set to *true*. The flag is set to *false* initially. + + + .. deprecated-removed:: 3.8 3.10 + The *loop* parameter. + + .. _asyncio_example_sync_event: + + Example:: + + async def waiter(event): + print('waiting for it ...') + await event.wait() + print('... got it!') + + async def main(): + # Create an Event object. + event = asyncio.Event() + + # Spawn a Task to wait until 'event' is set. + waiter_task = asyncio.create_task(waiter(event)) + + # Sleep for 1 second and set the event. + await asyncio.sleep(1) + event.set() + + # Wait until the waiter task is finished. + await waiter_task + + asyncio.run(main()) + + .. coroutinemethod:: wait() + + Wait until the event is set. + + If the event is set, return ``True`` immediately. + Otherwise block until another task calls :meth:`set`. + + .. method:: set() + + Set the event. + + All tasks waiting for event to be set will be immediately + awakened. + + .. method:: clear() + + Clear (unset) the event. + + Tasks awaiting on :meth:`wait` will now block until the + :meth:`set` method is called again. + + .. method:: is_set() + + Return ``True`` if the event is set. + + +Condition +========= + +.. class:: Condition(lock=None, \*, loop=None) + + A Condition object. Not thread-safe. + + An asyncio condition primitive can be used by a task to wait for + some event to happen and then get exclusive access to a shared + resource. + + In essence, a Condition object combines the functionality + of an :class:`Event` and a :class:`Lock`. It is possible to have + multiple Condition objects share one Lock, which allows coordinating + exclusive access to a shared resource between different tasks + interested in particular states of that shared resource. + + The optional *lock* argument must be a :class:`Lock` object or + ``None``. In the latter case a new Lock object is created + automatically. + + + .. deprecated-removed:: 3.8 3.10 + The *loop* parameter. + + The preferred way to use a Condition is an :keyword:`async with` + statement:: + + cond = asyncio.Condition() + + # ... later + async with cond: + await cond.wait() + + which is equivalent to:: + + cond = asyncio.Condition() + + # ... later + await cond.acquire() + try: + await cond.wait() + finally: + cond.release() + + .. coroutinemethod:: acquire() + + Acquire the underlying lock. + + This method waits until the underlying lock is *unlocked*, + sets it to *locked* and returns ``True``. + + .. method:: notify(n=1) + + Wake up at most *n* tasks (1 by default) waiting on this + condition. The method is no-op if no tasks are waiting. + + The lock must be acquired before this method is called and + released shortly after. If called with an *unlocked* lock + a :exc:`RuntimeError` error is raised. + + .. method:: locked() + + Return ``True`` if the underlying lock is acquired. + + .. method:: notify_all() + + Wake up all tasks waiting on this condition. + + This method acts like :meth:`notify`, but wakes up all waiting + tasks. + + The lock must be acquired before this method is called and + released shortly after. If called with an *unlocked* lock + a :exc:`RuntimeError` error is raised. + + .. method:: release() + + Release the underlying lock. + + When invoked on an unlocked lock, a :exc:`RuntimeError` is + raised. + + .. coroutinemethod:: wait() + + Wait until notified. + + If the calling task has not acquired the lock when this method is + called, a :exc:`RuntimeError` is raised. + + This method releases the underlying lock, and then blocks until + it is awakened by a :meth:`notify` or :meth:`notify_all` call. + Once awakened, the Condition re-acquires its lock and this method + returns ``True``. + + .. coroutinemethod:: wait_for(predicate) + + Wait until a predicate becomes *true*. + + The predicate must be a callable which result will be + interpreted as a boolean value. The final value is the + return value. + + +Semaphore +========= + +.. class:: Semaphore(value=1, \*, loop=None) + + A Semaphore object. Not thread-safe. + + A semaphore manages an internal counter which is decremented by each + :meth:`acquire` call and incremented by each :meth:`release` call. + The counter can never go below zero; when :meth:`acquire` finds + that it is zero, it blocks, waiting until some task calls + :meth:`release`. + + The optional *value* argument gives the initial value for the + internal counter (``1`` by default). If the given value is + less than ``0`` a :exc:`ValueError` is raised. + + + .. deprecated-removed:: 3.8 3.10 + The *loop* parameter. + + The preferred way to use a Semaphore is an :keyword:`async with` + statement:: + + sem = asyncio.Semaphore(10) + + # ... later + async with sem: + # work with shared resource + + which is equivalent to:: + + sem = asyncio.Semaphore(10) + + # ... later + await sem.acquire() + try: + # work with shared resource + finally: + sem.release() + + .. coroutinemethod:: acquire() + + Acquire a semaphore. + + If the internal counter is greater than zero, decrement + it by one and return ``True`` immediately. If it is zero, wait + until a :meth:`release` is called and return ``True``. + + .. method:: locked() + + Returns ``True`` if semaphore can not be acquired immediately. + + .. method:: release() + + Release a semaphore, incrementing the internal counter by one. + Can wake up a task waiting to acquire the semaphore. + + Unlike :class:`BoundedSemaphore`, :class:`Semaphore` allows + making more ``release()`` calls than ``acquire()`` calls. + + +BoundedSemaphore +================ + +.. class:: BoundedSemaphore(value=1, \*, loop=None) + + A bounded semaphore object. Not thread-safe. + + Bounded Semaphore is a version of :class:`Semaphore` that raises + a :exc:`ValueError` in :meth:`~Semaphore.release` if it + increases the internal counter above the initial *value*. + + + .. deprecated-removed:: 3.8 3.10 + The *loop* parameter. + +--------- + + +.. versionchanged:: 3.9 + + Acquiring a lock using ``await lock`` or ``yield from lock`` and/or + :keyword:`with` statement (``with await lock``, ``with (yield from + lock)``) was removed. Use ``async with lock`` instead. diff --git a/cpython_2/environment/repo/Doc/library/asyncio-task.rst b/cpython_2/environment/repo/Doc/library/asyncio-task.rst new file mode 100644 index 0000000000000000000000000000000000000000..2e963398d93001999a1b0b6fbe40421c853256f8 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/asyncio-task.rst @@ -0,0 +1,986 @@ +.. currentmodule:: asyncio + + +==================== +Coroutines and Tasks +==================== + +This section outlines high-level asyncio APIs to work with coroutines +and Tasks. + +.. contents:: + :depth: 1 + :local: + + +.. _coroutine: + +Coroutines +========== + +:term:`Coroutines ` declared with the async/await syntax is the +preferred way of writing asyncio applications. For example, the following +snippet of code (requires Python 3.7+) prints "hello", waits 1 second, +and then prints "world":: + + >>> import asyncio + + >>> async def main(): + ... print('hello') + ... await asyncio.sleep(1) + ... print('world') + + >>> asyncio.run(main()) + hello + world + +Note that simply calling a coroutine will not schedule it to +be executed:: + + >>> main() + + +To actually run a coroutine, asyncio provides three main mechanisms: + +* The :func:`asyncio.run` function to run the top-level + entry point "main()" function (see the above example.) + +* Awaiting on a coroutine. The following snippet of code will + print "hello" after waiting for 1 second, and then print "world" + after waiting for *another* 2 seconds:: + + import asyncio + import time + + async def say_after(delay, what): + await asyncio.sleep(delay) + print(what) + + async def main(): + print(f"started at {time.strftime('%X')}") + + await say_after(1, 'hello') + await say_after(2, 'world') + + print(f"finished at {time.strftime('%X')}") + + asyncio.run(main()) + + Expected output:: + + started at 17:13:52 + hello + world + finished at 17:13:55 + +* The :func:`asyncio.create_task` function to run coroutines + concurrently as asyncio :class:`Tasks `. + + Let's modify the above example and run two ``say_after`` coroutines + *concurrently*:: + + async def main(): + task1 = asyncio.create_task( + say_after(1, 'hello')) + + task2 = asyncio.create_task( + say_after(2, 'world')) + + print(f"started at {time.strftime('%X')}") + + # Wait until both tasks are completed (should take + # around 2 seconds.) + await task1 + await task2 + + print(f"finished at {time.strftime('%X')}") + + Note that expected output now shows that the snippet runs + 1 second faster than before:: + + started at 17:14:32 + hello + world + finished at 17:14:34 + + +.. _asyncio-awaitables: + +Awaitables +========== + +We say that an object is an **awaitable** object if it can be used +in an :keyword:`await` expression. Many asyncio APIs are designed to +accept awaitables. + +There are three main types of *awaitable* objects: +**coroutines**, **Tasks**, and **Futures**. + + +.. rubric:: Coroutines + +Python coroutines are *awaitables* and therefore can be awaited from +other coroutines:: + + import asyncio + + async def nested(): + return 42 + + async def main(): + # Nothing happens if we just call "nested()". + # A coroutine object is created but not awaited, + # so it *won't run at all*. + nested() + + # Let's do it differently now and await it: + print(await nested()) # will print "42". + + asyncio.run(main()) + +.. important:: + + In this documentation the term "coroutine" can be used for + two closely related concepts: + + * a *coroutine function*: an :keyword:`async def` function; + + * a *coroutine object*: an object returned by calling a + *coroutine function*. + +asyncio also supports legacy :ref:`generator-based +` coroutines. + + +.. rubric:: Tasks + +*Tasks* are used to schedule coroutines *concurrently*. + +When a coroutine is wrapped into a *Task* with functions like +:func:`asyncio.create_task` the coroutine is automatically +scheduled to run soon:: + + import asyncio + + async def nested(): + return 42 + + async def main(): + # Schedule nested() to run soon concurrently + # with "main()". + task = asyncio.create_task(nested()) + + # "task" can now be used to cancel "nested()", or + # can simply be awaited to wait until it is complete: + await task + + asyncio.run(main()) + + +.. rubric:: Futures + +A :class:`Future` is a special **low-level** awaitable object that +represents an **eventual result** of an asynchronous operation. + +When a Future object is *awaited* it means that the coroutine will +wait until the Future is resolved in some other place. + +Future objects in asyncio are needed to allow callback-based code +to be used with async/await. + +Normally **there is no need** to create Future objects at the +application level code. + +Future objects, sometimes exposed by libraries and some asyncio +APIs, can be awaited:: + + async def main(): + await function_that_returns_a_future_object() + + # this is also valid: + await asyncio.gather( + function_that_returns_a_future_object(), + some_python_coroutine() + ) + +A good example of a low-level function that returns a Future object +is :meth:`loop.run_in_executor`. + + +Running an asyncio Program +========================== + +.. function:: run(coro, \*, debug=False) + + Execute the :term:`coroutine` *coro* and return the result. + + This function runs the passed coroutine, taking care of + managing the asyncio event loop, *finalizing asynchronous + generators*, and closing the threadpool. + + This function cannot be called when another asyncio event loop is + running in the same thread. + + If *debug* is ``True``, the event loop will be run in debug mode. + + This function always creates a new event loop and closes it at + the end. It should be used as a main entry point for asyncio + programs, and should ideally only be called once. + + Example:: + + async def main(): + await asyncio.sleep(1) + print('hello') + + asyncio.run(main()) + + .. versionadded:: 3.7 + + .. versionchanged:: 3.9 + Updated to use :meth:`loop.shutdown_default_executor`. + + .. note:: + The source code for ``asyncio.run()`` can be found in + :source:`Lib/asyncio/runners.py`. + +Creating Tasks +============== + +.. function:: create_task(coro, \*, name=None) + + Wrap the *coro* :ref:`coroutine ` into a :class:`Task` + and schedule its execution. Return the Task object. + + If *name* is not ``None``, it is set as the name of the task using + :meth:`Task.set_name`. + + The task is executed in the loop returned by :func:`get_running_loop`, + :exc:`RuntimeError` is raised if there is no running loop in + current thread. + + This function has been **added in Python 3.7**. Prior to + Python 3.7, the low-level :func:`asyncio.ensure_future` function + can be used instead:: + + async def coro(): + ... + + # In Python 3.7+ + task = asyncio.create_task(coro()) + ... + + # This works in all Python versions but is less readable + task = asyncio.ensure_future(coro()) + ... + + .. versionadded:: 3.7 + + .. versionchanged:: 3.8 + Added the ``name`` parameter. + + +Sleeping +======== + +.. coroutinefunction:: sleep(delay, result=None, \*, loop=None) + + Block for *delay* seconds. + + If *result* is provided, it is returned to the caller + when the coroutine completes. + + ``sleep()`` always suspends the current task, allowing other tasks + to run. + + .. deprecated-removed:: 3.8 3.10 + The *loop* parameter. + + .. _asyncio_example_sleep: + + Example of coroutine displaying the current date every second + for 5 seconds:: + + import asyncio + import datetime + + async def display_date(): + loop = asyncio.get_running_loop() + end_time = loop.time() + 5.0 + while True: + print(datetime.datetime.now()) + if (loop.time() + 1.0) >= end_time: + break + await asyncio.sleep(1) + + asyncio.run(display_date()) + + +Running Tasks Concurrently +========================== + +.. awaitablefunction:: gather(\*aws, loop=None, return_exceptions=False) + + Run :ref:`awaitable objects ` in the *aws* + sequence *concurrently*. + + If any awaitable in *aws* is a coroutine, it is automatically + scheduled as a Task. + + If all awaitables are completed successfully, the result is an + aggregate list of returned values. The order of result values + corresponds to the order of awaitables in *aws*. + + If *return_exceptions* is ``False`` (default), the first + raised exception is immediately propagated to the task that + awaits on ``gather()``. Other awaitables in the *aws* sequence + **won't be cancelled** and will continue to run. + + If *return_exceptions* is ``True``, exceptions are treated the + same as successful results, and aggregated in the result list. + + If ``gather()`` is *cancelled*, all submitted awaitables + (that have not completed yet) are also *cancelled*. + + If any Task or Future from the *aws* sequence is *cancelled*, it is + treated as if it raised :exc:`CancelledError` -- the ``gather()`` + call is **not** cancelled in this case. This is to prevent the + cancellation of one submitted Task/Future to cause other + Tasks/Futures to be cancelled. + + .. deprecated-removed:: 3.8 3.10 + The *loop* parameter. + + .. _asyncio_example_gather: + + Example:: + + import asyncio + + async def factorial(name, number): + f = 1 + for i in range(2, number + 1): + print(f"Task {name}: Compute factorial({i})...") + await asyncio.sleep(1) + f *= i + print(f"Task {name}: factorial({number}) = {f}") + + async def main(): + # Schedule three calls *concurrently*: + await asyncio.gather( + factorial("A", 2), + factorial("B", 3), + factorial("C", 4), + ) + + asyncio.run(main()) + + # Expected output: + # + # Task A: Compute factorial(2)... + # Task B: Compute factorial(2)... + # Task C: Compute factorial(2)... + # Task A: factorial(2) = 2 + # Task B: Compute factorial(3)... + # Task C: Compute factorial(3)... + # Task B: factorial(3) = 6 + # Task C: Compute factorial(4)... + # Task C: factorial(4) = 24 + + .. versionchanged:: 3.7 + If the *gather* itself is cancelled, the cancellation is + propagated regardless of *return_exceptions*. + + +Shielding From Cancellation +=========================== + +.. awaitablefunction:: shield(aw, \*, loop=None) + + Protect an :ref:`awaitable object ` + from being :meth:`cancelled `. + + If *aw* is a coroutine it is automatically scheduled as a Task. + + The statement:: + + res = await shield(something()) + + is equivalent to:: + + res = await something() + + *except* that if the coroutine containing it is cancelled, the + Task running in ``something()`` is not cancelled. From the point + of view of ``something()``, the cancellation did not happen. + Although its caller is still cancelled, so the "await" expression + still raises a :exc:`CancelledError`. + + If ``something()`` is cancelled by other means (i.e. from within + itself) that would also cancel ``shield()``. + + If it is desired to completely ignore cancellation (not recommended) + the ``shield()`` function should be combined with a try/except + clause, as follows:: + + try: + res = await shield(something()) + except CancelledError: + res = None + + .. deprecated-removed:: 3.8 3.10 + The *loop* parameter. + + +Timeouts +======== + +.. coroutinefunction:: wait_for(aw, timeout, \*, loop=None) + + Wait for the *aw* :ref:`awaitable ` + to complete with a timeout. + + If *aw* is a coroutine it is automatically scheduled as a Task. + + *timeout* can either be ``None`` or a float or int number of seconds + to wait for. If *timeout* is ``None``, block until the future + completes. + + If a timeout occurs, it cancels the task and raises + :exc:`asyncio.TimeoutError`. + + To avoid the task :meth:`cancellation `, + wrap it in :func:`shield`. + + The function will wait until the future is actually cancelled, + so the total wait time may exceed the *timeout*. If an exception + happens during cancellation, it is propagated. + + If the wait is cancelled, the future *aw* is also cancelled. + + .. deprecated-removed:: 3.8 3.10 + The *loop* parameter. + + .. _asyncio_example_waitfor: + + Example:: + + async def eternity(): + # Sleep for one hour + await asyncio.sleep(3600) + print('yay!') + + async def main(): + # Wait for at most 1 second + try: + await asyncio.wait_for(eternity(), timeout=1.0) + except asyncio.TimeoutError: + print('timeout!') + + asyncio.run(main()) + + # Expected output: + # + # timeout! + + .. versionchanged:: 3.7 + When *aw* is cancelled due to a timeout, ``wait_for`` waits + for *aw* to be cancelled. Previously, it raised + :exc:`asyncio.TimeoutError` immediately. + + +Waiting Primitives +================== + +.. coroutinefunction:: wait(aws, \*, loop=None, timeout=None,\ + return_when=ALL_COMPLETED) + + Run :ref:`awaitable objects ` in the *aws* + set concurrently and block until the condition specified + by *return_when*. + + The *aws* set must not be empty. + + Returns two sets of Tasks/Futures: ``(done, pending)``. + + Usage:: + + done, pending = await asyncio.wait(aws) + + *timeout* (a float or int), if specified, can be used to control + the maximum number of seconds to wait before returning. + + Note that this function does not raise :exc:`asyncio.TimeoutError`. + Futures or Tasks that aren't done when the timeout occurs are simply + returned in the second set. + + *return_when* indicates when this function should return. It must + be one of the following constants: + + .. tabularcolumns:: |l|L| + + +-----------------------------+----------------------------------------+ + | Constant | Description | + +=============================+========================================+ + | :const:`FIRST_COMPLETED` | The function will return when any | + | | future finishes or is cancelled. | + +-----------------------------+----------------------------------------+ + | :const:`FIRST_EXCEPTION` | The function will return when any | + | | future finishes by raising an | + | | exception. If no future raises an | + | | exception then it is equivalent to | + | | :const:`ALL_COMPLETED`. | + +-----------------------------+----------------------------------------+ + | :const:`ALL_COMPLETED` | The function will return when all | + | | futures finish or are cancelled. | + +-----------------------------+----------------------------------------+ + + Unlike :func:`~asyncio.wait_for`, ``wait()`` does not cancel the + futures when a timeout occurs. + + .. deprecated:: 3.8 + + If any awaitable in *aws* is a coroutine, it is automatically + scheduled as a Task. Passing coroutines objects to + ``wait()`` directly is deprecated as it leads to + :ref:`confusing behavior `. + + .. deprecated-removed:: 3.8 3.10 + + The *loop* parameter. + + .. _asyncio_example_wait_coroutine: + .. note:: + + ``wait()`` schedules coroutines as Tasks automatically and later + returns those implicitly created Task objects in ``(done, pending)`` + sets. Therefore the following code won't work as expected:: + + async def foo(): + return 42 + + coro = foo() + done, pending = await asyncio.wait({coro}) + + if coro in done: + # This branch will never be run! + + Here is how the above snippet can be fixed:: + + async def foo(): + return 42 + + task = asyncio.create_task(foo()) + done, pending = await asyncio.wait({task}) + + if task in done: + # Everything will work as expected now. + + .. deprecated-removed:: 3.8 3.11 + + Passing coroutine objects to ``wait()`` directly is + deprecated. + + +.. function:: as_completed(aws, \*, loop=None, timeout=None) + + Run :ref:`awaitable objects ` in the *aws* + set concurrently. Return an iterator of :class:`Future` objects. + Each Future object returned represents the earliest result + from the set of the remaining awaitables. + + Raises :exc:`asyncio.TimeoutError` if the timeout occurs before + all Futures are done. + + .. deprecated-removed:: 3.8 3.10 + The *loop* parameter. + + Example:: + + for f in as_completed(aws): + earliest_result = await f + # ... + + +Scheduling From Other Threads +============================= + +.. function:: run_coroutine_threadsafe(coro, loop) + + Submit a coroutine to the given event loop. Thread-safe. + + Return a :class:`concurrent.futures.Future` to wait for the result + from another OS thread. + + This function is meant to be called from a different OS thread + than the one where the event loop is running. Example:: + + # Create a coroutine + coro = asyncio.sleep(1, result=3) + + # Submit the coroutine to a given loop + future = asyncio.run_coroutine_threadsafe(coro, loop) + + # Wait for the result with an optional timeout argument + assert future.result(timeout) == 3 + + If an exception is raised in the coroutine, the returned Future + will be notified. It can also be used to cancel the task in + the event loop:: + + try: + result = future.result(timeout) + except asyncio.TimeoutError: + print('The coroutine took too long, cancelling the task...') + future.cancel() + except Exception as exc: + print(f'The coroutine raised an exception: {exc!r}') + else: + print(f'The coroutine returned: {result!r}') + + See the :ref:`concurrency and multithreading ` + section of the documentation. + + Unlike other asyncio functions this function requires the *loop* + argument to be passed explicitly. + + .. versionadded:: 3.5.1 + + +Introspection +============= + + +.. function:: current_task(loop=None) + + Return the currently running :class:`Task` instance, or ``None`` if + no task is running. + + If *loop* is ``None`` :func:`get_running_loop` is used to get + the current loop. + + .. versionadded:: 3.7 + + +.. function:: all_tasks(loop=None) + + Return a set of not yet finished :class:`Task` objects run by + the loop. + + If *loop* is ``None``, :func:`get_running_loop` is used for getting + current loop. + + .. versionadded:: 3.7 + + +Task Object +=========== + +.. class:: Task(coro, \*, loop=None, name=None) + + A :class:`Future-like ` object that runs a Python + :ref:`coroutine `. Not thread-safe. + + Tasks are used to run coroutines in event loops. + If a coroutine awaits on a Future, the Task suspends + the execution of the coroutine and waits for the completion + of the Future. When the Future is *done*, the execution of + the wrapped coroutine resumes. + + Event loops use cooperative scheduling: an event loop runs + one Task at a time. While a Task awaits for the completion of a + Future, the event loop runs other Tasks, callbacks, or performs + IO operations. + + Use the high-level :func:`asyncio.create_task` function to create + Tasks, or the low-level :meth:`loop.create_task` or + :func:`ensure_future` functions. Manual instantiation of Tasks + is discouraged. + + To cancel a running Task use the :meth:`cancel` method. Calling it + will cause the Task to throw a :exc:`CancelledError` exception into + the wrapped coroutine. If a coroutine is awaiting on a Future + object during cancellation, the Future object will be cancelled. + + :meth:`cancelled` can be used to check if the Task was cancelled. + The method returns ``True`` if the wrapped coroutine did not + suppress the :exc:`CancelledError` exception and was actually + cancelled. + + :class:`asyncio.Task` inherits from :class:`Future` all of its + APIs except :meth:`Future.set_result` and + :meth:`Future.set_exception`. + + Tasks support the :mod:`contextvars` module. When a Task + is created it copies the current context and later runs its + coroutine in the copied context. + + .. versionchanged:: 3.7 + Added support for the :mod:`contextvars` module. + + .. versionchanged:: 3.8 + Added the ``name`` parameter. + + .. deprecated-removed:: 3.8 3.10 + The *loop* parameter. + + .. method:: cancel(msg=None) + + Request the Task to be cancelled. + + This arranges for a :exc:`CancelledError` exception to be thrown + into the wrapped coroutine on the next cycle of the event loop. + + The coroutine then has a chance to clean up or even deny the + request by suppressing the exception with a :keyword:`try` ... + ... ``except CancelledError`` ... :keyword:`finally` block. + Therefore, unlike :meth:`Future.cancel`, :meth:`Task.cancel` does + not guarantee that the Task will be cancelled, although + suppressing cancellation completely is not common and is actively + discouraged. + + .. versionchanged:: 3.9 + Added the ``msg`` parameter. + + .. _asyncio_example_task_cancel: + + The following example illustrates how coroutines can intercept + the cancellation request:: + + async def cancel_me(): + print('cancel_me(): before sleep') + + try: + # Wait for 1 hour + await asyncio.sleep(3600) + except asyncio.CancelledError: + print('cancel_me(): cancel sleep') + raise + finally: + print('cancel_me(): after sleep') + + async def main(): + # Create a "cancel_me" Task + task = asyncio.create_task(cancel_me()) + + # Wait for 1 second + await asyncio.sleep(1) + + task.cancel() + try: + await task + except asyncio.CancelledError: + print("main(): cancel_me is cancelled now") + + asyncio.run(main()) + + # Expected output: + # + # cancel_me(): before sleep + # cancel_me(): cancel sleep + # cancel_me(): after sleep + # main(): cancel_me is cancelled now + + .. method:: cancelled() + + Return ``True`` if the Task is *cancelled*. + + The Task is *cancelled* when the cancellation was requested with + :meth:`cancel` and the wrapped coroutine propagated the + :exc:`CancelledError` exception thrown into it. + + .. method:: done() + + Return ``True`` if the Task is *done*. + + A Task is *done* when the wrapped coroutine either returned + a value, raised an exception, or the Task was cancelled. + + .. method:: result() + + Return the result of the Task. + + If the Task is *done*, the result of the wrapped coroutine + is returned (or if the coroutine raised an exception, that + exception is re-raised.) + + If the Task has been *cancelled*, this method raises + a :exc:`CancelledError` exception. + + If the Task's result isn't yet available, this method raises + a :exc:`InvalidStateError` exception. + + .. method:: exception() + + Return the exception of the Task. + + If the wrapped coroutine raised an exception that exception + is returned. If the wrapped coroutine returned normally + this method returns ``None``. + + If the Task has been *cancelled*, this method raises a + :exc:`CancelledError` exception. + + If the Task isn't *done* yet, this method raises an + :exc:`InvalidStateError` exception. + + .. method:: add_done_callback(callback, *, context=None) + + Add a callback to be run when the Task is *done*. + + This method should only be used in low-level callback-based code. + + See the documentation of :meth:`Future.add_done_callback` + for more details. + + .. method:: remove_done_callback(callback) + + Remove *callback* from the callbacks list. + + This method should only be used in low-level callback-based code. + + See the documentation of :meth:`Future.remove_done_callback` + for more details. + + .. method:: get_stack(\*, limit=None) + + Return the list of stack frames for this Task. + + If the wrapped coroutine is not done, this returns the stack + where it is suspended. If the coroutine has completed + successfully or was cancelled, this returns an empty list. + If the coroutine was terminated by an exception, this returns + the list of traceback frames. + + The frames are always ordered from oldest to newest. + + Only one stack frame is returned for a suspended coroutine. + + The optional *limit* argument sets the maximum number of frames + to return; by default all available frames are returned. + The ordering of the returned list differs depending on whether + a stack or a traceback is returned: the newest frames of a + stack are returned, but the oldest frames of a traceback are + returned. (This matches the behavior of the traceback module.) + + .. method:: print_stack(\*, limit=None, file=None) + + Print the stack or traceback for this Task. + + This produces output similar to that of the traceback module + for the frames retrieved by :meth:`get_stack`. + + The *limit* argument is passed to :meth:`get_stack` directly. + + The *file* argument is an I/O stream to which the output + is written; by default output is written to :data:`sys.stderr`. + + .. method:: get_coro() + + Return the coroutine object wrapped by the :class:`Task`. + + .. versionadded:: 3.8 + + .. method:: get_name() + + Return the name of the Task. + + If no name has been explicitly assigned to the Task, the default + asyncio Task implementation generates a default name during + instantiation. + + .. versionadded:: 3.8 + + .. method:: set_name(value) + + Set the name of the Task. + + The *value* argument can be any object, which is then + converted to a string. + + In the default Task implementation, the name will be visible + in the :func:`repr` output of a task object. + + .. versionadded:: 3.8 + + .. classmethod:: all_tasks(loop=None) + + Return a set of all tasks for an event loop. + + By default all tasks for the current event loop are returned. + If *loop* is ``None``, the :func:`get_event_loop` function + is used to get the current loop. + + .. deprecated-removed:: 3.7 3.9 + + Do not call this as a task method. Use the :func:`asyncio.all_tasks` + function instead. + + .. classmethod:: current_task(loop=None) + + Return the currently running task or ``None``. + + If *loop* is ``None``, the :func:`get_event_loop` function + is used to get the current loop. + + .. deprecated-removed:: 3.7 3.9 + + Do not call this as a task method. Use the + :func:`asyncio.current_task` function instead. + + +.. _asyncio_generator_based_coro: + +Generator-based Coroutines +========================== + +.. note:: + + Support for generator-based coroutines is **deprecated** and + is scheduled for removal in Python 3.10. + +Generator-based coroutines predate async/await syntax. They are +Python generators that use ``yield from`` expressions to await +on Futures and other coroutines. + +Generator-based coroutines should be decorated with +:func:`@asyncio.coroutine `, although this is not +enforced. + + +.. decorator:: coroutine + + Decorator to mark generator-based coroutines. + + This decorator enables legacy generator-based coroutines to be + compatible with async/await code:: + + @asyncio.coroutine + def old_style_coroutine(): + yield from asyncio.sleep(1) + + async def main(): + await old_style_coroutine() + + This decorator should not be used for :keyword:`async def` + coroutines. + + .. deprecated-removed:: 3.8 3.10 + + Use :keyword:`async def` instead. + +.. function:: iscoroutine(obj) + + Return ``True`` if *obj* is a :ref:`coroutine object `. + + This method is different from :func:`inspect.iscoroutine` because + it returns ``True`` for generator-based coroutines. + +.. function:: iscoroutinefunction(func) + + Return ``True`` if *func* is a :ref:`coroutine function + `. + + This method is different from :func:`inspect.iscoroutinefunction` + because it returns ``True`` for generator-based coroutine functions + decorated with :func:`@coroutine `. diff --git a/cpython_2/environment/repo/Doc/library/asyncio.rst b/cpython_2/environment/repo/Doc/library/asyncio.rst new file mode 100644 index 0000000000000000000000000000000000000000..94a853259d348336720af76673316a193a11b8d8 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/asyncio.rst @@ -0,0 +1,96 @@ +:mod:`asyncio` --- Asynchronous I/O +=================================== + +.. module:: asyncio + :synopsis: Asynchronous I/O. + +------------------------------- + +.. sidebar:: Hello World! + + :: + + import asyncio + + async def main(): + print('Hello ...') + await asyncio.sleep(1) + print('... World!') + + # Python 3.7+ + asyncio.run(main()) + +asyncio is a library to write **concurrent** code using +the **async/await** syntax. + +asyncio is used as a foundation for multiple Python asynchronous +frameworks that provide high-performance network and web-servers, +database connection libraries, distributed task queues, etc. + +asyncio is often a perfect fit for IO-bound and high-level +**structured** network code. + +asyncio provides a set of **high-level** APIs to: + +* :ref:`run Python coroutines ` concurrently and + have full control over their execution; + +* perform :ref:`network IO and IPC `; + +* control :ref:`subprocesses `; + +* distribute tasks via :ref:`queues `; + +* :ref:`synchronize ` concurrent code; + +Additionally, there are **low-level** APIs for +*library and framework developers* to: + +* create and manage :ref:`event loops `, which + provide asynchronous APIs for :meth:`networking `, + running :meth:`subprocesses `, + handling :meth:`OS signals `, etc; + +* implement efficient protocols using + :ref:`transports `; + +* :ref:`bridge ` callback-based libraries and code + with async/await syntax. + + +.. We use the "rubric" directive here to avoid creating + the "Reference" subsection in the TOC. + +.. rubric:: Reference + +.. toctree:: + :caption: High-level APIs + :maxdepth: 1 + + asyncio-task.rst + asyncio-stream.rst + asyncio-sync.rst + asyncio-subprocess.rst + asyncio-queue.rst + asyncio-exceptions.rst + +.. toctree:: + :caption: Low-level APIs + :maxdepth: 1 + + asyncio-eventloop.rst + asyncio-future.rst + asyncio-protocol.rst + asyncio-policy.rst + asyncio-platforms.rst + +.. toctree:: + :caption: Guides and Tutorials + :maxdepth: 1 + + asyncio-api-index.rst + asyncio-llapi-index.rst + asyncio-dev.rst + +.. note:: + The source code for asyncio can be found in :source:`Lib/asyncio/`. diff --git a/cpython_2/environment/repo/Doc/library/asyncore.rst b/cpython_2/environment/repo/Doc/library/asyncore.rst new file mode 100644 index 0000000000000000000000000000000000000000..a86518ebff2777eb12e75fb361950392145a2699 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/asyncore.rst @@ -0,0 +1,360 @@ +:mod:`asyncore` --- Asynchronous socket handler +=============================================== + +.. module:: asyncore + :synopsis: A base class for developing asynchronous socket handling + services. + +.. moduleauthor:: Sam Rushing +.. sectionauthor:: Christopher Petrilli +.. sectionauthor:: Steve Holden +.. heavily adapted from original documentation by Sam Rushing + +**Source code:** :source:`Lib/asyncore.py` + +.. deprecated:: 3.6 + Please use :mod:`asyncio` instead. + +-------------- + +.. note:: + + This module exists for backwards compatibility only. For new code we + recommend using :mod:`asyncio`. + +This module provides the basic infrastructure for writing asynchronous socket +service clients and servers. + +There are only two ways to have a program on a single processor do "more than +one thing at a time." Multi-threaded programming is the simplest and most +popular way to do it, but there is another very different technique, that lets +you have nearly all the advantages of multi-threading, without actually using +multiple threads. It's really only practical if your program is largely I/O +bound. If your program is processor bound, then pre-emptive scheduled threads +are probably what you really need. Network servers are rarely processor +bound, however. + +If your operating system supports the :c:func:`select` system call in its I/O +library (and nearly all do), then you can use it to juggle multiple +communication channels at once; doing other work while your I/O is taking +place in the "background." Although this strategy can seem strange and +complex, especially at first, it is in many ways easier to understand and +control than multi-threaded programming. The :mod:`asyncore` module solves +many of the difficult problems for you, making the task of building +sophisticated high-performance network servers and clients a snap. For +"conversational" applications and protocols the companion :mod:`asynchat` +module is invaluable. + +The basic idea behind both modules is to create one or more network +*channels*, instances of class :class:`asyncore.dispatcher` and +:class:`asynchat.async_chat`. Creating the channels adds them to a global +map, used by the :func:`loop` function if you do not provide it with your own +*map*. + +Once the initial channel(s) is(are) created, calling the :func:`loop` function +activates channel service, which continues until the last channel (including +any that have been added to the map during asynchronous service) is closed. + + +.. function:: loop([timeout[, use_poll[, map[,count]]]]) + + Enter a polling loop that terminates after count passes or all open + channels have been closed. All arguments are optional. The *count* + parameter defaults to ``None``, resulting in the loop terminating only when all + channels have been closed. The *timeout* argument sets the timeout + parameter for the appropriate :func:`~select.select` or :func:`~select.poll` + call, measured in seconds; the default is 30 seconds. The *use_poll* + parameter, if true, indicates that :func:`~select.poll` should be used in + preference to :func:`~select.select` (the default is ``False``). + + The *map* parameter is a dictionary whose items are the channels to watch. + As channels are closed they are deleted from their map. If *map* is + omitted, a global map is used. Channels (instances of + :class:`asyncore.dispatcher`, :class:`asynchat.async_chat` and subclasses + thereof) can freely be mixed in the map. + + +.. class:: dispatcher() + + The :class:`dispatcher` class is a thin wrapper around a low-level socket + object. To make it more useful, it has a few methods for event-handling + which are called from the asynchronous loop. Otherwise, it can be treated + as a normal non-blocking socket object. + + The firing of low-level events at certain times or in certain connection + states tells the asynchronous loop that certain higher-level events have + taken place. For example, if we have asked for a socket to connect to + another host, we know that the connection has been made when the socket + becomes writable for the first time (at this point you know that you may + write to it with the expectation of success). The implied higher-level + events are: + + +----------------------+----------------------------------------+ + | Event | Description | + +======================+========================================+ + | ``handle_connect()`` | Implied by the first read or write | + | | event | + +----------------------+----------------------------------------+ + | ``handle_close()`` | Implied by a read event with no data | + | | available | + +----------------------+----------------------------------------+ + | ``handle_accepted()``| Implied by a read event on a listening | + | | socket | + +----------------------+----------------------------------------+ + + During asynchronous processing, each mapped channel's :meth:`readable` and + :meth:`writable` methods are used to determine whether the channel's socket + should be added to the list of channels :c:func:`select`\ ed or + :c:func:`poll`\ ed for read and write events. + + Thus, the set of channel events is larger than the basic socket events. The + full set of methods that can be overridden in your subclass follows: + + + .. method:: handle_read() + + Called when the asynchronous loop detects that a :meth:`read` call on the + channel's socket will succeed. + + + .. method:: handle_write() + + Called when the asynchronous loop detects that a writable socket can be + written. Often this method will implement the necessary buffering for + performance. For example:: + + def handle_write(self): + sent = self.send(self.buffer) + self.buffer = self.buffer[sent:] + + + .. method:: handle_expt() + + Called when there is out of band (OOB) data for a socket connection. This + will almost never happen, as OOB is tenuously supported and rarely used. + + + .. method:: handle_connect() + + Called when the active opener's socket actually makes a connection. Might + send a "welcome" banner, or initiate a protocol negotiation with the + remote endpoint, for example. + + + .. method:: handle_close() + + Called when the socket is closed. + + + .. method:: handle_error() + + Called when an exception is raised and not otherwise handled. The default + version prints a condensed traceback. + + + .. method:: handle_accept() + + Called on listening channels (passive openers) when a connection can be + established with a new remote endpoint that has issued a :meth:`connect` + call for the local endpoint. Deprecated in version 3.2; use + :meth:`handle_accepted` instead. + + .. deprecated:: 3.2 + + + .. method:: handle_accepted(sock, addr) + + Called on listening channels (passive openers) when a connection has been + established with a new remote endpoint that has issued a :meth:`connect` + call for the local endpoint. *sock* is a *new* socket object usable to + send and receive data on the connection, and *addr* is the address + bound to the socket on the other end of the connection. + + .. versionadded:: 3.2 + + + .. method:: readable() + + Called each time around the asynchronous loop to determine whether a + channel's socket should be added to the list on which read events can + occur. The default method simply returns ``True``, indicating that by + default, all channels will be interested in read events. + + + .. method:: writable() + + Called each time around the asynchronous loop to determine whether a + channel's socket should be added to the list on which write events can + occur. The default method simply returns ``True``, indicating that by + default, all channels will be interested in write events. + + + In addition, each channel delegates or extends many of the socket methods. + Most of these are nearly identical to their socket partners. + + + .. method:: create_socket(family=socket.AF_INET, type=socket.SOCK_STREAM) + + This is identical to the creation of a normal socket, and will use the + same options for creation. Refer to the :mod:`socket` documentation for + information on creating sockets. + + .. versionchanged:: 3.3 + *family* and *type* arguments can be omitted. + + + .. method:: connect(address) + + As with the normal socket object, *address* is a tuple with the first + element the host to connect to, and the second the port number. + + + .. method:: send(data) + + Send *data* to the remote end-point of the socket. + + + .. method:: recv(buffer_size) + + Read at most *buffer_size* bytes from the socket's remote end-point. An + empty bytes object implies that the channel has been closed from the + other end. + + Note that :meth:`recv` may raise :exc:`BlockingIOError` , even though + :func:`select.select` or :func:`select.poll` has reported the socket + ready for reading. + + + .. method:: listen(backlog) + + Listen for connections made to the socket. The *backlog* argument + specifies the maximum number of queued connections and should be at least + 1; the maximum value is system-dependent (usually 5). + + + .. method:: bind(address) + + Bind the socket to *address*. The socket must not already be bound. (The + format of *address* depends on the address family --- refer to the + :mod:`socket` documentation for more information.) To mark + the socket as re-usable (setting the :const:`SO_REUSEADDR` option), call + the :class:`dispatcher` object's :meth:`set_reuse_addr` method. + + + .. method:: accept() + + Accept a connection. The socket must be bound to an address and listening + for connections. The return value can be either ``None`` or a pair + ``(conn, address)`` where *conn* is a *new* socket object usable to send + and receive data on the connection, and *address* is the address bound to + the socket on the other end of the connection. + When ``None`` is returned it means the connection didn't take place, in + which case the server should just ignore this event and keep listening + for further incoming connections. + + + .. method:: close() + + Close the socket. All future operations on the socket object will fail. + The remote end-point will receive no more data (after queued data is + flushed). Sockets are automatically closed when they are + garbage-collected. + + +.. class:: dispatcher_with_send() + + A :class:`dispatcher` subclass which adds simple buffered output capability, + useful for simple clients. For more sophisticated usage use + :class:`asynchat.async_chat`. + +.. class:: file_dispatcher() + + A file_dispatcher takes a file descriptor or :term:`file object` along + with an optional map argument and wraps it for use with the :c:func:`poll` + or :c:func:`loop` functions. If provided a file object or anything with a + :c:func:`fileno` method, that method will be called and passed to the + :class:`file_wrapper` constructor. + + .. availability:: Unix. + +.. class:: file_wrapper() + + A file_wrapper takes an integer file descriptor and calls :func:`os.dup` to + duplicate the handle so that the original handle may be closed independently + of the file_wrapper. This class implements sufficient methods to emulate a + socket for use by the :class:`file_dispatcher` class. + + .. availability:: Unix. + + +.. _asyncore-example-1: + +asyncore Example basic HTTP client +---------------------------------- + +Here is a very basic HTTP client that uses the :class:`dispatcher` class to +implement its socket handling:: + + import asyncore + + class HTTPClient(asyncore.dispatcher): + + def __init__(self, host, path): + asyncore.dispatcher.__init__(self) + self.create_socket() + self.connect( (host, 80) ) + self.buffer = bytes('GET %s HTTP/1.0\r\nHost: %s\r\n\r\n' % + (path, host), 'ascii') + + def handle_connect(self): + pass + + def handle_close(self): + self.close() + + def handle_read(self): + print(self.recv(8192)) + + def writable(self): + return (len(self.buffer) > 0) + + def handle_write(self): + sent = self.send(self.buffer) + self.buffer = self.buffer[sent:] + + + client = HTTPClient('www.python.org', '/') + asyncore.loop() + +.. _asyncore-example-2: + +asyncore Example basic echo server +---------------------------------- + +Here is a basic echo server that uses the :class:`dispatcher` class to accept +connections and dispatches the incoming connections to a handler:: + + import asyncore + + class EchoHandler(asyncore.dispatcher_with_send): + + def handle_read(self): + data = self.recv(8192) + if data: + self.send(data) + + class EchoServer(asyncore.dispatcher): + + def __init__(self, host, port): + asyncore.dispatcher.__init__(self) + self.create_socket() + self.set_reuse_addr() + self.bind((host, port)) + self.listen(5) + + def handle_accepted(self, sock, addr): + print('Incoming connection from %s' % repr(addr)) + handler = EchoHandler(sock) + + server = EchoServer('localhost', 8080) + asyncore.loop() diff --git a/cpython_2/environment/repo/Doc/library/atexit.rst b/cpython_2/environment/repo/Doc/library/atexit.rst new file mode 100644 index 0000000000000000000000000000000000000000..c2c058e474cbdcde2a3ef1fdcde33ebaa8539fad --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/atexit.rst @@ -0,0 +1,112 @@ +:mod:`atexit` --- Exit handlers +=============================== + +.. module:: atexit + :synopsis: Register and execute cleanup functions. + +.. moduleauthor:: Skip Montanaro +.. sectionauthor:: Skip Montanaro + +-------------- + +The :mod:`atexit` module defines functions to register and unregister cleanup +functions. Functions thus registered are automatically executed upon normal +interpreter termination. :mod:`atexit` runs these functions in the *reverse* +order in which they were registered; if you register ``A``, ``B``, and ``C``, +at interpreter termination time they will be run in the order ``C``, ``B``, +``A``. + +**Note:** The functions registered via this module are not called when the +program is killed by a signal not handled by Python, when a Python fatal +internal error is detected, or when :func:`os._exit` is called. + +.. versionchanged:: 3.7 + When used with C-API subinterpreters, registered functions + are local to the interpreter they were registered in. + +.. function:: register(func, *args, **kwargs) + + Register *func* as a function to be executed at termination. Any optional + arguments that are to be passed to *func* must be passed as arguments to + :func:`register`. It is possible to register the same function and arguments + more than once. + + At normal program termination (for instance, if :func:`sys.exit` is called or + the main module's execution completes), all functions registered are called in + last in, first out order. The assumption is that lower level modules will + normally be imported before higher level modules and thus must be cleaned up + later. + + If an exception is raised during execution of the exit handlers, a traceback is + printed (unless :exc:`SystemExit` is raised) and the exception information is + saved. After all exit handlers have had a chance to run the last exception to + be raised is re-raised. + + This function returns *func*, which makes it possible to use it as a + decorator. + + +.. function:: unregister(func) + + Remove *func* from the list of functions to be run at interpreter + shutdown. After calling :func:`unregister`, *func* is guaranteed not to be + called when the interpreter shuts down, even if it was registered more than + once. :func:`unregister` silently does nothing if *func* was not previously + registered. + + +.. seealso:: + + Module :mod:`readline` + Useful example of :mod:`atexit` to read and write :mod:`readline` history + files. + + +.. _atexit-example: + +:mod:`atexit` Example +--------------------- + +The following simple example demonstrates how a module can initialize a counter +from a file when it is imported and save the counter's updated value +automatically when the program terminates without relying on the application +making an explicit call into this module at termination. :: + + try: + with open("counterfile") as infile: + _count = int(infile.read()) + except FileNotFoundError: + _count = 0 + + def incrcounter(n): + global _count + _count = _count + n + + def savecounter(): + with open("counterfile", "w") as outfile: + outfile.write("%d" % _count) + + import atexit + atexit.register(savecounter) + +Positional and keyword arguments may also be passed to :func:`register` to be +passed along to the registered function when it is called:: + + def goodbye(name, adjective): + print('Goodbye, %s, it was %s to meet you.' % (name, adjective)) + + import atexit + atexit.register(goodbye, 'Donny', 'nice') + + # or: + atexit.register(goodbye, adjective='nice', name='Donny') + +Usage as a :term:`decorator`:: + + import atexit + + @atexit.register + def goodbye(): + print("You are now leaving the Python sector.") + +This only works with functions that can be called without arguments. diff --git a/cpython_2/environment/repo/Doc/library/audioop.rst b/cpython_2/environment/repo/Doc/library/audioop.rst new file mode 100644 index 0000000000000000000000000000000000000000..bad9da2ec62e565d50bfdd0ed45519251f07ae35 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/audioop.rst @@ -0,0 +1,282 @@ +:mod:`audioop` --- Manipulate raw audio data +============================================ + +.. module:: audioop + :synopsis: Manipulate raw audio data. + +-------------- + +The :mod:`audioop` module contains some useful operations on sound fragments. +It operates on sound fragments consisting of signed integer samples 8, 16, 24 +or 32 bits wide, stored in :term:`bytes-like objects `. All scalar items are +integers, unless specified otherwise. + +.. versionchanged:: 3.4 + Support for 24-bit samples was added. + All functions now accept any :term:`bytes-like object`. + String input now results in an immediate error. + +.. index:: + single: Intel/DVI ADPCM + single: ADPCM, Intel/DVI + single: a-LAW + single: u-LAW + +This module provides support for a-LAW, u-LAW and Intel/DVI ADPCM encodings. + +.. This para is mostly here to provide an excuse for the index entries... + +A few of the more complicated operations only take 16-bit samples, otherwise the +sample size (in bytes) is always a parameter of the operation. + +The module defines the following variables and functions: + + +.. exception:: error + + This exception is raised on all errors, such as unknown number of bytes per + sample, etc. + + +.. function:: add(fragment1, fragment2, width) + + Return a fragment which is the addition of the two samples passed as parameters. + *width* is the sample width in bytes, either ``1``, ``2``, ``3`` or ``4``. Both + fragments should have the same length. Samples are truncated in case of overflow. + + +.. function:: adpcm2lin(adpcmfragment, width, state) + + Decode an Intel/DVI ADPCM coded fragment to a linear fragment. See the + description of :func:`lin2adpcm` for details on ADPCM coding. Return a tuple + ``(sample, newstate)`` where the sample has the width specified in *width*. + + +.. function:: alaw2lin(fragment, width) + + Convert sound fragments in a-LAW encoding to linearly encoded sound fragments. + a-LAW encoding always uses 8 bits samples, so *width* refers only to the sample + width of the output fragment here. + + +.. function:: avg(fragment, width) + + Return the average over all samples in the fragment. + + +.. function:: avgpp(fragment, width) + + Return the average peak-peak value over all samples in the fragment. No + filtering is done, so the usefulness of this routine is questionable. + + +.. function:: bias(fragment, width, bias) + + Return a fragment that is the original fragment with a bias added to each + sample. Samples wrap around in case of overflow. + + +.. function:: byteswap(fragment, width) + + "Byteswap" all samples in a fragment and returns the modified fragment. + Converts big-endian samples to little-endian and vice versa. + + .. versionadded:: 3.4 + + +.. function:: cross(fragment, width) + + Return the number of zero crossings in the fragment passed as an argument. + + +.. function:: findfactor(fragment, reference) + + Return a factor *F* such that ``rms(add(fragment, mul(reference, -F)))`` is + minimal, i.e., return the factor with which you should multiply *reference* to + make it match as well as possible to *fragment*. The fragments should both + contain 2-byte samples. + + The time taken by this routine is proportional to ``len(fragment)``. + + +.. function:: findfit(fragment, reference) + + Try to match *reference* as well as possible to a portion of *fragment* (which + should be the longer fragment). This is (conceptually) done by taking slices + out of *fragment*, using :func:`findfactor` to compute the best match, and + minimizing the result. The fragments should both contain 2-byte samples. + Return a tuple ``(offset, factor)`` where *offset* is the (integer) offset into + *fragment* where the optimal match started and *factor* is the (floating-point) + factor as per :func:`findfactor`. + + +.. function:: findmax(fragment, length) + + Search *fragment* for a slice of length *length* samples (not bytes!) with + maximum energy, i.e., return *i* for which ``rms(fragment[i*2:(i+length)*2])`` + is maximal. The fragments should both contain 2-byte samples. + + The routine takes time proportional to ``len(fragment)``. + + +.. function:: getsample(fragment, width, index) + + Return the value of sample *index* from the fragment. + + +.. function:: lin2adpcm(fragment, width, state) + + Convert samples to 4 bit Intel/DVI ADPCM encoding. ADPCM coding is an adaptive + coding scheme, whereby each 4 bit number is the difference between one sample + and the next, divided by a (varying) step. The Intel/DVI ADPCM algorithm has + been selected for use by the IMA, so it may well become a standard. + + *state* is a tuple containing the state of the coder. The coder returns a tuple + ``(adpcmfrag, newstate)``, and the *newstate* should be passed to the next call + of :func:`lin2adpcm`. In the initial call, ``None`` can be passed as the state. + *adpcmfrag* is the ADPCM coded fragment packed 2 4-bit values per byte. + + +.. function:: lin2alaw(fragment, width) + + Convert samples in the audio fragment to a-LAW encoding and return this as a + bytes object. a-LAW is an audio encoding format whereby you get a dynamic + range of about 13 bits using only 8 bit samples. It is used by the Sun audio + hardware, among others. + + +.. function:: lin2lin(fragment, width, newwidth) + + Convert samples between 1-, 2-, 3- and 4-byte formats. + + .. note:: + + In some audio formats, such as .WAV files, 16, 24 and 32 bit samples are + signed, but 8 bit samples are unsigned. So when converting to 8 bit wide + samples for these formats, you need to also add 128 to the result:: + + new_frames = audioop.lin2lin(frames, old_width, 1) + new_frames = audioop.bias(new_frames, 1, 128) + + The same, in reverse, has to be applied when converting from 8 to 16, 24 + or 32 bit width samples. + + +.. function:: lin2ulaw(fragment, width) + + Convert samples in the audio fragment to u-LAW encoding and return this as a + bytes object. u-LAW is an audio encoding format whereby you get a dynamic + range of about 14 bits using only 8 bit samples. It is used by the Sun audio + hardware, among others. + + +.. function:: max(fragment, width) + + Return the maximum of the *absolute value* of all samples in a fragment. + + +.. function:: maxpp(fragment, width) + + Return the maximum peak-peak value in the sound fragment. + + +.. function:: minmax(fragment, width) + + Return a tuple consisting of the minimum and maximum values of all samples in + the sound fragment. + + +.. function:: mul(fragment, width, factor) + + Return a fragment that has all samples in the original fragment multiplied by + the floating-point value *factor*. Samples are truncated in case of overflow. + + +.. function:: ratecv(fragment, width, nchannels, inrate, outrate, state[, weightA[, weightB]]) + + Convert the frame rate of the input fragment. + + *state* is a tuple containing the state of the converter. The converter returns + a tuple ``(newfragment, newstate)``, and *newstate* should be passed to the next + call of :func:`ratecv`. The initial call should pass ``None`` as the state. + + The *weightA* and *weightB* arguments are parameters for a simple digital filter + and default to ``1`` and ``0`` respectively. + + +.. function:: reverse(fragment, width) + + Reverse the samples in a fragment and returns the modified fragment. + + +.. function:: rms(fragment, width) + + Return the root-mean-square of the fragment, i.e. ``sqrt(sum(S_i^2)/n)``. + + This is a measure of the power in an audio signal. + + +.. function:: tomono(fragment, width, lfactor, rfactor) + + Convert a stereo fragment to a mono fragment. The left channel is multiplied by + *lfactor* and the right channel by *rfactor* before adding the two channels to + give a mono signal. + + +.. function:: tostereo(fragment, width, lfactor, rfactor) + + Generate a stereo fragment from a mono fragment. Each pair of samples in the + stereo fragment are computed from the mono sample, whereby left channel samples + are multiplied by *lfactor* and right channel samples by *rfactor*. + + +.. function:: ulaw2lin(fragment, width) + + Convert sound fragments in u-LAW encoding to linearly encoded sound fragments. + u-LAW encoding always uses 8 bits samples, so *width* refers only to the sample + width of the output fragment here. + +Note that operations such as :func:`.mul` or :func:`.max` make no distinction +between mono and stereo fragments, i.e. all samples are treated equal. If this +is a problem the stereo fragment should be split into two mono fragments first +and recombined later. Here is an example of how to do that:: + + def mul_stereo(sample, width, lfactor, rfactor): + lsample = audioop.tomono(sample, width, 1, 0) + rsample = audioop.tomono(sample, width, 0, 1) + lsample = audioop.mul(lsample, width, lfactor) + rsample = audioop.mul(rsample, width, rfactor) + lsample = audioop.tostereo(lsample, width, 1, 0) + rsample = audioop.tostereo(rsample, width, 0, 1) + return audioop.add(lsample, rsample, width) + +If you use the ADPCM coder to build network packets and you want your protocol +to be stateless (i.e. to be able to tolerate packet loss) you should not only +transmit the data but also the state. Note that you should send the *initial* +state (the one you passed to :func:`lin2adpcm`) along to the decoder, not the +final state (as returned by the coder). If you want to use +:class:`struct.Struct` to store the state in binary you can code the first +element (the predicted value) in 16 bits and the second (the delta index) in 8. + +The ADPCM coders have never been tried against other ADPCM coders, only against +themselves. It could well be that I misinterpreted the standards in which case +they will not be interoperable with the respective standards. + +The :func:`find\*` routines might look a bit funny at first sight. They are +primarily meant to do echo cancellation. A reasonably fast way to do this is to +pick the most energetic piece of the output sample, locate that in the input +sample and subtract the whole output sample from the input sample:: + + def echocancel(outputdata, inputdata): + pos = audioop.findmax(outputdata, 800) # one tenth second + out_test = outputdata[pos*2:] + in_test = inputdata[pos*2:] + ipos, factor = audioop.findfit(in_test, out_test) + # Optional (for better cancellation): + # factor = audioop.findfactor(in_test[ipos*2:ipos*2+len(out_test)], + # out_test) + prefill = '\0'*(pos+ipos)*2 + postfill = '\0'*(len(inputdata)-len(prefill)-len(outputdata)) + outputdata = prefill + audioop.mul(outputdata, 2, -factor) + postfill + return audioop.add(inputdata, outputdata, 2) + diff --git a/cpython_2/environment/repo/Doc/library/audit_events.rst b/cpython_2/environment/repo/Doc/library/audit_events.rst new file mode 100644 index 0000000000000000000000000000000000000000..3c68a1515b3effbc4b5efef985f4f1ab87ebc833 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/audit_events.rst @@ -0,0 +1,21 @@ +.. _audit-events: + +.. index:: single: audit events + +Audit events table +================== + +This table contains all events raised by :func:`sys.audit` or +:c:func:`PySys_Audit` calls throughout the CPython runtime and the +standard library. These calls were added in 3.8.0 or later. + +See :func:`sys.addaudithook` and :c:func:`PySys_AddAuditHook` for +information on handling these events. + +.. impl-detail:: + + This table is generated from the CPython documentation, and may not + represent events raised by other implementations. See your runtime + specific documentation for actual events raised. + +.. audit-event-table:: diff --git a/cpython_2/environment/repo/Doc/library/base64.rst b/cpython_2/environment/repo/Doc/library/base64.rst new file mode 100644 index 0000000000000000000000000000000000000000..1ff22a00d6199de0b79e1d37fbea32d3bd6657e9 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/base64.rst @@ -0,0 +1,278 @@ +:mod:`base64` --- Base16, Base32, Base64, Base85 Data Encodings +=============================================================== + +.. module:: base64 + :synopsis: RFC 3548: Base16, Base32, Base64 Data Encodings; + Base85 and Ascii85 + +**Source code:** :source:`Lib/base64.py` + +.. index:: + pair: base64; encoding + single: MIME; base64 encoding + +-------------- + +This module provides functions for encoding binary data to printable +ASCII characters and decoding such encodings back to binary data. +It provides encoding and decoding functions for the encodings specified in +:rfc:`3548`, which defines the Base16, Base32, and Base64 algorithms, +and for the de-facto standard Ascii85 and Base85 encodings. + +The :rfc:`3548` encodings are suitable for encoding binary data so that it can +safely sent by email, used as parts of URLs, or included as part of an HTTP +POST request. The encoding algorithm is not the same as the +:program:`uuencode` program. + +There are two interfaces provided by this module. The modern interface +supports encoding :term:`bytes-like objects ` to ASCII +:class:`bytes`, and decoding :term:`bytes-like objects ` or +strings containing ASCII to :class:`bytes`. Both base-64 alphabets +defined in :rfc:`3548` (normal, and URL- and filesystem-safe) are supported. + +The legacy interface does not support decoding from strings, but it does +provide functions for encoding and decoding to and from :term:`file objects +`. It only supports the Base64 standard alphabet, and it adds +newlines every 76 characters as per :rfc:`2045`. Note that if you are looking +for :rfc:`2045` support you probably want to be looking at the :mod:`email` +package instead. + + +.. versionchanged:: 3.3 + ASCII-only Unicode strings are now accepted by the decoding functions of + the modern interface. + +.. versionchanged:: 3.4 + Any :term:`bytes-like objects ` are now accepted by all + encoding and decoding functions in this module. Ascii85/Base85 support added. + +The modern interface provides: + +.. function:: b64encode(s, altchars=None) + + Encode the :term:`bytes-like object` *s* using Base64 and return the encoded + :class:`bytes`. + + Optional *altchars* must be a :term:`bytes-like object` of at least + length 2 (additional characters are ignored) which specifies an alternative + alphabet for the ``+`` and ``/`` characters. This allows an application to e.g. + generate URL or filesystem safe Base64 strings. The default is ``None``, for + which the standard Base64 alphabet is used. + + +.. function:: b64decode(s, altchars=None, validate=False) + + Decode the Base64 encoded :term:`bytes-like object` or ASCII string + *s* and return the decoded :class:`bytes`. + + Optional *altchars* must be a :term:`bytes-like object` or ASCII string of + at least length 2 (additional characters are ignored) which specifies the + alternative alphabet used instead of the ``+`` and ``/`` characters. + + A :exc:`binascii.Error` exception is raised + if *s* is incorrectly padded. + + If *validate* is ``False`` (the default), characters that are neither + in the normal base-64 alphabet nor the alternative alphabet are + discarded prior to the padding check. If *validate* is ``True``, + these non-alphabet characters in the input result in a + :exc:`binascii.Error`. + + +.. function:: standard_b64encode(s) + + Encode :term:`bytes-like object` *s* using the standard Base64 alphabet + and return the encoded :class:`bytes`. + + +.. function:: standard_b64decode(s) + + Decode :term:`bytes-like object` or ASCII string *s* using the standard + Base64 alphabet and return the decoded :class:`bytes`. + + +.. function:: urlsafe_b64encode(s) + + Encode :term:`bytes-like object` *s* using the + URL- and filesystem-safe alphabet, which + substitutes ``-`` instead of ``+`` and ``_`` instead of ``/`` in the + standard Base64 alphabet, and return the encoded :class:`bytes`. The result + can still contain ``=``. + + +.. function:: urlsafe_b64decode(s) + + Decode :term:`bytes-like object` or ASCII string *s* + using the URL- and filesystem-safe + alphabet, which substitutes ``-`` instead of ``+`` and ``_`` instead of + ``/`` in the standard Base64 alphabet, and return the decoded + :class:`bytes`. + + +.. function:: b32encode(s) + + Encode the :term:`bytes-like object` *s* using Base32 and return the + encoded :class:`bytes`. + + +.. function:: b32decode(s, casefold=False, map01=None) + + Decode the Base32 encoded :term:`bytes-like object` or ASCII string *s* and + return the decoded :class:`bytes`. + + Optional *casefold* is a flag specifying + whether a lowercase alphabet is acceptable as input. For security purposes, + the default is ``False``. + + :rfc:`3548` allows for optional mapping of the digit 0 (zero) to the letter O + (oh), and for optional mapping of the digit 1 (one) to either the letter I (eye) + or letter L (el). The optional argument *map01* when not ``None``, specifies + which letter the digit 1 should be mapped to (when *map01* is not ``None``, the + digit 0 is always mapped to the letter O). For security purposes the default is + ``None``, so that 0 and 1 are not allowed in the input. + + A :exc:`binascii.Error` is raised if *s* is + incorrectly padded or if there are non-alphabet characters present in the + input. + + +.. function:: b16encode(s) + + Encode the :term:`bytes-like object` *s* using Base16 and return the + encoded :class:`bytes`. + + +.. function:: b16decode(s, casefold=False) + + Decode the Base16 encoded :term:`bytes-like object` or ASCII string *s* and + return the decoded :class:`bytes`. + + Optional *casefold* is a flag specifying whether a + lowercase alphabet is acceptable as input. For security purposes, the default + is ``False``. + + A :exc:`binascii.Error` is raised if *s* is + incorrectly padded or if there are non-alphabet characters present in the + input. + + +.. function:: a85encode(b, *, foldspaces=False, wrapcol=0, pad=False, adobe=False) + + Encode the :term:`bytes-like object` *b* using Ascii85 and return the + encoded :class:`bytes`. + + *foldspaces* is an optional flag that uses the special short sequence 'y' + instead of 4 consecutive spaces (ASCII 0x20) as supported by 'btoa'. This + feature is not supported by the "standard" Ascii85 encoding. + + *wrapcol* controls whether the output should have newline (``b'\n'``) + characters added to it. If this is non-zero, each output line will be + at most this many characters long. + + *pad* controls whether the input is padded to a multiple of 4 + before encoding. Note that the ``btoa`` implementation always pads. + + *adobe* controls whether the encoded byte sequence is framed with ``<~`` + and ``~>``, which is used by the Adobe implementation. + + .. versionadded:: 3.4 + + +.. function:: a85decode(b, *, foldspaces=False, adobe=False, ignorechars=b' \\t\\n\\r\\v') + + Decode the Ascii85 encoded :term:`bytes-like object` or ASCII string *b* and + return the decoded :class:`bytes`. + + *foldspaces* is a flag that specifies whether the 'y' short sequence + should be accepted as shorthand for 4 consecutive spaces (ASCII 0x20). + This feature is not supported by the "standard" Ascii85 encoding. + + *adobe* controls whether the input sequence is in Adobe Ascii85 format + (i.e. is framed with <~ and ~>). + + *ignorechars* should be a :term:`bytes-like object` or ASCII string + containing characters to ignore + from the input. This should only contain whitespace characters, and by + default contains all whitespace characters in ASCII. + + .. versionadded:: 3.4 + + +.. function:: b85encode(b, pad=False) + + Encode the :term:`bytes-like object` *b* using base85 (as used in e.g. + git-style binary diffs) and return the encoded :class:`bytes`. + + If *pad* is true, the input is padded with ``b'\0'`` so its length is a + multiple of 4 bytes before encoding. + + .. versionadded:: 3.4 + + +.. function:: b85decode(b) + + Decode the base85-encoded :term:`bytes-like object` or ASCII string *b* and + return the decoded :class:`bytes`. Padding is implicitly removed, if + necessary. + + .. versionadded:: 3.4 + + +The legacy interface: + +.. function:: decode(input, output) + + Decode the contents of the binary *input* file and write the resulting binary + data to the *output* file. *input* and *output* must be :term:`file objects + `. *input* will be read until ``input.readline()`` returns an + empty bytes object. + + +.. function:: decodebytes(s) + + Decode the :term:`bytes-like object` *s*, which must contain one or more + lines of base64 encoded data, and return the decoded :class:`bytes`. + + .. versionadded:: 3.1 + + +.. function:: encode(input, output) + + Encode the contents of the binary *input* file and write the resulting base64 + encoded data to the *output* file. *input* and *output* must be :term:`file + objects `. *input* will be read until ``input.read()`` returns + an empty bytes object. :func:`encode` inserts a newline character (``b'\n'``) + after every 76 bytes of the output, as well as ensuring that the output + always ends with a newline, as per :rfc:`2045` (MIME). + + +.. function:: encodebytes(s) + + Encode the :term:`bytes-like object` *s*, which can contain arbitrary binary + data, and return :class:`bytes` containing the base64-encoded data, with newlines + (``b'\n'``) inserted after every 76 bytes of output, and ensuring that + there is a trailing newline, as per :rfc:`2045` (MIME). + + .. versionadded:: 3.1 + + +An example usage of the module: + + >>> import base64 + >>> encoded = base64.b64encode(b'data to be encoded') + >>> encoded + b'ZGF0YSB0byBiZSBlbmNvZGVk' + >>> data = base64.b64decode(encoded) + >>> data + b'data to be encoded' + + +.. seealso:: + + Module :mod:`binascii` + Support module containing ASCII-to-binary and binary-to-ASCII conversions. + + :rfc:`1521` - MIME (Multipurpose Internet Mail Extensions) Part One: Mechanisms for Specifying and Describing the Format of Internet Message Bodies + Section 5.2, "Base64 Content-Transfer-Encoding," provides the definition of the + base64 encoding. + diff --git a/cpython_2/environment/repo/Doc/library/bdb.rst b/cpython_2/environment/repo/Doc/library/bdb.rst new file mode 100644 index 0000000000000000000000000000000000000000..7e4066cd436ad538136c0d2d4d644bdb3ec8437b --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/bdb.rst @@ -0,0 +1,372 @@ +:mod:`bdb` --- Debugger framework +================================= + +.. module:: bdb + :synopsis: Debugger framework. + +**Source code:** :source:`Lib/bdb.py` + +-------------- + +The :mod:`bdb` module handles basic debugger functions, like setting breakpoints +or managing execution via the debugger. + +The following exception is defined: + +.. exception:: BdbQuit + + Exception raised by the :class:`Bdb` class for quitting the debugger. + + +The :mod:`bdb` module also defines two classes: + +.. class:: Breakpoint(self, file, line, temporary=0, cond=None, funcname=None) + + This class implements temporary breakpoints, ignore counts, disabling and + (re-)enabling, and conditionals. + + Breakpoints are indexed by number through a list called :attr:`bpbynumber` + and by ``(file, line)`` pairs through :attr:`bplist`. The former points to a + single instance of class :class:`Breakpoint`. The latter points to a list of + such instances since there may be more than one breakpoint per line. + + When creating a breakpoint, its associated filename should be in canonical + form. If a *funcname* is defined, a breakpoint hit will be counted when the + first line of that function is executed. A conditional breakpoint always + counts a hit. + + :class:`Breakpoint` instances have the following methods: + + .. method:: deleteMe() + + Delete the breakpoint from the list associated to a file/line. If it is + the last breakpoint in that position, it also deletes the entry for the + file/line. + + + .. method:: enable() + + Mark the breakpoint as enabled. + + + .. method:: disable() + + Mark the breakpoint as disabled. + + + .. method:: bpformat() + + Return a string with all the information about the breakpoint, nicely + formatted: + + * The breakpoint number. + * If it is temporary or not. + * Its file,line position. + * The condition that causes a break. + * If it must be ignored the next N times. + * The breakpoint hit count. + + .. versionadded:: 3.2 + + .. method:: bpprint(out=None) + + Print the output of :meth:`bpformat` to the file *out*, or if it is + ``None``, to standard output. + + +.. class:: Bdb(skip=None) + + The :class:`Bdb` class acts as a generic Python debugger base class. + + This class takes care of the details of the trace facility; a derived class + should implement user interaction. The standard debugger class + (:class:`pdb.Pdb`) is an example. + + The *skip* argument, if given, must be an iterable of glob-style + module name patterns. The debugger will not step into frames that + originate in a module that matches one of these patterns. Whether a + frame is considered to originate in a certain module is determined + by the ``__name__`` in the frame globals. + + .. versionadded:: 3.1 + The *skip* argument. + + The following methods of :class:`Bdb` normally don't need to be overridden. + + .. method:: canonic(filename) + + Auxiliary method for getting a filename in a canonical form, that is, as a + case-normalized (on case-insensitive filesystems) absolute path, stripped + of surrounding angle brackets. + + .. method:: reset() + + Set the :attr:`botframe`, :attr:`stopframe`, :attr:`returnframe` and + :attr:`quitting` attributes with values ready to start debugging. + + .. method:: trace_dispatch(frame, event, arg) + + This function is installed as the trace function of debugged frames. Its + return value is the new trace function (in most cases, that is, itself). + + The default implementation decides how to dispatch a frame, depending on + the type of event (passed as a string) that is about to be executed. + *event* can be one of the following: + + * ``"line"``: A new line of code is going to be executed. + * ``"call"``: A function is about to be called, or another code block + entered. + * ``"return"``: A function or other code block is about to return. + * ``"exception"``: An exception has occurred. + * ``"c_call"``: A C function is about to be called. + * ``"c_return"``: A C function has returned. + * ``"c_exception"``: A C function has raised an exception. + + For the Python events, specialized functions (see below) are called. For + the C events, no action is taken. + + The *arg* parameter depends on the previous event. + + See the documentation for :func:`sys.settrace` for more information on the + trace function. For more information on code and frame objects, refer to + :ref:`types`. + + .. method:: dispatch_line(frame) + + If the debugger should stop on the current line, invoke the + :meth:`user_line` method (which should be overridden in subclasses). + Raise a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set + (which can be set from :meth:`user_line`). Return a reference to the + :meth:`trace_dispatch` method for further tracing in that scope. + + .. method:: dispatch_call(frame, arg) + + If the debugger should stop on this function call, invoke the + :meth:`user_call` method (which should be overridden in subclasses). + Raise a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set + (which can be set from :meth:`user_call`). Return a reference to the + :meth:`trace_dispatch` method for further tracing in that scope. + + .. method:: dispatch_return(frame, arg) + + If the debugger should stop on this function return, invoke the + :meth:`user_return` method (which should be overridden in subclasses). + Raise a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set + (which can be set from :meth:`user_return`). Return a reference to the + :meth:`trace_dispatch` method for further tracing in that scope. + + .. method:: dispatch_exception(frame, arg) + + If the debugger should stop at this exception, invokes the + :meth:`user_exception` method (which should be overridden in subclasses). + Raise a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set + (which can be set from :meth:`user_exception`). Return a reference to the + :meth:`trace_dispatch` method for further tracing in that scope. + + Normally derived classes don't override the following methods, but they may + if they want to redefine the definition of stopping and breakpoints. + + .. method:: stop_here(frame) + + This method checks if the *frame* is somewhere below :attr:`botframe` in + the call stack. :attr:`botframe` is the frame in which debugging started. + + .. method:: break_here(frame) + + This method checks if there is a breakpoint in the filename and line + belonging to *frame* or, at least, in the current function. If the + breakpoint is a temporary one, this method deletes it. + + .. method:: break_anywhere(frame) + + This method checks if there is a breakpoint in the filename of the current + frame. + + Derived classes should override these methods to gain control over debugger + operation. + + .. method:: user_call(frame, argument_list) + + This method is called from :meth:`dispatch_call` when there is the + possibility that a break might be necessary anywhere inside the called + function. + + .. method:: user_line(frame) + + This method is called from :meth:`dispatch_line` when either + :meth:`stop_here` or :meth:`break_here` yields ``True``. + + .. method:: user_return(frame, return_value) + + This method is called from :meth:`dispatch_return` when :meth:`stop_here` + yields ``True``. + + .. method:: user_exception(frame, exc_info) + + This method is called from :meth:`dispatch_exception` when + :meth:`stop_here` yields ``True``. + + .. method:: do_clear(arg) + + Handle how a breakpoint must be removed when it is a temporary one. + + This method must be implemented by derived classes. + + + Derived classes and clients can call the following methods to affect the + stepping state. + + .. method:: set_step() + + Stop after one line of code. + + .. method:: set_next(frame) + + Stop on the next line in or below the given frame. + + .. method:: set_return(frame) + + Stop when returning from the given frame. + + .. method:: set_until(frame) + + Stop when the line with the line no greater than the current one is + reached or when returning from current frame. + + .. method:: set_trace([frame]) + + Start debugging from *frame*. If *frame* is not specified, debugging + starts from caller's frame. + + .. method:: set_continue() + + Stop only at breakpoints or when finished. If there are no breakpoints, + set the system trace function to ``None``. + + .. method:: set_quit() + + Set the :attr:`quitting` attribute to ``True``. This raises :exc:`BdbQuit` in + the next call to one of the :meth:`dispatch_\*` methods. + + + Derived classes and clients can call the following methods to manipulate + breakpoints. These methods return a string containing an error message if + something went wrong, or ``None`` if all is well. + + .. method:: set_break(filename, lineno, temporary=0, cond, funcname) + + Set a new breakpoint. If the *lineno* line doesn't exist for the + *filename* passed as argument, return an error message. The *filename* + should be in canonical form, as described in the :meth:`canonic` method. + + .. method:: clear_break(filename, lineno) + + Delete the breakpoints in *filename* and *lineno*. If none were set, an + error message is returned. + + .. method:: clear_bpbynumber(arg) + + Delete the breakpoint which has the index *arg* in the + :attr:`Breakpoint.bpbynumber`. If *arg* is not numeric or out of range, + return an error message. + + .. method:: clear_all_file_breaks(filename) + + Delete all breakpoints in *filename*. If none were set, an error message + is returned. + + .. method:: clear_all_breaks() + + Delete all existing breakpoints. + + .. method:: get_bpbynumber(arg) + + Return a breakpoint specified by the given number. If *arg* is a string, + it will be converted to a number. If *arg* is a non-numeric string, if + the given breakpoint never existed or has been deleted, a + :exc:`ValueError` is raised. + + .. versionadded:: 3.2 + + .. method:: get_break(filename, lineno) + + Check if there is a breakpoint for *lineno* of *filename*. + + .. method:: get_breaks(filename, lineno) + + Return all breakpoints for *lineno* in *filename*, or an empty list if + none are set. + + .. method:: get_file_breaks(filename) + + Return all breakpoints in *filename*, or an empty list if none are set. + + .. method:: get_all_breaks() + + Return all breakpoints that are set. + + + Derived classes and clients can call the following methods to get a data + structure representing a stack trace. + + .. method:: get_stack(f, t) + + Get a list of records for a frame and all higher (calling) and lower + frames, and the size of the higher part. + + .. method:: format_stack_entry(frame_lineno, lprefix=': ') + + Return a string with information about a stack entry, identified by a + ``(frame, lineno)`` tuple: + + * The canonical form of the filename which contains the frame. + * The function name, or ``""``. + * The input arguments. + * The return value. + * The line of code (if it exists). + + + The following two methods can be called by clients to use a debugger to debug + a :term:`statement`, given as a string. + + .. method:: run(cmd, globals=None, locals=None) + + Debug a statement executed via the :func:`exec` function. *globals* + defaults to :attr:`__main__.__dict__`, *locals* defaults to *globals*. + + .. method:: runeval(expr, globals=None, locals=None) + + Debug an expression executed via the :func:`eval` function. *globals* and + *locals* have the same meaning as in :meth:`run`. + + .. method:: runctx(cmd, globals, locals) + + For backwards compatibility. Calls the :meth:`run` method. + + .. method:: runcall(func, /, *args, **kwds) + + Debug a single function call, and return its result. + + +Finally, the module defines the following functions: + +.. function:: checkfuncname(b, frame) + + Check whether we should break here, depending on the way the breakpoint *b* + was set. + + If it was set via line number, it checks if ``b.line`` is the same as the one + in the frame also passed as argument. If the breakpoint was set via function + name, we have to check we are in the right frame (the right function) and if + we are in its first executable line. + +.. function:: effective(file, line, frame) + + Determine if there is an effective (active) breakpoint at this line of code. + Return a tuple of the breakpoint and a boolean that indicates if it is ok + to delete a temporary breakpoint. Return ``(None, None)`` if there is no + matching breakpoint. + +.. function:: set_trace() + + Start debugging with a :class:`Bdb` instance from caller's frame. diff --git a/cpython_2/environment/repo/Doc/library/binary.rst b/cpython_2/environment/repo/Doc/library/binary.rst new file mode 100644 index 0000000000000000000000000000000000000000..51fbdc1a44b15d8781b6261d2fe44294158e38ed --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/binary.rst @@ -0,0 +1,23 @@ +.. _binaryservices: + +******************** +Binary Data Services +******************** + +The modules described in this chapter provide some basic services operations +for manipulation of binary data. Other operations on binary data, specifically +in relation to file formats and network protocols, are described in the +relevant sections. + +Some libraries described under :ref:`textservices` also work with either +ASCII-compatible binary formats (for example, :mod:`re`) or all binary data +(for example, :mod:`difflib`). + +In addition, see the documentation for Python's built-in binary data types in +:ref:`binaryseq`. + +.. toctree:: + + struct.rst + codecs.rst + diff --git a/cpython_2/environment/repo/Doc/library/binascii.rst b/cpython_2/environment/repo/Doc/library/binascii.rst new file mode 100644 index 0000000000000000000000000000000000000000..2c0c1bce5d7f8f9a0f18f0be815a0c4c5605b6df --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/binascii.rst @@ -0,0 +1,220 @@ +:mod:`binascii` --- Convert between binary and ASCII +==================================================== + +.. module:: binascii + :synopsis: Tools for converting between binary and various ASCII-encoded binary + representations. + +.. index:: + module: uu + module: base64 + module: binhex + +-------------- + +The :mod:`binascii` module contains a number of methods to convert between +binary and various ASCII-encoded binary representations. Normally, you will not +use these functions directly but use wrapper modules like :mod:`uu`, +:mod:`base64`, or :mod:`binhex` instead. The :mod:`binascii` module contains +low-level functions written in C for greater speed that are used by the +higher-level modules. + +.. note:: + + ``a2b_*`` functions accept Unicode strings containing only ASCII characters. + Other functions only accept :term:`bytes-like objects ` (such as + :class:`bytes`, :class:`bytearray` and other objects that support the buffer + protocol). + + .. versionchanged:: 3.3 + ASCII-only unicode strings are now accepted by the ``a2b_*`` functions. + + +The :mod:`binascii` module defines the following functions: + + +.. function:: a2b_uu(string) + + Convert a single line of uuencoded data back to binary and return the binary + data. Lines normally contain 45 (binary) bytes, except for the last line. Line + data may be followed by whitespace. + + +.. function:: b2a_uu(data, *, backtick=False) + + Convert binary data to a line of ASCII characters, the return value is the + converted line, including a newline char. The length of *data* should be at most + 45. If *backtick* is true, zeros are represented by ``'`'`` instead of spaces. + + .. versionchanged:: 3.7 + Added the *backtick* parameter. + + +.. function:: a2b_base64(string) + + Convert a block of base64 data back to binary and return the binary data. More + than one line may be passed at a time. + + +.. function:: b2a_base64(data, *, newline=True) + + Convert binary data to a line of ASCII characters in base64 coding. The return + value is the converted line, including a newline char if *newline* is + true. The output of this function conforms to :rfc:`3548`. + + .. versionchanged:: 3.6 + Added the *newline* parameter. + + +.. function:: a2b_qp(data, header=False) + + Convert a block of quoted-printable data back to binary and return the binary + data. More than one line may be passed at a time. If the optional argument + *header* is present and true, underscores will be decoded as spaces. + + +.. function:: b2a_qp(data, quotetabs=False, istext=True, header=False) + + Convert binary data to a line(s) of ASCII characters in quoted-printable + encoding. The return value is the converted line(s). If the optional argument + *quotetabs* is present and true, all tabs and spaces will be encoded. If the + optional argument *istext* is present and true, newlines are not encoded but + trailing whitespace will be encoded. If the optional argument *header* is + present and true, spaces will be encoded as underscores per :rfc:`1522`. If the + optional argument *header* is present and false, newline characters will be + encoded as well; otherwise linefeed conversion might corrupt the binary data + stream. + + +.. function:: a2b_hqx(string) + + Convert binhex4 formatted ASCII data to binary, without doing RLE-decompression. + The string should contain a complete number of binary bytes, or (in case of the + last portion of the binhex4 data) have the remaining bits zero. + + .. deprecated:: 3.9 + + +.. function:: rledecode_hqx(data) + + Perform RLE-decompression on the data, as per the binhex4 standard. The + algorithm uses ``0x90`` after a byte as a repeat indicator, followed by a count. + A count of ``0`` specifies a byte value of ``0x90``. The routine returns the + decompressed data, unless data input data ends in an orphaned repeat indicator, + in which case the :exc:`Incomplete` exception is raised. + + .. versionchanged:: 3.2 + Accept only bytestring or bytearray objects as input. + + .. deprecated:: 3.9 + + +.. function:: rlecode_hqx(data) + + Perform binhex4 style RLE-compression on *data* and return the result. + + .. deprecated:: 3.9 + + +.. function:: b2a_hqx(data) + + Perform hexbin4 binary-to-ASCII translation and return the resulting string. The + argument should already be RLE-coded, and have a length divisible by 3 (except + possibly the last fragment). + + .. deprecated:: 3.9 + + +.. function:: crc_hqx(data, value) + + Compute a 16-bit CRC value of *data*, starting with *value* as the + initial CRC, and return the result. This uses the CRC-CCITT polynomial + *x*:sup:`16` + *x*:sup:`12` + *x*:sup:`5` + 1, often represented as + 0x1021. This CRC is used in the binhex4 format. + + +.. function:: crc32(data[, value]) + + Compute CRC-32, the 32-bit checksum of *data*, starting with an + initial CRC of *value*. The default initial CRC is zero. The algorithm + is consistent with the ZIP file checksum. Since the algorithm is designed for + use as a checksum algorithm, it is not suitable for use as a general hash + algorithm. Use as follows:: + + print(binascii.crc32(b"hello world")) + # Or, in two pieces: + crc = binascii.crc32(b"hello") + crc = binascii.crc32(b" world", crc) + print('crc32 = {:#010x}'.format(crc)) + + .. versionchanged:: 3.0 + The result is always unsigned. + To generate the same numeric value across all Python versions and + platforms, use ``crc32(data) & 0xffffffff``. + + +.. function:: b2a_hex(data[, sep[, bytes_per_sep=1]]) + hexlify(data[, sep[, bytes_per_sep=1]]) + + Return the hexadecimal representation of the binary *data*. Every byte of + *data* is converted into the corresponding 2-digit hex representation. The + returned bytes object is therefore twice as long as the length of *data*. + + Similar functionality (but returning a text string) is also conveniently + accessible using the :meth:`bytes.hex` method. + + If *sep* is specified, it must be a single character str or bytes object. + It will be inserted in the output after every *bytes_per_sep* input bytes. + Separator placement is counted from the right end of the output by default, + if you wish to count from the left, supply a negative *bytes_per_sep* value. + + >>> import binascii + >>> binascii.b2a_hex(b'\xb9\x01\xef') + b'b901ef' + >>> binascii.hexlify(b'\xb9\x01\xef', '-') + b'b9-01-ef' + >>> binascii.b2a_hex(b'\xb9\x01\xef', b'_', 2) + b'b9_01ef' + >>> binascii.b2a_hex(b'\xb9\x01\xef', b' ', -2) + b'b901 ef' + + .. versionchanged:: 3.8 + The *sep* and *bytes_per_sep* parameters were added. + +.. function:: a2b_hex(hexstr) + unhexlify(hexstr) + + Return the binary data represented by the hexadecimal string *hexstr*. This + function is the inverse of :func:`b2a_hex`. *hexstr* must contain an even number + of hexadecimal digits (which can be upper or lower case), otherwise an + :exc:`Error` exception is raised. + + Similar functionality (accepting only text string arguments, but more + liberal towards whitespace) is also accessible using the + :meth:`bytes.fromhex` class method. + +.. exception:: Error + + Exception raised on errors. These are usually programming errors. + + +.. exception:: Incomplete + + Exception raised on incomplete data. These are usually not programming errors, + but may be handled by reading a little more data and trying again. + + +.. seealso:: + + Module :mod:`base64` + Support for RFC compliant base64-style encoding in base 16, 32, 64, + and 85. + + Module :mod:`binhex` + Support for the binhex format used on the Macintosh. + + Module :mod:`uu` + Support for UU encoding used on Unix. + + Module :mod:`quopri` + Support for quoted-printable encoding used in MIME email messages. diff --git a/cpython_2/environment/repo/Doc/library/binhex.rst b/cpython_2/environment/repo/Doc/library/binhex.rst new file mode 100644 index 0000000000000000000000000000000000000000..7de6a663762f0c019422a67bc66a2b29f7ae891b --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/binhex.rst @@ -0,0 +1,59 @@ +:mod:`binhex` --- Encode and decode binhex4 files +================================================= + +.. module:: binhex + :synopsis: Encode and decode files in binhex4 format. + +**Source code:** :source:`Lib/binhex.py` + +.. deprecated:: 3.9 + +-------------- + +This module encodes and decodes files in binhex4 format, a format allowing +representation of Macintosh files in ASCII. Only the data fork is handled. + +The :mod:`binhex` module defines the following functions: + + +.. function:: binhex(input, output) + + Convert a binary file with filename *input* to binhex file *output*. The + *output* parameter can either be a filename or a file-like object (any object + supporting a :meth:`write` and :meth:`close` method). + + +.. function:: hexbin(input, output) + + Decode a binhex file *input*. *input* may be a filename or a file-like object + supporting :meth:`read` and :meth:`close` methods. The resulting file is written + to a file named *output*, unless the argument is ``None`` in which case the + output filename is read from the binhex file. + +The following exception is also defined: + + +.. exception:: Error + + Exception raised when something can't be encoded using the binhex format (for + example, a filename is too long to fit in the filename field), or when input is + not properly encoded binhex data. + + +.. seealso:: + + Module :mod:`binascii` + Support module containing ASCII-to-binary and binary-to-ASCII conversions. + + +.. _binhex-notes: + +Notes +----- + +There is an alternative, more powerful interface to the coder and decoder, see +the source for details. + +If you code or decode textfiles on non-Macintosh platforms they will still use +the old Macintosh newline convention (carriage-return as end of line). + diff --git a/cpython_2/environment/repo/Doc/library/bisect.rst b/cpython_2/environment/repo/Doc/library/bisect.rst new file mode 100644 index 0000000000000000000000000000000000000000..6bf7814b257f4abdbe48b48614635313fdbb07d7 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/bisect.rst @@ -0,0 +1,149 @@ +:mod:`bisect` --- Array bisection algorithm +=========================================== + +.. module:: bisect + :synopsis: Array bisection algorithms for binary searching. +.. sectionauthor:: Fred L. Drake, Jr. +.. sectionauthor:: Raymond Hettinger +.. example based on the PyModules FAQ entry by Aaron Watters + +**Source code:** :source:`Lib/bisect.py` + +-------------- + +This module provides support for maintaining a list in sorted order without +having to sort the list after each insertion. For long lists of items with +expensive comparison operations, this can be an improvement over the more common +approach. The module is called :mod:`bisect` because it uses a basic bisection +algorithm to do its work. The source code may be most useful as a working +example of the algorithm (the boundary conditions are already right!). + +The following functions are provided: + + +.. function:: bisect_left(a, x, lo=0, hi=len(a)) + + Locate the insertion point for *x* in *a* to maintain sorted order. + The parameters *lo* and *hi* may be used to specify a subset of the list + which should be considered; by default the entire list is used. If *x* is + already present in *a*, the insertion point will be before (to the left of) + any existing entries. The return value is suitable for use as the first + parameter to ``list.insert()`` assuming that *a* is already sorted. + + The returned insertion point *i* partitions the array *a* into two halves so + that ``all(val < x for val in a[lo:i])`` for the left side and + ``all(val >= x for val in a[i:hi])`` for the right side. + +.. function:: bisect_right(a, x, lo=0, hi=len(a)) + bisect(a, x, lo=0, hi=len(a)) + + Similar to :func:`bisect_left`, but returns an insertion point which comes + after (to the right of) any existing entries of *x* in *a*. + + The returned insertion point *i* partitions the array *a* into two halves so + that ``all(val <= x for val in a[lo:i])`` for the left side and + ``all(val > x for val in a[i:hi])`` for the right side. + +.. function:: insort_left(a, x, lo=0, hi=len(a)) + + Insert *x* in *a* in sorted order. This is equivalent to + ``a.insert(bisect.bisect_left(a, x, lo, hi), x)`` assuming that *a* is + already sorted. Keep in mind that the O(log n) search is dominated by + the slow O(n) insertion step. + +.. function:: insort_right(a, x, lo=0, hi=len(a)) + insort(a, x, lo=0, hi=len(a)) + + Similar to :func:`insort_left`, but inserting *x* in *a* after any existing + entries of *x*. + +.. seealso:: + + `SortedCollection recipe + `_ that uses + bisect to build a full-featured collection class with straight-forward search + methods and support for a key-function. The keys are precomputed to save + unnecessary calls to the key function during searches. + + +Searching Sorted Lists +---------------------- + +The above :func:`bisect` functions are useful for finding insertion points but +can be tricky or awkward to use for common searching tasks. The following five +functions show how to transform them into the standard lookups for sorted +lists:: + + def index(a, x): + 'Locate the leftmost value exactly equal to x' + i = bisect_left(a, x) + if i != len(a) and a[i] == x: + return i + raise ValueError + + def find_lt(a, x): + 'Find rightmost value less than x' + i = bisect_left(a, x) + if i: + return a[i-1] + raise ValueError + + def find_le(a, x): + 'Find rightmost value less than or equal to x' + i = bisect_right(a, x) + if i: + return a[i-1] + raise ValueError + + def find_gt(a, x): + 'Find leftmost value greater than x' + i = bisect_right(a, x) + if i != len(a): + return a[i] + raise ValueError + + def find_ge(a, x): + 'Find leftmost item greater than or equal to x' + i = bisect_left(a, x) + if i != len(a): + return a[i] + raise ValueError + + +Other Examples +-------------- + +.. _bisect-example: + +The :func:`bisect` function can be useful for numeric table lookups. This +example uses :func:`bisect` to look up a letter grade for an exam score (say) +based on a set of ordered numeric breakpoints: 90 and up is an 'A', 80 to 89 is +a 'B', and so on:: + + >>> def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'): + ... i = bisect(breakpoints, score) + ... return grades[i] + ... + >>> [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]] + ['F', 'A', 'C', 'C', 'B', 'A', 'A'] + +Unlike the :func:`sorted` function, it does not make sense for the :func:`bisect` +functions to have *key* or *reversed* arguments because that would lead to an +inefficient design (successive calls to bisect functions would not "remember" +all of the previous key lookups). + +Instead, it is better to search a list of precomputed keys to find the index +of the record in question:: + + >>> data = [('red', 5), ('blue', 1), ('yellow', 8), ('black', 0)] + >>> data.sort(key=lambda r: r[1]) + >>> keys = [r[1] for r in data] # precomputed list of keys + >>> data[bisect_left(keys, 0)] + ('black', 0) + >>> data[bisect_left(keys, 1)] + ('blue', 1) + >>> data[bisect_left(keys, 5)] + ('red', 5) + >>> data[bisect_left(keys, 8)] + ('yellow', 8) + diff --git a/cpython_2/environment/repo/Doc/library/builtins.rst b/cpython_2/environment/repo/Doc/library/builtins.rst new file mode 100644 index 0000000000000000000000000000000000000000..8fb1fef6da2954a37ed5794774602575c648c8ef --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/builtins.rst @@ -0,0 +1,42 @@ +:mod:`builtins` --- Built-in objects +==================================== + +.. module:: builtins + :synopsis: The module that provides the built-in namespace. + +-------------- + +This module provides direct access to all 'built-in' identifiers of Python; for +example, ``builtins.open`` is the full name for the built-in function +:func:`open`. See :ref:`built-in-funcs` and :ref:`built-in-consts` for +documentation. + + +This module is not normally accessed explicitly by most applications, but can be +useful in modules that provide objects with the same name as a built-in value, +but in which the built-in of that name is also needed. For example, in a module +that wants to implement an :func:`open` function that wraps the built-in +:func:`open`, this module can be used directly:: + + import builtins + + def open(path): + f = builtins.open(path, 'r') + return UpperCaser(f) + + class UpperCaser: + '''Wrapper around a file that converts output to upper-case.''' + + def __init__(self, f): + self._f = f + + def read(self, count=-1): + return self._f.read(count).upper() + + # ... + +As an implementation detail, most modules have the name ``__builtins__`` made +available as part of their globals. The value of ``__builtins__`` is normally +either this module or the value of this module's :attr:`~object.__dict__` attribute. +Since this is an implementation detail, it may not be used by alternate +implementations of Python. diff --git a/cpython_2/environment/repo/Doc/library/bz2.rst b/cpython_2/environment/repo/Doc/library/bz2.rst new file mode 100644 index 0000000000000000000000000000000000000000..85cdc16a7d78d4ac84bca9a4246b78a6ade130cc --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/bz2.rst @@ -0,0 +1,332 @@ +:mod:`bz2` --- Support for :program:`bzip2` compression +======================================================= + +.. module:: bz2 + :synopsis: Interfaces for bzip2 compression and decompression. + +.. moduleauthor:: Gustavo Niemeyer +.. moduleauthor:: Nadeem Vawda +.. sectionauthor:: Gustavo Niemeyer +.. sectionauthor:: Nadeem Vawda + +**Source code:** :source:`Lib/bz2.py` + +-------------- + +This module provides a comprehensive interface for compressing and +decompressing data using the bzip2 compression algorithm. + +The :mod:`bz2` module contains: + +* The :func:`.open` function and :class:`BZ2File` class for reading and + writing compressed files. +* The :class:`BZ2Compressor` and :class:`BZ2Decompressor` classes for + incremental (de)compression. +* The :func:`compress` and :func:`decompress` functions for one-shot + (de)compression. + +All of the classes in this module may safely be accessed from multiple threads. + + +(De)compression of files +------------------------ + +.. function:: open(filename, mode='rb', compresslevel=9, encoding=None, errors=None, newline=None) + + Open a bzip2-compressed file in binary or text mode, returning a :term:`file + object`. + + As with the constructor for :class:`BZ2File`, the *filename* argument can be + an actual filename (a :class:`str` or :class:`bytes` object), or an existing + file object to read from or write to. + + The *mode* argument can be any of ``'r'``, ``'rb'``, ``'w'``, ``'wb'``, + ``'x'``, ``'xb'``, ``'a'`` or ``'ab'`` for binary mode, or ``'rt'``, + ``'wt'``, ``'xt'``, or ``'at'`` for text mode. The default is ``'rb'``. + + The *compresslevel* argument is an integer from 1 to 9, as for the + :class:`BZ2File` constructor. + + For binary mode, this function is equivalent to the :class:`BZ2File` + constructor: ``BZ2File(filename, mode, compresslevel=compresslevel)``. In + this case, the *encoding*, *errors* and *newline* arguments must not be + provided. + + For text mode, a :class:`BZ2File` object is created, and wrapped in an + :class:`io.TextIOWrapper` instance with the specified encoding, error + handling behavior, and line ending(s). + + .. versionadded:: 3.3 + + .. versionchanged:: 3.4 + The ``'x'`` (exclusive creation) mode was added. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. class:: BZ2File(filename, mode='r', *, compresslevel=9) + + Open a bzip2-compressed file in binary mode. + + If *filename* is a :class:`str` or :class:`bytes` object, open the named file + directly. Otherwise, *filename* should be a :term:`file object`, which will + be used to read or write the compressed data. + + The *mode* argument can be either ``'r'`` for reading (default), ``'w'`` for + overwriting, ``'x'`` for exclusive creation, or ``'a'`` for appending. These + can equivalently be given as ``'rb'``, ``'wb'``, ``'xb'`` and ``'ab'`` + respectively. + + If *filename* is a file object (rather than an actual file name), a mode of + ``'w'`` does not truncate the file, and is instead equivalent to ``'a'``. + + If *mode* is ``'w'`` or ``'a'``, *compresslevel* can be an integer between + ``1`` and ``9`` specifying the level of compression: ``1`` produces the + least compression, and ``9`` (default) produces the most compression. + + If *mode* is ``'r'``, the input file may be the concatenation of multiple + compressed streams. + + :class:`BZ2File` provides all of the members specified by the + :class:`io.BufferedIOBase`, except for :meth:`detach` and :meth:`truncate`. + Iteration and the :keyword:`with` statement are supported. + + :class:`BZ2File` also provides the following method: + + .. method:: peek([n]) + + Return buffered data without advancing the file position. At least one + byte of data will be returned (unless at EOF). The exact number of bytes + returned is unspecified. + + .. note:: While calling :meth:`peek` does not change the file position of + the :class:`BZ2File`, it may change the position of the underlying file + object (e.g. if the :class:`BZ2File` was constructed by passing a file + object for *filename*). + + .. versionadded:: 3.3 + + + .. versionchanged:: 3.1 + Support for the :keyword:`with` statement was added. + + .. versionchanged:: 3.3 + The :meth:`fileno`, :meth:`readable`, :meth:`seekable`, :meth:`writable`, + :meth:`read1` and :meth:`readinto` methods were added. + + .. versionchanged:: 3.3 + Support was added for *filename* being a :term:`file object` instead of an + actual filename. + + .. versionchanged:: 3.3 + The ``'a'`` (append) mode was added, along with support for reading + multi-stream files. + + .. versionchanged:: 3.4 + The ``'x'`` (exclusive creation) mode was added. + + .. versionchanged:: 3.5 + The :meth:`~io.BufferedIOBase.read` method now accepts an argument of + ``None``. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + .. versionchanged:: 3.9 + The *buffering* parameter has been removed. It was ignored and deprecated + since Python 3.0. Pass an open file object to control how the file is + opened. + + The *compresslevel* parameter became keyword-only. + + +Incremental (de)compression +--------------------------- + +.. class:: BZ2Compressor(compresslevel=9) + + Create a new compressor object. This object may be used to compress data + incrementally. For one-shot compression, use the :func:`compress` function + instead. + + *compresslevel*, if given, must be an integer between ``1`` and ``9``. The + default is ``9``. + + .. method:: compress(data) + + Provide data to the compressor object. Returns a chunk of compressed data + if possible, or an empty byte string otherwise. + + When you have finished providing data to the compressor, call the + :meth:`flush` method to finish the compression process. + + + .. method:: flush() + + Finish the compression process. Returns the compressed data left in + internal buffers. + + The compressor object may not be used after this method has been called. + + +.. class:: BZ2Decompressor() + + Create a new decompressor object. This object may be used to decompress data + incrementally. For one-shot compression, use the :func:`decompress` function + instead. + + .. note:: + This class does not transparently handle inputs containing multiple + compressed streams, unlike :func:`decompress` and :class:`BZ2File`. If + you need to decompress a multi-stream input with :class:`BZ2Decompressor`, + you must use a new decompressor for each stream. + + .. method:: decompress(data, max_length=-1) + + Decompress *data* (a :term:`bytes-like object`), returning + uncompressed data as bytes. Some of *data* may be buffered + internally, for use in later calls to :meth:`decompress`. The + returned data should be concatenated with the output of any + previous calls to :meth:`decompress`. + + If *max_length* is nonnegative, returns at most *max_length* + bytes of decompressed data. If this limit is reached and further + output can be produced, the :attr:`~.needs_input` attribute will + be set to ``False``. In this case, the next call to + :meth:`~.decompress` may provide *data* as ``b''`` to obtain + more of the output. + + If all of the input data was decompressed and returned (either + because this was less than *max_length* bytes, or because + *max_length* was negative), the :attr:`~.needs_input` attribute + will be set to ``True``. + + Attempting to decompress data after the end of stream is reached + raises an `EOFError`. Any data found after the end of the + stream is ignored and saved in the :attr:`~.unused_data` attribute. + + .. versionchanged:: 3.5 + Added the *max_length* parameter. + + .. attribute:: eof + + ``True`` if the end-of-stream marker has been reached. + + .. versionadded:: 3.3 + + + .. attribute:: unused_data + + Data found after the end of the compressed stream. + + If this attribute is accessed before the end of the stream has been + reached, its value will be ``b''``. + + .. attribute:: needs_input + + ``False`` if the :meth:`.decompress` method can provide more + decompressed data before requiring new uncompressed input. + + .. versionadded:: 3.5 + + +One-shot (de)compression +------------------------ + +.. function:: compress(data, compresslevel=9) + + Compress *data*, a :term:`bytes-like object `. + + *compresslevel*, if given, must be an integer between ``1`` and ``9``. The + default is ``9``. + + For incremental compression, use a :class:`BZ2Compressor` instead. + + +.. function:: decompress(data) + + Decompress *data*, a :term:`bytes-like object `. + + If *data* is the concatenation of multiple compressed streams, decompress + all of the streams. + + For incremental decompression, use a :class:`BZ2Decompressor` instead. + + .. versionchanged:: 3.3 + Support for multi-stream inputs was added. + +.. _bz2-usage-examples: + +Examples of usage +----------------- + +Below are some examples of typical usage of the :mod:`bz2` module. + +Using :func:`compress` and :func:`decompress` to demonstrate round-trip compression: + + >>> import bz2 + + >>> data = b"""\ + ... Donec rhoncus quis sapien sit amet molestie. Fusce scelerisque vel augue + ... nec ullamcorper. Nam rutrum pretium placerat. Aliquam vel tristique lorem, + ... sit amet cursus ante. In interdum laoreet mi, sit amet ultrices purus + ... pulvinar a. Nam gravida euismod magna, non varius justo tincidunt feugiat. + ... Aliquam pharetra lacus non risus vehicula rutrum. Maecenas aliquam leo + ... felis. Pellentesque semper nunc sit amet nibh ullamcorper, ac elementum + ... dolor luctus. Curabitur lacinia mi ornare consectetur vestibulum.""" + + >>> c = bz2.compress(data) + >>> len(data) / len(c) # Data compression ratio + 1.513595166163142 + + >>> d = bz2.decompress(c) + >>> data == d # Check equality to original object after round-trip + True + +Using :class:`BZ2Compressor` for incremental compression: + + >>> import bz2 + + >>> def gen_data(chunks=10, chunksize=1000): + ... """Yield incremental blocks of chunksize bytes.""" + ... for _ in range(chunks): + ... yield b"z" * chunksize + ... + >>> comp = bz2.BZ2Compressor() + >>> out = b"" + >>> for chunk in gen_data(): + ... # Provide data to the compressor object + ... out = out + comp.compress(chunk) + ... + >>> # Finish the compression process. Call this once you have + >>> # finished providing data to the compressor. + >>> out = out + comp.flush() + +The example above uses a very "nonrandom" stream of data +(a stream of `b"z"` chunks). Random data tends to compress poorly, +while ordered, repetitive data usually yields a high compression ratio. + +Writing and reading a bzip2-compressed file in binary mode: + + >>> import bz2 + + >>> data = b"""\ + ... Donec rhoncus quis sapien sit amet molestie. Fusce scelerisque vel augue + ... nec ullamcorper. Nam rutrum pretium placerat. Aliquam vel tristique lorem, + ... sit amet cursus ante. In interdum laoreet mi, sit amet ultrices purus + ... pulvinar a. Nam gravida euismod magna, non varius justo tincidunt feugiat. + ... Aliquam pharetra lacus non risus vehicula rutrum. Maecenas aliquam leo + ... felis. Pellentesque semper nunc sit amet nibh ullamcorper, ac elementum + ... dolor luctus. Curabitur lacinia mi ornare consectetur vestibulum.""" + + >>> with bz2.open("myfile.bz2", "wb") as f: + ... # Write compressed data to file + ... unused = f.write(data) + + >>> with bz2.open("myfile.bz2", "rb") as f: + ... # Decompress data from file + ... content = f.read() + + >>> content == data # Check equality to original object after round-trip + True diff --git a/cpython_2/environment/repo/Doc/library/calendar.rst b/cpython_2/environment/repo/Doc/library/calendar.rst new file mode 100644 index 0000000000000000000000000000000000000000..56b75ef0f850a6726d335880bb3f776bdc1fc4f4 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/calendar.rst @@ -0,0 +1,420 @@ +:mod:`calendar` --- General calendar-related functions +====================================================== + +.. module:: calendar + :synopsis: Functions for working with calendars, including some emulation + of the Unix cal program. + +.. sectionauthor:: Drew Csillag + +**Source code:** :source:`Lib/calendar.py` + +-------------- + +This module allows you to output calendars like the Unix :program:`cal` program, +and provides additional useful functions related to the calendar. By default, +these calendars have Monday as the first day of the week, and Sunday as the last +(the European convention). Use :func:`setfirstweekday` to set the first day of +the week to Sunday (6) or to any other weekday. Parameters that specify dates +are given as integers. For related +functionality, see also the :mod:`datetime` and :mod:`time` modules. + +The functions and classes defined in this module +use an idealized calendar, the current Gregorian calendar extended indefinitely +in both directions. This matches the definition of the "proleptic Gregorian" +calendar in Dershowitz and Reingold's book "Calendrical Calculations", where +it's the base calendar for all computations. Zero and negative years are +interpreted as prescribed by the ISO 8601 standard. Year 0 is 1 BC, year -1 is +2 BC, and so on. + + +.. class:: Calendar(firstweekday=0) + + Creates a :class:`Calendar` object. *firstweekday* is an integer specifying the + first day of the week. ``0`` is Monday (the default), ``6`` is Sunday. + + A :class:`Calendar` object provides several methods that can be used for + preparing the calendar data for formatting. This class doesn't do any formatting + itself. This is the job of subclasses. + + + :class:`Calendar` instances have the following methods: + + .. method:: iterweekdays() + + Return an iterator for the week day numbers that will be used for one + week. The first value from the iterator will be the same as the value of + the :attr:`firstweekday` property. + + + .. method:: itermonthdates(year, month) + + Return an iterator for the month *month* (1--12) in the year *year*. This + iterator will return all days (as :class:`datetime.date` objects) for the + month and all days before the start of the month or after the end of the + month that are required to get a complete week. + + + .. method:: itermonthdays(year, month) + + Return an iterator for the month *month* in the year *year* similar to + :meth:`itermonthdates`, but not restricted by the :class:`datetime.date` + range. Days returned will simply be day of the month numbers. For the + days outside of the specified month, the day number is ``0``. + + + .. method:: itermonthdays2(year, month) + + Return an iterator for the month *month* in the year *year* similar to + :meth:`itermonthdates`, but not restricted by the :class:`datetime.date` + range. Days returned will be tuples consisting of a day of the month + number and a week day number. + + + .. method:: itermonthdays3(year, month) + + Return an iterator for the month *month* in the year *year* similar to + :meth:`itermonthdates`, but not restricted by the :class:`datetime.date` + range. Days returned will be tuples consisting of a year, a month and a day + of the month numbers. + + .. versionadded:: 3.7 + + + .. method:: itermonthdays4(year, month) + + Return an iterator for the month *month* in the year *year* similar to + :meth:`itermonthdates`, but not restricted by the :class:`datetime.date` + range. Days returned will be tuples consisting of a year, a month, a day + of the month, and a day of the week numbers. + + .. versionadded:: 3.7 + + + .. method:: monthdatescalendar(year, month) + + Return a list of the weeks in the month *month* of the *year* as full + weeks. Weeks are lists of seven :class:`datetime.date` objects. + + + .. method:: monthdays2calendar(year, month) + + Return a list of the weeks in the month *month* of the *year* as full + weeks. Weeks are lists of seven tuples of day numbers and weekday + numbers. + + + .. method:: monthdayscalendar(year, month) + + Return a list of the weeks in the month *month* of the *year* as full + weeks. Weeks are lists of seven day numbers. + + + .. method:: yeardatescalendar(year, width=3) + + Return the data for the specified year ready for formatting. The return + value is a list of month rows. Each month row contains up to *width* + months (defaulting to 3). Each month contains between 4 and 6 weeks and + each week contains 1--7 days. Days are :class:`datetime.date` objects. + + + .. method:: yeardays2calendar(year, width=3) + + Return the data for the specified year ready for formatting (similar to + :meth:`yeardatescalendar`). Entries in the week lists are tuples of day + numbers and weekday numbers. Day numbers outside this month are zero. + + + .. method:: yeardayscalendar(year, width=3) + + Return the data for the specified year ready for formatting (similar to + :meth:`yeardatescalendar`). Entries in the week lists are day numbers. Day + numbers outside this month are zero. + + +.. class:: TextCalendar(firstweekday=0) + + This class can be used to generate plain text calendars. + + :class:`TextCalendar` instances have the following methods: + + .. method:: formatmonth(theyear, themonth, w=0, l=0) + + Return a month's calendar in a multi-line string. If *w* is provided, it + specifies the width of the date columns, which are centered. If *l* is + given, it specifies the number of lines that each week will use. Depends + on the first weekday as specified in the constructor or set by the + :meth:`setfirstweekday` method. + + + .. method:: prmonth(theyear, themonth, w=0, l=0) + + Print a month's calendar as returned by :meth:`formatmonth`. + + + .. method:: formatyear(theyear, w=2, l=1, c=6, m=3) + + Return a *m*-column calendar for an entire year as a multi-line string. + Optional parameters *w*, *l*, and *c* are for date column width, lines per + week, and number of spaces between month columns, respectively. Depends on + the first weekday as specified in the constructor or set by the + :meth:`setfirstweekday` method. The earliest year for which a calendar + can be generated is platform-dependent. + + + .. method:: pryear(theyear, w=2, l=1, c=6, m=3) + + Print the calendar for an entire year as returned by :meth:`formatyear`. + + +.. class:: HTMLCalendar(firstweekday=0) + + This class can be used to generate HTML calendars. + + + :class:`!HTMLCalendar` instances have the following methods: + + .. method:: formatmonth(theyear, themonth, withyear=True) + + Return a month's calendar as an HTML table. If *withyear* is true the year + will be included in the header, otherwise just the month name will be + used. + + + .. method:: formatyear(theyear, width=3) + + Return a year's calendar as an HTML table. *width* (defaulting to 3) + specifies the number of months per row. + + + .. method:: formatyearpage(theyear, width=3, css='calendar.css', encoding=None) + + Return a year's calendar as a complete HTML page. *width* (defaulting to + 3) specifies the number of months per row. *css* is the name for the + cascading style sheet to be used. :const:`None` can be passed if no style + sheet should be used. *encoding* specifies the encoding to be used for the + output (defaulting to the system default encoding). + + + :class:`!HTMLCalendar` has the following attributes you can override to + customize the CSS classes used by the calendar: + + .. attribute:: cssclasses + + A list of CSS classes used for each weekday. The default class list is:: + + cssclasses = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] + + more styles can be added for each day:: + + cssclasses = ["mon text-bold", "tue", "wed", "thu", "fri", "sat", "sun red"] + + Note that the length of this list must be seven items. + + + .. attribute:: cssclass_noday + + The CSS class for a weekday occurring in the previous or coming month. + + .. versionadded:: 3.7 + + + .. attribute:: cssclasses_weekday_head + + A list of CSS classes used for weekday names in the header row. + The default is the same as :attr:`cssclasses`. + + .. versionadded:: 3.7 + + + .. attribute:: cssclass_month_head + + The month's head CSS class (used by :meth:`formatmonthname`). + The default value is ``"month"``. + + .. versionadded:: 3.7 + + + .. attribute:: cssclass_month + + The CSS class for the whole month's table (used by :meth:`formatmonth`). + The default value is ``"month"``. + + .. versionadded:: 3.7 + + + .. attribute:: cssclass_year + + The CSS class for the whole year's table of tables (used by + :meth:`formatyear`). The default value is ``"year"``. + + .. versionadded:: 3.7 + + + .. attribute:: cssclass_year_head + + The CSS class for the table head for the whole year (used by + :meth:`formatyear`). The default value is ``"year"``. + + .. versionadded:: 3.7 + + + Note that although the naming for the above described class attributes is + singular (e.g. ``cssclass_month`` ``cssclass_noday``), one can replace the + single CSS class with a space separated list of CSS classes, for example:: + + "text-bold text-red" + + Here is an example how :class:`!HTMLCalendar` can be customized:: + + class CustomHTMLCal(calendar.HTMLCalendar): + cssclasses = [style + " text-nowrap" for style in + calendar.HTMLCalendar.cssclasses] + cssclass_month_head = "text-center month-head" + cssclass_month = "text-center month" + cssclass_year = "text-italic lead" + + +.. class:: LocaleTextCalendar(firstweekday=0, locale=None) + + This subclass of :class:`TextCalendar` can be passed a locale name in the + constructor and will return month and weekday names in the specified locale. + If this locale includes an encoding all strings containing month and weekday + names will be returned as unicode. + + +.. class:: LocaleHTMLCalendar(firstweekday=0, locale=None) + + This subclass of :class:`HTMLCalendar` can be passed a locale name in the + constructor and will return month and weekday names in the specified + locale. If this locale includes an encoding all strings containing month and + weekday names will be returned as unicode. + +.. note:: + + The :meth:`formatweekday` and :meth:`formatmonthname` methods of these two + classes temporarily change the current locale to the given *locale*. Because + the current locale is a process-wide setting, they are not thread-safe. + + +For simple text calendars this module provides the following functions. + +.. function:: setfirstweekday(weekday) + + Sets the weekday (``0`` is Monday, ``6`` is Sunday) to start each week. The + values :const:`MONDAY`, :const:`TUESDAY`, :const:`WEDNESDAY`, :const:`THURSDAY`, + :const:`FRIDAY`, :const:`SATURDAY`, and :const:`SUNDAY` are provided for + convenience. For example, to set the first weekday to Sunday:: + + import calendar + calendar.setfirstweekday(calendar.SUNDAY) + + +.. function:: firstweekday() + + Returns the current setting for the weekday to start each week. + + +.. function:: isleap(year) + + Returns :const:`True` if *year* is a leap year, otherwise :const:`False`. + + +.. function:: leapdays(y1, y2) + + Returns the number of leap years in the range from *y1* to *y2* (exclusive), + where *y1* and *y2* are years. + + This function works for ranges spanning a century change. + + +.. function:: weekday(year, month, day) + + Returns the day of the week (``0`` is Monday) for *year* (``1970``--...), + *month* (``1``--``12``), *day* (``1``--``31``). + + +.. function:: weekheader(n) + + Return a header containing abbreviated weekday names. *n* specifies the width in + characters for one weekday. + + +.. function:: monthrange(year, month) + + Returns weekday of first day of the month and number of days in month, for the + specified *year* and *month*. + + +.. function:: monthcalendar(year, month) + + Returns a matrix representing a month's calendar. Each row represents a week; + days outside of the month a represented by zeros. Each week begins with Monday + unless set by :func:`setfirstweekday`. + + +.. function:: prmonth(theyear, themonth, w=0, l=0) + + Prints a month's calendar as returned by :func:`month`. + + +.. function:: month(theyear, themonth, w=0, l=0) + + Returns a month's calendar in a multi-line string using the :meth:`formatmonth` + of the :class:`TextCalendar` class. + + +.. function:: prcal(year, w=0, l=0, c=6, m=3) + + Prints the calendar for an entire year as returned by :func:`calendar`. + + +.. function:: calendar(year, w=2, l=1, c=6, m=3) + + Returns a 3-column calendar for an entire year as a multi-line string using + the :meth:`formatyear` of the :class:`TextCalendar` class. + + +.. function:: timegm(tuple) + + An unrelated but handy function that takes a time tuple such as returned by + the :func:`~time.gmtime` function in the :mod:`time` module, and returns the + corresponding Unix timestamp value, assuming an epoch of 1970, and the POSIX + encoding. In fact, :func:`time.gmtime` and :func:`timegm` are each others' + inverse. + + +The :mod:`calendar` module exports the following data attributes: + +.. data:: day_name + + An array that represents the days of the week in the current locale. + + +.. data:: day_abbr + + An array that represents the abbreviated days of the week in the current locale. + + +.. data:: month_name + + An array that represents the months of the year in the current locale. This + follows normal convention of January being month number 1, so it has a length of + 13 and ``month_name[0]`` is the empty string. + + +.. data:: month_abbr + + An array that represents the abbreviated months of the year in the current + locale. This follows normal convention of January being month number 1, so it + has a length of 13 and ``month_abbr[0]`` is the empty string. + + +.. seealso:: + + Module :mod:`datetime` + Object-oriented interface to dates and times with similar functionality to the + :mod:`time` module. + + Module :mod:`time` + Low-level time related functions. diff --git a/cpython_2/environment/repo/Doc/library/cgi.rst b/cpython_2/environment/repo/Doc/library/cgi.rst new file mode 100644 index 0000000000000000000000000000000000000000..4048592e7361f705b2bcf93e8bafc1284eb5bd99 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/cgi.rst @@ -0,0 +1,519 @@ +:mod:`cgi` --- Common Gateway Interface support +=============================================== + +.. module:: cgi + :synopsis: Helpers for running Python scripts via the Common Gateway Interface. + +**Source code:** :source:`Lib/cgi.py` + +.. index:: + pair: WWW; server + pair: CGI; protocol + pair: HTTP; protocol + pair: MIME; headers + single: URL + single: Common Gateway Interface + +-------------- + +Support module for Common Gateway Interface (CGI) scripts. + +This module defines a number of utilities for use by CGI scripts written in +Python. + + +Introduction +------------ + +.. _cgi-intro: + +A CGI script is invoked by an HTTP server, usually to process user input +submitted through an HTML ``
    `` or ```` element. + +Most often, CGI scripts live in the server's special :file:`cgi-bin` directory. +The HTTP server places all sorts of information about the request (such as the +client's hostname, the requested URL, the query string, and lots of other +goodies) in the script's shell environment, executes the script, and sends the +script's output back to the client. + +The script's input is connected to the client too, and sometimes the form data +is read this way; at other times the form data is passed via the "query string" +part of the URL. This module is intended to take care of the different cases +and provide a simpler interface to the Python script. It also provides a number +of utilities that help in debugging scripts, and the latest addition is support +for file uploads from a form (if your browser supports it). + +The output of a CGI script should consist of two sections, separated by a blank +line. The first section contains a number of headers, telling the client what +kind of data is following. Python code to generate a minimal header section +looks like this:: + + print("Content-Type: text/html") # HTML is following + print() # blank line, end of headers + +The second section is usually HTML, which allows the client software to display +nicely formatted text with header, in-line images, etc. Here's Python code that +prints a simple piece of HTML:: + + print("CGI script output") + print("

    This is my first CGI script

    ") + print("Hello, world!") + + +.. _using-the-cgi-module: + +Using the cgi module +-------------------- + +Begin by writing ``import cgi``. + +When you write a new script, consider adding these lines:: + + import cgitb + cgitb.enable() + +This activates a special exception handler that will display detailed reports in +the Web browser if any errors occur. If you'd rather not show the guts of your +program to users of your script, you can have the reports saved to files +instead, with code like this:: + + import cgitb + cgitb.enable(display=0, logdir="/path/to/logdir") + +It's very helpful to use this feature during script development. The reports +produced by :mod:`cgitb` provide information that can save you a lot of time in +tracking down bugs. You can always remove the ``cgitb`` line later when you +have tested your script and are confident that it works correctly. + +To get at submitted form data, use the :class:`FieldStorage` class. If the form +contains non-ASCII characters, use the *encoding* keyword parameter set to the +value of the encoding defined for the document. It is usually contained in the +META tag in the HEAD section of the HTML document or by the +:mailheader:`Content-Type` header). This reads the form contents from the +standard input or the environment (depending on the value of various +environment variables set according to the CGI standard). Since it may consume +standard input, it should be instantiated only once. + +The :class:`FieldStorage` instance can be indexed like a Python dictionary. +It allows membership testing with the :keyword:`in` operator, and also supports +the standard dictionary method :meth:`~dict.keys` and the built-in function +:func:`len`. Form fields containing empty strings are ignored and do not appear +in the dictionary; to keep such values, provide a true value for the optional +*keep_blank_values* keyword parameter when creating the :class:`FieldStorage` +instance. + +For instance, the following code (which assumes that the +:mailheader:`Content-Type` header and blank line have already been printed) +checks that the fields ``name`` and ``addr`` are both set to a non-empty +string:: + + form = cgi.FieldStorage() + if "name" not in form or "addr" not in form: + print("

    Error

    ") + print("Please fill in the name and addr fields.") + return + print("

    name:", form["name"].value) + print("

    addr:", form["addr"].value) + ...further form processing here... + +Here the fields, accessed through ``form[key]``, are themselves instances of +:class:`FieldStorage` (or :class:`MiniFieldStorage`, depending on the form +encoding). The :attr:`~FieldStorage.value` attribute of the instance yields +the string value of the field. The :meth:`~FieldStorage.getvalue` method +returns this string value directly; it also accepts an optional second argument +as a default to return if the requested key is not present. + +If the submitted form data contains more than one field with the same name, the +object retrieved by ``form[key]`` is not a :class:`FieldStorage` or +:class:`MiniFieldStorage` instance but a list of such instances. Similarly, in +this situation, ``form.getvalue(key)`` would return a list of strings. If you +expect this possibility (when your HTML form contains multiple fields with the +same name), use the :meth:`~FieldStorage.getlist` method, which always returns +a list of values (so that you do not need to special-case the single item +case). For example, this code concatenates any number of username fields, +separated by commas:: + + value = form.getlist("username") + usernames = ",".join(value) + +If a field represents an uploaded file, accessing the value via the +:attr:`~FieldStorage.value` attribute or the :meth:`~FieldStorage.getvalue` +method reads the entire file in memory as bytes. This may not be what you +want. You can test for an uploaded file by testing either the +:attr:`~FieldStorage.filename` attribute or the :attr:`~FieldStorage.file` +attribute. You can then read the data from the :attr:`!file` +attribute before it is automatically closed as part of the garbage collection of +the :class:`FieldStorage` instance +(the :func:`~io.RawIOBase.read` and :func:`~io.IOBase.readline` methods will +return bytes):: + + fileitem = form["userfile"] + if fileitem.file: + # It's an uploaded file; count lines + linecount = 0 + while True: + line = fileitem.file.readline() + if not line: break + linecount = linecount + 1 + +:class:`FieldStorage` objects also support being used in a :keyword:`with` +statement, which will automatically close them when done. + +If an error is encountered when obtaining the contents of an uploaded file +(for example, when the user interrupts the form submission by clicking on +a Back or Cancel button) the :attr:`~FieldStorage.done` attribute of the +object for the field will be set to the value -1. + +The file upload draft standard entertains the possibility of uploading multiple +files from one field (using a recursive :mimetype:`multipart/\*` encoding). +When this occurs, the item will be a dictionary-like :class:`FieldStorage` item. +This can be determined by testing its :attr:`!type` attribute, which should be +:mimetype:`multipart/form-data` (or perhaps another MIME type matching +:mimetype:`multipart/\*`). In this case, it can be iterated over recursively +just like the top-level form object. + +When a form is submitted in the "old" format (as the query string or as a single +data part of type :mimetype:`application/x-www-form-urlencoded`), the items will +actually be instances of the class :class:`MiniFieldStorage`. In this case, the +:attr:`!list`, :attr:`!file`, and :attr:`filename` attributes are always ``None``. + +A form submitted via POST that also has a query string will contain both +:class:`FieldStorage` and :class:`MiniFieldStorage` items. + +.. versionchanged:: 3.4 + The :attr:`~FieldStorage.file` attribute is automatically closed upon the + garbage collection of the creating :class:`FieldStorage` instance. + +.. versionchanged:: 3.5 + Added support for the context management protocol to the + :class:`FieldStorage` class. + + +Higher Level Interface +---------------------- + +The previous section explains how to read CGI form data using the +:class:`FieldStorage` class. This section describes a higher level interface +which was added to this class to allow one to do it in a more readable and +intuitive way. The interface doesn't make the techniques described in previous +sections obsolete --- they are still useful to process file uploads efficiently, +for example. + +.. XXX: Is this true ? + +The interface consists of two simple methods. Using the methods you can process +form data in a generic way, without the need to worry whether only one or more +values were posted under one name. + +In the previous section, you learned to write following code anytime you +expected a user to post more than one value under one name:: + + item = form.getvalue("item") + if isinstance(item, list): + # The user is requesting more than one item. + else: + # The user is requesting only one item. + +This situation is common for example when a form contains a group of multiple +checkboxes with the same name:: + + + + +In most situations, however, there's only one form control with a particular +name in a form and then you expect and need only one value associated with this +name. So you write a script containing for example this code:: + + user = form.getvalue("user").upper() + +The problem with the code is that you should never expect that a client will +provide valid input to your scripts. For example, if a curious user appends +another ``user=foo`` pair to the query string, then the script would crash, +because in this situation the ``getvalue("user")`` method call returns a list +instead of a string. Calling the :meth:`~str.upper` method on a list is not valid +(since lists do not have a method of this name) and results in an +:exc:`AttributeError` exception. + +Therefore, the appropriate way to read form data values was to always use the +code which checks whether the obtained value is a single value or a list of +values. That's annoying and leads to less readable scripts. + +A more convenient approach is to use the methods :meth:`~FieldStorage.getfirst` +and :meth:`~FieldStorage.getlist` provided by this higher level interface. + + +.. method:: FieldStorage.getfirst(name, default=None) + + This method always returns only one value associated with form field *name*. + The method returns only the first value in case that more values were posted + under such name. Please note that the order in which the values are received + may vary from browser to browser and should not be counted on. [#]_ If no such + form field or value exists then the method returns the value specified by the + optional parameter *default*. This parameter defaults to ``None`` if not + specified. + + +.. method:: FieldStorage.getlist(name) + + This method always returns a list of values associated with form field *name*. + The method returns an empty list if no such form field or value exists for + *name*. It returns a list consisting of one item if only one such value exists. + +Using these methods you can write nice compact code:: + + import cgi + form = cgi.FieldStorage() + user = form.getfirst("user", "").upper() # This way it's safe. + for item in form.getlist("item"): + do_something(item) + + +.. _functions-in-cgi-module: + +Functions +--------- + +These are useful if you want more control, or if you want to employ some of the +algorithms implemented in this module in other circumstances. + + +.. function:: parse(fp=None, environ=os.environ, keep_blank_values=False, strict_parsing=False) + + Parse a query in the environment or from a file (the file defaults to + ``sys.stdin``). The *keep_blank_values* and *strict_parsing* parameters are + passed to :func:`urllib.parse.parse_qs` unchanged. + + +.. function:: parse_multipart(fp, pdict, encoding="utf-8", errors="replace") + + Parse input of type :mimetype:`multipart/form-data` (for file uploads). + Arguments are *fp* for the input file, *pdict* for a dictionary containing + other parameters in the :mailheader:`Content-Type` header, and *encoding*, + the request encoding. + + Returns a dictionary just like :func:`urllib.parse.parse_qs`: keys are the + field names, each value is a list of values for that field. For non-file + fields, the value is a list of strings. + + This is easy to use but not much good if you are expecting megabytes to be + uploaded --- in that case, use the :class:`FieldStorage` class instead + which is much more flexible. + + .. versionchanged:: 3.7 + Added the *encoding* and *errors* parameters. For non-file fields, the + value is now a list of strings, not bytes. + + +.. function:: parse_header(string) + + Parse a MIME header (such as :mailheader:`Content-Type`) into a main value and a + dictionary of parameters. + + +.. function:: test() + + Robust test CGI script, usable as main program. Writes minimal HTTP headers and + formats all information provided to the script in HTML form. + + +.. function:: print_environ() + + Format the shell environment in HTML. + + +.. function:: print_form(form) + + Format a form in HTML. + + +.. function:: print_directory() + + Format the current directory in HTML. + + +.. function:: print_environ_usage() + + Print a list of useful (used by CGI) environment variables in HTML. + + +.. _cgi-security: + +Caring about security +--------------------- + +.. index:: pair: CGI; security + +There's one important rule: if you invoke an external program (via the +:func:`os.system` or :func:`os.popen` functions. or others with similar +functionality), make very sure you don't pass arbitrary strings received from +the client to the shell. This is a well-known security hole whereby clever +hackers anywhere on the Web can exploit a gullible CGI script to invoke +arbitrary shell commands. Even parts of the URL or field names cannot be +trusted, since the request doesn't have to come from your form! + +To be on the safe side, if you must pass a string gotten from a form to a shell +command, you should make sure the string contains only alphanumeric characters, +dashes, underscores, and periods. + + +Installing your CGI script on a Unix system +------------------------------------------- + +Read the documentation for your HTTP server and check with your local system +administrator to find the directory where CGI scripts should be installed; +usually this is in a directory :file:`cgi-bin` in the server tree. + +Make sure that your script is readable and executable by "others"; the Unix file +mode should be ``0o755`` octal (use ``chmod 0755 filename``). Make sure that the +first line of the script contains ``#!`` starting in column 1 followed by the +pathname of the Python interpreter, for instance:: + + #!/usr/local/bin/python + +Make sure the Python interpreter exists and is executable by "others". + +Make sure that any files your script needs to read or write are readable or +writable, respectively, by "others" --- their mode should be ``0o644`` for +readable and ``0o666`` for writable. This is because, for security reasons, the +HTTP server executes your script as user "nobody", without any special +privileges. It can only read (write, execute) files that everybody can read +(write, execute). The current directory at execution time is also different (it +is usually the server's cgi-bin directory) and the set of environment variables +is also different from what you get when you log in. In particular, don't count +on the shell's search path for executables (:envvar:`PATH`) or the Python module +search path (:envvar:`PYTHONPATH`) to be set to anything interesting. + +If you need to load modules from a directory which is not on Python's default +module search path, you can change the path in your script, before importing +other modules. For example:: + + import sys + sys.path.insert(0, "/usr/home/joe/lib/python") + sys.path.insert(0, "/usr/local/lib/python") + +(This way, the directory inserted last will be searched first!) + +Instructions for non-Unix systems will vary; check your HTTP server's +documentation (it will usually have a section on CGI scripts). + + +Testing your CGI script +----------------------- + +Unfortunately, a CGI script will generally not run when you try it from the +command line, and a script that works perfectly from the command line may fail +mysteriously when run from the server. There's one reason why you should still +test your script from the command line: if it contains a syntax error, the +Python interpreter won't execute it at all, and the HTTP server will most likely +send a cryptic error to the client. + +Assuming your script has no syntax errors, yet it does not work, you have no +choice but to read the next section. + + +Debugging CGI scripts +--------------------- + +.. index:: pair: CGI; debugging + +First of all, check for trivial installation errors --- reading the section +above on installing your CGI script carefully can save you a lot of time. If +you wonder whether you have understood the installation procedure correctly, try +installing a copy of this module file (:file:`cgi.py`) as a CGI script. When +invoked as a script, the file will dump its environment and the contents of the +form in HTML form. Give it the right mode etc, and send it a request. If it's +installed in the standard :file:`cgi-bin` directory, it should be possible to +send it a request by entering a URL into your browser of the form: + +.. code-block:: none + + http://yourhostname/cgi-bin/cgi.py?name=Joe+Blow&addr=At+Home + +If this gives an error of type 404, the server cannot find the script -- perhaps +you need to install it in a different directory. If it gives another error, +there's an installation problem that you should fix before trying to go any +further. If you get a nicely formatted listing of the environment and form +content (in this example, the fields should be listed as "addr" with value "At +Home" and "name" with value "Joe Blow"), the :file:`cgi.py` script has been +installed correctly. If you follow the same procedure for your own script, you +should now be able to debug it. + +The next step could be to call the :mod:`cgi` module's :func:`test` function +from your script: replace its main code with the single statement :: + + cgi.test() + +This should produce the same results as those gotten from installing the +:file:`cgi.py` file itself. + +When an ordinary Python script raises an unhandled exception (for whatever +reason: of a typo in a module name, a file that can't be opened, etc.), the +Python interpreter prints a nice traceback and exits. While the Python +interpreter will still do this when your CGI script raises an exception, most +likely the traceback will end up in one of the HTTP server's log files, or be +discarded altogether. + +Fortunately, once you have managed to get your script to execute *some* code, +you can easily send tracebacks to the Web browser using the :mod:`cgitb` module. +If you haven't done so already, just add the lines:: + + import cgitb + cgitb.enable() + +to the top of your script. Then try running it again; when a problem occurs, +you should see a detailed report that will likely make apparent the cause of the +crash. + +If you suspect that there may be a problem in importing the :mod:`cgitb` module, +you can use an even more robust approach (which only uses built-in modules):: + + import sys + sys.stderr = sys.stdout + print("Content-Type: text/plain") + print() + ...your code here... + +This relies on the Python interpreter to print the traceback. The content type +of the output is set to plain text, which disables all HTML processing. If your +script works, the raw HTML will be displayed by your client. If it raises an +exception, most likely after the first two lines have been printed, a traceback +will be displayed. Because no HTML interpretation is going on, the traceback +will be readable. + + +Common problems and solutions +----------------------------- + +* Most HTTP servers buffer the output from CGI scripts until the script is + completed. This means that it is not possible to display a progress report on + the client's display while the script is running. + +* Check the installation instructions above. + +* Check the HTTP server's log files. (``tail -f logfile`` in a separate window + may be useful!) + +* Always check a script for syntax errors first, by doing something like + ``python script.py``. + +* If your script does not have any syntax errors, try adding ``import cgitb; + cgitb.enable()`` to the top of the script. + +* When invoking external programs, make sure they can be found. Usually, this + means using absolute path names --- :envvar:`PATH` is usually not set to a very + useful value in a CGI script. + +* When reading or writing external files, make sure they can be read or written + by the userid under which your CGI script will be running: this is typically the + userid under which the web server is running, or some explicitly specified + userid for a web server's ``suexec`` feature. + +* Don't try to give a CGI script a set-uid mode. This doesn't work on most + systems, and is a security liability as well. + +.. rubric:: Footnotes + +.. [#] Note that some recent versions of the HTML specification do state what + order the field values should be supplied in, but knowing whether a request + was received from a conforming browser, or even from a browser at all, is + tedious and error-prone. diff --git a/cpython_2/environment/repo/Doc/library/cgitb.rst b/cpython_2/environment/repo/Doc/library/cgitb.rst new file mode 100644 index 0000000000000000000000000000000000000000..5f3a6476dd8cdcf5431425576ea14f3b0c638fd5 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/cgitb.rst @@ -0,0 +1,84 @@ +:mod:`cgitb` --- Traceback manager for CGI scripts +================================================== + +.. module:: cgitb + :synopsis: Configurable traceback handler for CGI scripts. + +.. moduleauthor:: Ka-Ping Yee +.. sectionauthor:: Fred L. Drake, Jr. + +**Source code:** :source:`Lib/cgitb.py` + +.. index:: + single: CGI; exceptions + single: CGI; tracebacks + single: exceptions; in CGI scripts + single: tracebacks; in CGI scripts + +-------------- + +The :mod:`cgitb` module provides a special exception handler for Python scripts. +(Its name is a bit misleading. It was originally designed to display extensive +traceback information in HTML for CGI scripts. It was later generalized to also +display this information in plain text.) After this module is activated, if an +uncaught exception occurs, a detailed, formatted report will be displayed. The +report includes a traceback showing excerpts of the source code for each level, +as well as the values of the arguments and local variables to currently running +functions, to help you debug the problem. Optionally, you can save this +information to a file instead of sending it to the browser. + +To enable this feature, simply add this to the top of your CGI script:: + + import cgitb + cgitb.enable() + +The options to the :func:`enable` function control whether the report is +displayed in the browser and whether the report is logged to a file for later +analysis. + + +.. function:: enable(display=1, logdir=None, context=5, format="html") + + .. index:: single: excepthook() (in module sys) + + This function causes the :mod:`cgitb` module to take over the interpreter's + default handling for exceptions by setting the value of :attr:`sys.excepthook`. + + The optional argument *display* defaults to ``1`` and can be set to ``0`` to + suppress sending the traceback to the browser. If the argument *logdir* is + present, the traceback reports are written to files. The value of *logdir* + should be a directory where these files will be placed. The optional argument + *context* is the number of lines of context to display around the current line + of source code in the traceback; this defaults to ``5``. If the optional + argument *format* is ``"html"``, the output is formatted as HTML. Any other + value forces plain text output. The default value is ``"html"``. + + +.. function:: text(info, context=5) + + This function handles the exception described by *info* (a 3-tuple containing + the result of :func:`sys.exc_info`), formatting its traceback as text and + returning the result as a string. The optional argument *context* is the + number of lines of context to display around the current line of source code + in the traceback; this defaults to ``5``. + + +.. function:: html(info, context=5) + + This function handles the exception described by *info* (a 3-tuple containing + the result of :func:`sys.exc_info`), formatting its traceback as HTML and + returning the result as a string. The optional argument *context* is the + number of lines of context to display around the current line of source code + in the traceback; this defaults to ``5``. + + +.. function:: handler(info=None) + + This function handles an exception using the default settings (that is, show a + report in the browser, but don't log to a file). This can be used when you've + caught an exception and want to report it using :mod:`cgitb`. The optional + *info* argument should be a 3-tuple containing an exception type, exception + value, and traceback object, exactly like the tuple returned by + :func:`sys.exc_info`. If the *info* argument is not supplied, the current + exception is obtained from :func:`sys.exc_info`. + diff --git a/cpython_2/environment/repo/Doc/library/chunk.rst b/cpython_2/environment/repo/Doc/library/chunk.rst new file mode 100644 index 0000000000000000000000000000000000000000..5e24df923ed21024f986d8597921f1ac6938b344 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/chunk.rst @@ -0,0 +1,137 @@ +:mod:`chunk` --- Read IFF chunked data +====================================== + +.. module:: chunk + :synopsis: Module to read IFF chunks. + +.. moduleauthor:: Sjoerd Mullender +.. sectionauthor:: Sjoerd Mullender + +**Source code:** :source:`Lib/chunk.py` + +.. index:: + single: Audio Interchange File Format + single: AIFF + single: AIFF-C + single: Real Media File Format + single: RMFF + +-------------- + +This module provides an interface for reading files that use EA IFF 85 chunks. +[#]_ This format is used in at least the Audio Interchange File Format +(AIFF/AIFF-C) and the Real Media File Format (RMFF). The WAVE audio file format +is closely related and can also be read using this module. + +A chunk has the following structure: + ++---------+--------+-------------------------------+ +| Offset | Length | Contents | ++=========+========+===============================+ +| 0 | 4 | Chunk ID | ++---------+--------+-------------------------------+ +| 4 | 4 | Size of chunk in big-endian | +| | | byte order, not including the | +| | | header | ++---------+--------+-------------------------------+ +| 8 | *n* | Data bytes, where *n* is the | +| | | size given in the preceding | +| | | field | ++---------+--------+-------------------------------+ +| 8 + *n* | 0 or 1 | Pad byte needed if *n* is odd | +| | | and chunk alignment is used | ++---------+--------+-------------------------------+ + +The ID is a 4-byte string which identifies the type of chunk. + +The size field (a 32-bit value, encoded using big-endian byte order) gives the +size of the chunk data, not including the 8-byte header. + +Usually an IFF-type file consists of one or more chunks. The proposed usage of +the :class:`Chunk` class defined here is to instantiate an instance at the start +of each chunk and read from the instance until it reaches the end, after which a +new instance can be instantiated. At the end of the file, creating a new +instance will fail with an :exc:`EOFError` exception. + + +.. class:: Chunk(file, align=True, bigendian=True, inclheader=False) + + Class which represents a chunk. The *file* argument is expected to be a + file-like object. An instance of this class is specifically allowed. The + only method that is needed is :meth:`~io.IOBase.read`. If the methods + :meth:`~io.IOBase.seek` and :meth:`~io.IOBase.tell` are present and don't + raise an exception, they are also used. + If these methods are present and raise an exception, they are expected to not + have altered the object. If the optional argument *align* is true, chunks + are assumed to be aligned on 2-byte boundaries. If *align* is false, no + alignment is assumed. The default value is true. If the optional argument + *bigendian* is false, the chunk size is assumed to be in little-endian order. + This is needed for WAVE audio files. The default value is true. If the + optional argument *inclheader* is true, the size given in the chunk header + includes the size of the header. The default value is false. + + A :class:`Chunk` object supports the following methods: + + + .. method:: getname() + + Returns the name (ID) of the chunk. This is the first 4 bytes of the + chunk. + + + .. method:: getsize() + + Returns the size of the chunk. + + + .. method:: close() + + Close and skip to the end of the chunk. This does not close the + underlying file. + + The remaining methods will raise :exc:`OSError` if called after the + :meth:`close` method has been called. Before Python 3.3, they used to + raise :exc:`IOError`, now an alias of :exc:`OSError`. + + + .. method:: isatty() + + Returns ``False``. + + + .. method:: seek(pos, whence=0) + + Set the chunk's current position. The *whence* argument is optional and + defaults to ``0`` (absolute file positioning); other values are ``1`` + (seek relative to the current position) and ``2`` (seek relative to the + file's end). There is no return value. If the underlying file does not + allow seek, only forward seeks are allowed. + + + .. method:: tell() + + Return the current position into the chunk. + + + .. method:: read(size=-1) + + Read at most *size* bytes from the chunk (less if the read hits the end of + the chunk before obtaining *size* bytes). If the *size* argument is + negative or omitted, read all data until the end of the chunk. An empty + bytes object is returned when the end of the chunk is encountered + immediately. + + + .. method:: skip() + + Skip to the end of the chunk. All further calls to :meth:`read` for the + chunk will return ``b''``. If you are not interested in the contents of + the chunk, this method should be called so that the file points to the + start of the next chunk. + + +.. rubric:: Footnotes + +.. [#] "EA IFF 85" Standard for Interchange Format Files, Jerry Morrison, Electronic + Arts, January 1985. + diff --git a/cpython_2/environment/repo/Doc/library/cmath.rst b/cpython_2/environment/repo/Doc/library/cmath.rst new file mode 100644 index 0000000000000000000000000000000000000000..28cd96b0e12da9c71cd78fad1730e9f7cd4f66be --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/cmath.rst @@ -0,0 +1,316 @@ +:mod:`cmath` --- Mathematical functions for complex numbers +=========================================================== + +.. module:: cmath + :synopsis: Mathematical functions for complex numbers. + +-------------- + +This module provides access to mathematical functions for complex numbers. The +functions in this module accept integers, floating-point numbers or complex +numbers as arguments. They will also accept any Python object that has either a +:meth:`__complex__` or a :meth:`__float__` method: these methods are used to +convert the object to a complex or floating-point number, respectively, and +the function is then applied to the result of the conversion. + +.. note:: + + On platforms with hardware and system-level support for signed + zeros, functions involving branch cuts are continuous on *both* + sides of the branch cut: the sign of the zero distinguishes one + side of the branch cut from the other. On platforms that do not + support signed zeros the continuity is as specified below. + + +Conversions to and from polar coordinates +----------------------------------------- + +A Python complex number ``z`` is stored internally using *rectangular* +or *Cartesian* coordinates. It is completely determined by its *real +part* ``z.real`` and its *imaginary part* ``z.imag``. In other +words:: + + z == z.real + z.imag*1j + +*Polar coordinates* give an alternative way to represent a complex +number. In polar coordinates, a complex number *z* is defined by the +modulus *r* and the phase angle *phi*. The modulus *r* is the distance +from *z* to the origin, while the phase *phi* is the counterclockwise +angle, measured in radians, from the positive x-axis to the line +segment that joins the origin to *z*. + +The following functions can be used to convert from the native +rectangular coordinates to polar coordinates and back. + +.. function:: phase(x) + + Return the phase of *x* (also known as the *argument* of *x*), as a + float. ``phase(x)`` is equivalent to ``math.atan2(x.imag, + x.real)``. The result lies in the range [-\ *π*, *π*], and the branch + cut for this operation lies along the negative real axis, + continuous from above. On systems with support for signed zeros + (which includes most systems in current use), this means that the + sign of the result is the same as the sign of ``x.imag``, even when + ``x.imag`` is zero:: + + >>> phase(complex(-1.0, 0.0)) + 3.141592653589793 + >>> phase(complex(-1.0, -0.0)) + -3.141592653589793 + + +.. note:: + + The modulus (absolute value) of a complex number *x* can be + computed using the built-in :func:`abs` function. There is no + separate :mod:`cmath` module function for this operation. + + +.. function:: polar(x) + + Return the representation of *x* in polar coordinates. Returns a + pair ``(r, phi)`` where *r* is the modulus of *x* and phi is the + phase of *x*. ``polar(x)`` is equivalent to ``(abs(x), + phase(x))``. + + +.. function:: rect(r, phi) + + Return the complex number *x* with polar coordinates *r* and *phi*. + Equivalent to ``r * (math.cos(phi) + math.sin(phi)*1j)``. + + +Power and logarithmic functions +------------------------------- + +.. function:: exp(x) + + Return *e* raised to the power *x*, where *e* is the base of natural + logarithms. + + +.. function:: log(x[, base]) + + Returns the logarithm of *x* to the given *base*. If the *base* is not + specified, returns the natural logarithm of *x*. There is one branch cut, from 0 + along the negative real axis to -∞, continuous from above. + + +.. function:: log10(x) + + Return the base-10 logarithm of *x*. This has the same branch cut as + :func:`log`. + + +.. function:: sqrt(x) + + Return the square root of *x*. This has the same branch cut as :func:`log`. + + +Trigonometric functions +----------------------- + +.. function:: acos(x) + + Return the arc cosine of *x*. There are two branch cuts: One extends right from + 1 along the real axis to ∞, continuous from below. The other extends left from + -1 along the real axis to -∞, continuous from above. + + +.. function:: asin(x) + + Return the arc sine of *x*. This has the same branch cuts as :func:`acos`. + + +.. function:: atan(x) + + Return the arc tangent of *x*. There are two branch cuts: One extends from + ``1j`` along the imaginary axis to ``∞j``, continuous from the right. The + other extends from ``-1j`` along the imaginary axis to ``-∞j``, continuous + from the left. + + +.. function:: cos(x) + + Return the cosine of *x*. + + +.. function:: sin(x) + + Return the sine of *x*. + + +.. function:: tan(x) + + Return the tangent of *x*. + + +Hyperbolic functions +-------------------- + +.. function:: acosh(x) + + Return the inverse hyperbolic cosine of *x*. There is one branch cut, + extending left from 1 along the real axis to -∞, continuous from above. + + +.. function:: asinh(x) + + Return the inverse hyperbolic sine of *x*. There are two branch cuts: + One extends from ``1j`` along the imaginary axis to ``∞j``, + continuous from the right. The other extends from ``-1j`` along + the imaginary axis to ``-∞j``, continuous from the left. + + +.. function:: atanh(x) + + Return the inverse hyperbolic tangent of *x*. There are two branch cuts: One + extends from ``1`` along the real axis to ``∞``, continuous from below. The + other extends from ``-1`` along the real axis to ``-∞``, continuous from + above. + + +.. function:: cosh(x) + + Return the hyperbolic cosine of *x*. + + +.. function:: sinh(x) + + Return the hyperbolic sine of *x*. + + +.. function:: tanh(x) + + Return the hyperbolic tangent of *x*. + + +Classification functions +------------------------ + +.. function:: isfinite(x) + + Return ``True`` if both the real and imaginary parts of *x* are finite, and + ``False`` otherwise. + + .. versionadded:: 3.2 + + +.. function:: isinf(x) + + Return ``True`` if either the real or the imaginary part of *x* is an + infinity, and ``False`` otherwise. + + +.. function:: isnan(x) + + Return ``True`` if either the real or the imaginary part of *x* is a NaN, + and ``False`` otherwise. + + +.. function:: isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0) + + Return ``True`` if the values *a* and *b* are close to each other and + ``False`` otherwise. + + Whether or not two values are considered close is determined according to + given absolute and relative tolerances. + + *rel_tol* is the relative tolerance -- it is the maximum allowed difference + between *a* and *b*, relative to the larger absolute value of *a* or *b*. + For example, to set a tolerance of 5%, pass ``rel_tol=0.05``. The default + tolerance is ``1e-09``, which assures that the two values are the same + within about 9 decimal digits. *rel_tol* must be greater than zero. + + *abs_tol* is the minimum absolute tolerance -- useful for comparisons near + zero. *abs_tol* must be at least zero. + + If no errors occur, the result will be: + ``abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)``. + + The IEEE 754 special values of ``NaN``, ``inf``, and ``-inf`` will be + handled according to IEEE rules. Specifically, ``NaN`` is not considered + close to any other value, including ``NaN``. ``inf`` and ``-inf`` are only + considered close to themselves. + + .. versionadded:: 3.5 + + .. seealso:: + + :pep:`485` -- A function for testing approximate equality + + +Constants +--------- + +.. data:: pi + + The mathematical constant *π*, as a float. + + +.. data:: e + + The mathematical constant *e*, as a float. + + +.. data:: tau + + The mathematical constant *τ*, as a float. + + .. versionadded:: 3.6 + + +.. data:: inf + + Floating-point positive infinity. Equivalent to ``float('inf')``. + + .. versionadded:: 3.6 + + +.. data:: infj + + Complex number with zero real part and positive infinity imaginary + part. Equivalent to ``complex(0.0, float('inf'))``. + + .. versionadded:: 3.6 + + +.. data:: nan + + A floating-point "not a number" (NaN) value. Equivalent to + ``float('nan')``. + + .. versionadded:: 3.6 + + +.. data:: nanj + + Complex number with zero real part and NaN imaginary part. Equivalent to + ``complex(0.0, float('nan'))``. + + .. versionadded:: 3.6 + + +.. index:: module: math + +Note that the selection of functions is similar, but not identical, to that in +module :mod:`math`. The reason for having two modules is that some users aren't +interested in complex numbers, and perhaps don't even know what they are. They +would rather have ``math.sqrt(-1)`` raise an exception than return a complex +number. Also note that the functions defined in :mod:`cmath` always return a +complex number, even if the answer can be expressed as a real number (in which +case the complex number has an imaginary part of zero). + +A note on branch cuts: They are curves along which the given function fails to +be continuous. They are a necessary feature of many complex functions. It is +assumed that if you need to compute with complex functions, you will understand +about branch cuts. Consult almost any (not too elementary) book on complex +variables for enlightenment. For information of the proper choice of branch +cuts for numerical purposes, a good reference should be the following: + + +.. seealso:: + + Kahan, W: Branch cuts for complex elementary functions; or, Much ado about + nothing's sign bit. In Iserles, A., and Powell, M. (eds.), The state of the art + in numerical analysis. Clarendon Press (1987) pp165--211. diff --git a/cpython_2/environment/repo/Doc/library/cmd.rst b/cpython_2/environment/repo/Doc/library/cmd.rst new file mode 100644 index 0000000000000000000000000000000000000000..d57edb7eb1698d203592b6d5ac68d16a78161d4e --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/cmd.rst @@ -0,0 +1,381 @@ +:mod:`cmd` --- Support for line-oriented command interpreters +============================================================= + +.. module:: cmd + :synopsis: Build line-oriented command interpreters. + +.. sectionauthor:: Eric S. Raymond + +**Source code:** :source:`Lib/cmd.py` + +-------------- + +The :class:`Cmd` class provides a simple framework for writing line-oriented +command interpreters. These are often useful for test harnesses, administrative +tools, and prototypes that will later be wrapped in a more sophisticated +interface. + +.. class:: Cmd(completekey='tab', stdin=None, stdout=None) + + A :class:`Cmd` instance or subclass instance is a line-oriented interpreter + framework. There is no good reason to instantiate :class:`Cmd` itself; rather, + it's useful as a superclass of an interpreter class you define yourself in order + to inherit :class:`Cmd`'s methods and encapsulate action methods. + + The optional argument *completekey* is the :mod:`readline` name of a completion + key; it defaults to :kbd:`Tab`. If *completekey* is not :const:`None` and + :mod:`readline` is available, command completion is done automatically. + + The optional arguments *stdin* and *stdout* specify the input and output file + objects that the Cmd instance or subclass instance will use for input and + output. If not specified, they will default to :data:`sys.stdin` and + :data:`sys.stdout`. + + If you want a given *stdin* to be used, make sure to set the instance's + :attr:`use_rawinput` attribute to ``False``, otherwise *stdin* will be + ignored. + + +.. _cmd-objects: + +Cmd Objects +----------- + +A :class:`Cmd` instance has the following methods: + + +.. method:: Cmd.cmdloop(intro=None) + + Repeatedly issue a prompt, accept input, parse an initial prefix off the + received input, and dispatch to action methods, passing them the remainder of + the line as argument. + + The optional argument is a banner or intro string to be issued before the first + prompt (this overrides the :attr:`intro` class attribute). + + If the :mod:`readline` module is loaded, input will automatically inherit + :program:`bash`\ -like history-list editing (e.g. :kbd:`Control-P` scrolls back + to the last command, :kbd:`Control-N` forward to the next one, :kbd:`Control-F` + moves the cursor to the right non-destructively, :kbd:`Control-B` moves the + cursor to the left non-destructively, etc.). + + An end-of-file on input is passed back as the string ``'EOF'``. + + .. index:: + single: ? (question mark); in a command interpreter + single: ! (exclamation); in a command interpreter + + An interpreter instance will recognize a command name ``foo`` if and only if it + has a method :meth:`do_foo`. As a special case, a line beginning with the + character ``'?'`` is dispatched to the method :meth:`do_help`. As another + special case, a line beginning with the character ``'!'`` is dispatched to the + method :meth:`do_shell` (if such a method is defined). + + This method will return when the :meth:`postcmd` method returns a true value. + The *stop* argument to :meth:`postcmd` is the return value from the command's + corresponding :meth:`do_\*` method. + + If completion is enabled, completing commands will be done automatically, and + completing of commands args is done by calling :meth:`complete_foo` with + arguments *text*, *line*, *begidx*, and *endidx*. *text* is the string prefix + we are attempting to match: all returned matches must begin with it. *line* is + the current input line with leading whitespace removed, *begidx* and *endidx* + are the beginning and ending indexes of the prefix text, which could be used to + provide different completion depending upon which position the argument is in. + + All subclasses of :class:`Cmd` inherit a predefined :meth:`do_help`. This + method, called with an argument ``'bar'``, invokes the corresponding method + :meth:`help_bar`, and if that is not present, prints the docstring of + :meth:`do_bar`, if available. With no argument, :meth:`do_help` lists all + available help topics (that is, all commands with corresponding + :meth:`help_\*` methods or commands that have docstrings), and also lists any + undocumented commands. + + +.. method:: Cmd.onecmd(str) + + Interpret the argument as though it had been typed in response to the prompt. + This may be overridden, but should not normally need to be; see the + :meth:`precmd` and :meth:`postcmd` methods for useful execution hooks. The + return value is a flag indicating whether interpretation of commands by the + interpreter should stop. If there is a :meth:`do_\*` method for the command + *str*, the return value of that method is returned, otherwise the return value + from the :meth:`default` method is returned. + + +.. method:: Cmd.emptyline() + + Method called when an empty line is entered in response to the prompt. If this + method is not overridden, it repeats the last nonempty command entered. + + +.. method:: Cmd.default(line) + + Method called on an input line when the command prefix is not recognized. If + this method is not overridden, it prints an error message and returns. + + +.. method:: Cmd.completedefault(text, line, begidx, endidx) + + Method called to complete an input line when no command-specific + :meth:`complete_\*` method is available. By default, it returns an empty list. + + +.. method:: Cmd.precmd(line) + + Hook method executed just before the command line *line* is interpreted, but + after the input prompt is generated and issued. This method is a stub in + :class:`Cmd`; it exists to be overridden by subclasses. The return value is + used as the command which will be executed by the :meth:`onecmd` method; the + :meth:`precmd` implementation may re-write the command or simply return *line* + unchanged. + + +.. method:: Cmd.postcmd(stop, line) + + Hook method executed just after a command dispatch is finished. This method is + a stub in :class:`Cmd`; it exists to be overridden by subclasses. *line* is the + command line which was executed, and *stop* is a flag which indicates whether + execution will be terminated after the call to :meth:`postcmd`; this will be the + return value of the :meth:`onecmd` method. The return value of this method will + be used as the new value for the internal flag which corresponds to *stop*; + returning false will cause interpretation to continue. + + +.. method:: Cmd.preloop() + + Hook method executed once when :meth:`cmdloop` is called. This method is a stub + in :class:`Cmd`; it exists to be overridden by subclasses. + + +.. method:: Cmd.postloop() + + Hook method executed once when :meth:`cmdloop` is about to return. This method + is a stub in :class:`Cmd`; it exists to be overridden by subclasses. + + +Instances of :class:`Cmd` subclasses have some public instance variables: + +.. attribute:: Cmd.prompt + + The prompt issued to solicit input. + + +.. attribute:: Cmd.identchars + + The string of characters accepted for the command prefix. + + +.. attribute:: Cmd.lastcmd + + The last nonempty command prefix seen. + + +.. attribute:: Cmd.cmdqueue + + A list of queued input lines. The cmdqueue list is checked in + :meth:`cmdloop` when new input is needed; if it is nonempty, its elements + will be processed in order, as if entered at the prompt. + + +.. attribute:: Cmd.intro + + A string to issue as an intro or banner. May be overridden by giving the + :meth:`cmdloop` method an argument. + + +.. attribute:: Cmd.doc_header + + The header to issue if the help output has a section for documented commands. + + +.. attribute:: Cmd.misc_header + + The header to issue if the help output has a section for miscellaneous help + topics (that is, there are :meth:`help_\*` methods without corresponding + :meth:`do_\*` methods). + + +.. attribute:: Cmd.undoc_header + + The header to issue if the help output has a section for undocumented commands + (that is, there are :meth:`do_\*` methods without corresponding :meth:`help_\*` + methods). + + +.. attribute:: Cmd.ruler + + The character used to draw separator lines under the help-message headers. If + empty, no ruler line is drawn. It defaults to ``'='``. + + +.. attribute:: Cmd.use_rawinput + + A flag, defaulting to true. If true, :meth:`cmdloop` uses :func:`input` to + display a prompt and read the next command; if false, :meth:`sys.stdout.write` + and :meth:`sys.stdin.readline` are used. (This means that by importing + :mod:`readline`, on systems that support it, the interpreter will automatically + support :program:`Emacs`\ -like line editing and command-history keystrokes.) + + +.. _cmd-example: + +Cmd Example +----------- + +.. sectionauthor:: Raymond Hettinger + +The :mod:`cmd` module is mainly useful for building custom shells that let a +user work with a program interactively. + +This section presents a simple example of how to build a shell around a few of +the commands in the :mod:`turtle` module. + +Basic turtle commands such as :meth:`~turtle.forward` are added to a +:class:`Cmd` subclass with method named :meth:`do_forward`. The argument is +converted to a number and dispatched to the turtle module. The docstring is +used in the help utility provided by the shell. + +The example also includes a basic record and playback facility implemented with +the :meth:`~Cmd.precmd` method which is responsible for converting the input to +lowercase and writing the commands to a file. The :meth:`do_playback` method +reads the file and adds the recorded commands to the :attr:`cmdqueue` for +immediate playback:: + + import cmd, sys + from turtle import * + + class TurtleShell(cmd.Cmd): + intro = 'Welcome to the turtle shell. Type help or ? to list commands.\n' + prompt = '(turtle) ' + file = None + + # ----- basic turtle commands ----- + def do_forward(self, arg): + 'Move the turtle forward by the specified distance: FORWARD 10' + forward(*parse(arg)) + def do_right(self, arg): + 'Turn turtle right by given number of degrees: RIGHT 20' + right(*parse(arg)) + def do_left(self, arg): + 'Turn turtle left by given number of degrees: LEFT 90' + left(*parse(arg)) + def do_goto(self, arg): + 'Move turtle to an absolute position with changing orientation. GOTO 100 200' + goto(*parse(arg)) + def do_home(self, arg): + 'Return turtle to the home position: HOME' + home() + def do_circle(self, arg): + 'Draw circle with given radius an options extent and steps: CIRCLE 50' + circle(*parse(arg)) + def do_position(self, arg): + 'Print the current turtle position: POSITION' + print('Current position is %d %d\n' % position()) + def do_heading(self, arg): + 'Print the current turtle heading in degrees: HEADING' + print('Current heading is %d\n' % (heading(),)) + def do_color(self, arg): + 'Set the color: COLOR BLUE' + color(arg.lower()) + def do_undo(self, arg): + 'Undo (repeatedly) the last turtle action(s): UNDO' + def do_reset(self, arg): + 'Clear the screen and return turtle to center: RESET' + reset() + def do_bye(self, arg): + 'Stop recording, close the turtle window, and exit: BYE' + print('Thank you for using Turtle') + self.close() + bye() + return True + + # ----- record and playback ----- + def do_record(self, arg): + 'Save future commands to filename: RECORD rose.cmd' + self.file = open(arg, 'w') + def do_playback(self, arg): + 'Playback commands from a file: PLAYBACK rose.cmd' + self.close() + with open(arg) as f: + self.cmdqueue.extend(f.read().splitlines()) + def precmd(self, line): + line = line.lower() + if self.file and 'playback' not in line: + print(line, file=self.file) + return line + def close(self): + if self.file: + self.file.close() + self.file = None + + def parse(arg): + 'Convert a series of zero or more numbers to an argument tuple' + return tuple(map(int, arg.split())) + + if __name__ == '__main__': + TurtleShell().cmdloop() + + +Here is a sample session with the turtle shell showing the help functions, using +blank lines to repeat commands, and the simple record and playback facility: + +.. code-block:: none + + Welcome to the turtle shell. Type help or ? to list commands. + + (turtle) ? + + Documented commands (type help ): + ======================================== + bye color goto home playback record right + circle forward heading left position reset undo + + (turtle) help forward + Move the turtle forward by the specified distance: FORWARD 10 + (turtle) record spiral.cmd + (turtle) position + Current position is 0 0 + + (turtle) heading + Current heading is 0 + + (turtle) reset + (turtle) circle 20 + (turtle) right 30 + (turtle) circle 40 + (turtle) right 30 + (turtle) circle 60 + (turtle) right 30 + (turtle) circle 80 + (turtle) right 30 + (turtle) circle 100 + (turtle) right 30 + (turtle) circle 120 + (turtle) right 30 + (turtle) circle 120 + (turtle) heading + Current heading is 180 + + (turtle) forward 100 + (turtle) + (turtle) right 90 + (turtle) forward 100 + (turtle) + (turtle) right 90 + (turtle) forward 400 + (turtle) right 90 + (turtle) forward 500 + (turtle) right 90 + (turtle) forward 400 + (turtle) right 90 + (turtle) forward 300 + (turtle) playback spiral.cmd + Current position is 0 0 + + Current heading is 0 + + Current heading is 180 + + (turtle) bye + Thank you for using Turtle diff --git a/cpython_2/environment/repo/Doc/library/code.rst b/cpython_2/environment/repo/Doc/library/code.rst new file mode 100644 index 0000000000000000000000000000000000000000..538e5afc7822aa8ea102bfaecbc379d28f937b2e --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/code.rst @@ -0,0 +1,184 @@ +:mod:`code` --- Interpreter base classes +======================================== + +.. module:: code + :synopsis: Facilities to implement read-eval-print loops. + +**Source code:** :source:`Lib/code.py` + +-------------- + +The ``code`` module provides facilities to implement read-eval-print loops in +Python. Two classes and convenience functions are included which can be used to +build applications which provide an interactive interpreter prompt. + + +.. class:: InteractiveInterpreter(locals=None) + + This class deals with parsing and interpreter state (the user's namespace); it + does not deal with input buffering or prompting or input file naming (the + filename is always passed in explicitly). The optional *locals* argument + specifies the dictionary in which code will be executed; it defaults to a newly + created dictionary with key ``'__name__'`` set to ``'__console__'`` and key + ``'__doc__'`` set to ``None``. + + +.. class:: InteractiveConsole(locals=None, filename="") + + Closely emulate the behavior of the interactive Python interpreter. This class + builds on :class:`InteractiveInterpreter` and adds prompting using the familiar + ``sys.ps1`` and ``sys.ps2``, and input buffering. + + +.. function:: interact(banner=None, readfunc=None, local=None, exitmsg=None) + + Convenience function to run a read-eval-print loop. This creates a new + instance of :class:`InteractiveConsole` and sets *readfunc* to be used as + the :meth:`InteractiveConsole.raw_input` method, if provided. If *local* is + provided, it is passed to the :class:`InteractiveConsole` constructor for + use as the default namespace for the interpreter loop. The :meth:`interact` + method of the instance is then run with *banner* and *exitmsg* passed as the + banner and exit message to use, if provided. The console object is discarded + after use. + + .. versionchanged:: 3.6 + Added *exitmsg* parameter. + + +.. function:: compile_command(source, filename="", symbol="single") + + This function is useful for programs that want to emulate Python's interpreter + main loop (a.k.a. the read-eval-print loop). The tricky part is to determine + when the user has entered an incomplete command that can be completed by + entering more text (as opposed to a complete command or a syntax error). This + function *almost* always makes the same decision as the real interpreter main + loop. + + *source* is the source string; *filename* is the optional filename from which + source was read, defaulting to ``''``; and *symbol* is the optional + grammar start symbol, which should be ``'single'`` (the default), ``'eval'`` + or ``'exec'``. + + Returns a code object (the same as ``compile(source, filename, symbol)``) if the + command is complete and valid; ``None`` if the command is incomplete; raises + :exc:`SyntaxError` if the command is complete and contains a syntax error, or + raises :exc:`OverflowError` or :exc:`ValueError` if the command contains an + invalid literal. + + +.. _interpreter-objects: + +Interactive Interpreter Objects +------------------------------- + + +.. method:: InteractiveInterpreter.runsource(source, filename="", symbol="single") + + Compile and run some source in the interpreter. Arguments are the same as for + :func:`compile_command`; the default for *filename* is ``''``, and for + *symbol* is ``'single'``. One of several things can happen: + + * The input is incorrect; :func:`compile_command` raised an exception + (:exc:`SyntaxError` or :exc:`OverflowError`). A syntax traceback will be + printed by calling the :meth:`showsyntaxerror` method. :meth:`runsource` + returns ``False``. + + * The input is incomplete, and more input is required; :func:`compile_command` + returned ``None``. :meth:`runsource` returns ``True``. + + * The input is complete; :func:`compile_command` returned a code object. The + code is executed by calling the :meth:`runcode` (which also handles run-time + exceptions, except for :exc:`SystemExit`). :meth:`runsource` returns ``False``. + + The return value can be used to decide whether to use ``sys.ps1`` or ``sys.ps2`` + to prompt the next line. + + +.. method:: InteractiveInterpreter.runcode(code) + + Execute a code object. When an exception occurs, :meth:`showtraceback` is called + to display a traceback. All exceptions are caught except :exc:`SystemExit`, + which is allowed to propagate. + + A note about :exc:`KeyboardInterrupt`: this exception may occur elsewhere in + this code, and may not always be caught. The caller should be prepared to deal + with it. + + +.. method:: InteractiveInterpreter.showsyntaxerror(filename=None) + + Display the syntax error that just occurred. This does not display a stack + trace because there isn't one for syntax errors. If *filename* is given, it is + stuffed into the exception instead of the default filename provided by Python's + parser, because it always uses ``''`` when reading from a string. The + output is written by the :meth:`write` method. + + +.. method:: InteractiveInterpreter.showtraceback() + + Display the exception that just occurred. We remove the first stack item + because it is within the interpreter object implementation. The output is + written by the :meth:`write` method. + + .. versionchanged:: 3.5 The full chained traceback is displayed instead + of just the primary traceback. + + +.. method:: InteractiveInterpreter.write(data) + + Write a string to the standard error stream (``sys.stderr``). Derived classes + should override this to provide the appropriate output handling as needed. + + +.. _console-objects: + +Interactive Console Objects +--------------------------- + +The :class:`InteractiveConsole` class is a subclass of +:class:`InteractiveInterpreter`, and so offers all the methods of the +interpreter objects as well as the following additions. + + +.. method:: InteractiveConsole.interact(banner=None, exitmsg=None) + + Closely emulate the interactive Python console. The optional *banner* argument + specify the banner to print before the first interaction; by default it prints a + banner similar to the one printed by the standard Python interpreter, followed + by the class name of the console object in parentheses (so as not to confuse + this with the real interpreter -- since it's so close!). + + The optional *exitmsg* argument specifies an exit message printed when exiting. + Pass the empty string to suppress the exit message. If *exitmsg* is not given or + ``None``, a default message is printed. + + .. versionchanged:: 3.4 + To suppress printing any banner, pass an empty string. + + .. versionchanged:: 3.6 + Print an exit message when exiting. + + +.. method:: InteractiveConsole.push(line) + + Push a line of source text to the interpreter. The line should not have a + trailing newline; it may have internal newlines. The line is appended to a + buffer and the interpreter's :meth:`runsource` method is called with the + concatenated contents of the buffer as source. If this indicates that the + command was executed or invalid, the buffer is reset; otherwise, the command is + incomplete, and the buffer is left as it was after the line was appended. The + return value is ``True`` if more input is required, ``False`` if the line was + dealt with in some way (this is the same as :meth:`runsource`). + + +.. method:: InteractiveConsole.resetbuffer() + + Remove any unhandled source text from the input buffer. + + +.. method:: InteractiveConsole.raw_input(prompt="") + + Write a prompt and read a line. The returned line does not include the trailing + newline. When the user enters the EOF key sequence, :exc:`EOFError` is raised. + The base implementation reads from ``sys.stdin``; a subclass may replace this + with a different implementation. diff --git a/cpython_2/environment/repo/Doc/library/codecs.rst b/cpython_2/environment/repo/Doc/library/codecs.rst new file mode 100644 index 0000000000000000000000000000000000000000..f071057293eece49e95ad58ea70a8c45d8d39df2 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/codecs.rst @@ -0,0 +1,1496 @@ +:mod:`codecs` --- Codec registry and base classes +================================================= + +.. module:: codecs + :synopsis: Encode and decode data and streams. + +.. moduleauthor:: Marc-André Lemburg +.. sectionauthor:: Marc-André Lemburg +.. sectionauthor:: Martin v. Löwis + +**Source code:** :source:`Lib/codecs.py` + +.. index:: + single: Unicode + single: Codecs + pair: Codecs; encode + pair: Codecs; decode + single: streams + pair: stackable; streams + +-------------- + +This module defines base classes for standard Python codecs (encoders and +decoders) and provides access to the internal Python codec registry, which +manages the codec and error handling lookup process. Most standard codecs +are :term:`text encodings `, which encode text to bytes, +but there are also codecs provided that encode text to text, and bytes to +bytes. Custom codecs may encode and decode between arbitrary types, but some +module features are restricted to use specifically with +:term:`text encodings `, or with codecs that encode to +:class:`bytes`. + +The module defines the following functions for encoding and decoding with +any codec: + +.. function:: encode(obj, encoding='utf-8', errors='strict') + + Encodes *obj* using the codec registered for *encoding*. + + *Errors* may be given to set the desired error handling scheme. The + default error handler is ``'strict'`` meaning that encoding errors raise + :exc:`ValueError` (or a more codec specific subclass, such as + :exc:`UnicodeEncodeError`). Refer to :ref:`codec-base-classes` for more + information on codec error handling. + +.. function:: decode(obj, encoding='utf-8', errors='strict') + + Decodes *obj* using the codec registered for *encoding*. + + *Errors* may be given to set the desired error handling scheme. The + default error handler is ``'strict'`` meaning that decoding errors raise + :exc:`ValueError` (or a more codec specific subclass, such as + :exc:`UnicodeDecodeError`). Refer to :ref:`codec-base-classes` for more + information on codec error handling. + +The full details for each codec can also be looked up directly: + +.. function:: lookup(encoding) + + Looks up the codec info in the Python codec registry and returns a + :class:`CodecInfo` object as defined below. + + Encodings are first looked up in the registry's cache. If not found, the list of + registered search functions is scanned. If no :class:`CodecInfo` object is + found, a :exc:`LookupError` is raised. Otherwise, the :class:`CodecInfo` object + is stored in the cache and returned to the caller. + +.. class:: CodecInfo(encode, decode, streamreader=None, streamwriter=None, incrementalencoder=None, incrementaldecoder=None, name=None) + + Codec details when looking up the codec registry. The constructor + arguments are stored in attributes of the same name: + + + .. attribute:: name + + The name of the encoding. + + + .. attribute:: encode + decode + + The stateless encoding and decoding functions. These must be + functions or methods which have the same interface as + the :meth:`~Codec.encode` and :meth:`~Codec.decode` methods of Codec + instances (see :ref:`Codec Interface `). + The functions or methods are expected to work in a stateless mode. + + + .. attribute:: incrementalencoder + incrementaldecoder + + Incremental encoder and decoder classes or factory functions. + These have to provide the interface defined by the base classes + :class:`IncrementalEncoder` and :class:`IncrementalDecoder`, + respectively. Incremental codecs can maintain state. + + + .. attribute:: streamwriter + streamreader + + Stream writer and reader classes or factory functions. These have to + provide the interface defined by the base classes + :class:`StreamWriter` and :class:`StreamReader`, respectively. + Stream codecs can maintain state. + +To simplify access to the various codec components, the module provides +these additional functions which use :func:`lookup` for the codec lookup: + +.. function:: getencoder(encoding) + + Look up the codec for the given encoding and return its encoder function. + + Raises a :exc:`LookupError` in case the encoding cannot be found. + + +.. function:: getdecoder(encoding) + + Look up the codec for the given encoding and return its decoder function. + + Raises a :exc:`LookupError` in case the encoding cannot be found. + + +.. function:: getincrementalencoder(encoding) + + Look up the codec for the given encoding and return its incremental encoder + class or factory function. + + Raises a :exc:`LookupError` in case the encoding cannot be found or the codec + doesn't support an incremental encoder. + + +.. function:: getincrementaldecoder(encoding) + + Look up the codec for the given encoding and return its incremental decoder + class or factory function. + + Raises a :exc:`LookupError` in case the encoding cannot be found or the codec + doesn't support an incremental decoder. + + +.. function:: getreader(encoding) + + Look up the codec for the given encoding and return its :class:`StreamReader` + class or factory function. + + Raises a :exc:`LookupError` in case the encoding cannot be found. + + +.. function:: getwriter(encoding) + + Look up the codec for the given encoding and return its :class:`StreamWriter` + class or factory function. + + Raises a :exc:`LookupError` in case the encoding cannot be found. + +Custom codecs are made available by registering a suitable codec search +function: + +.. function:: register(search_function) + + Register a codec search function. Search functions are expected to take one + argument, being the encoding name in all lower case letters, and return a + :class:`CodecInfo` object. In case a search function cannot find + a given encoding, it should return ``None``. + + .. note:: + + Search function registration is not currently reversible, + which may cause problems in some cases, such as unit testing or + module reloading. + +While the builtin :func:`open` and the associated :mod:`io` module are the +recommended approach for working with encoded text files, this module +provides additional utility functions and classes that allow the use of a +wider range of codecs when working with binary files: + +.. function:: open(filename, mode='r', encoding=None, errors='strict', buffering=-1) + + Open an encoded file using the given *mode* and return an instance of + :class:`StreamReaderWriter`, providing transparent encoding/decoding. + The default file mode is ``'r'``, meaning to open the file in read mode. + + .. note:: + + Underlying encoded files are always opened in binary mode. + No automatic conversion of ``'\n'`` is done on reading and writing. + The *mode* argument may be any binary mode acceptable to the built-in + :func:`open` function; the ``'b'`` is automatically added. + + *encoding* specifies the encoding which is to be used for the file. + Any encoding that encodes to and decodes from bytes is allowed, and + the data types supported by the file methods depend on the codec used. + + *errors* may be given to define the error handling. It defaults to ``'strict'`` + which causes a :exc:`ValueError` to be raised in case an encoding error occurs. + + *buffering* has the same meaning as for the built-in :func:`open` function. + It defaults to -1 which means that the default buffer size will be used. + + +.. function:: EncodedFile(file, data_encoding, file_encoding=None, errors='strict') + + Return a :class:`StreamRecoder` instance, a wrapped version of *file* + which provides transparent transcoding. The original file is closed + when the wrapped version is closed. + + Data written to the wrapped file is decoded according to the given + *data_encoding* and then written to the original file as bytes using + *file_encoding*. Bytes read from the original file are decoded + according to *file_encoding*, and the result is encoded + using *data_encoding*. + + If *file_encoding* is not given, it defaults to *data_encoding*. + + *errors* may be given to define the error handling. It defaults to + ``'strict'``, which causes :exc:`ValueError` to be raised in case an encoding + error occurs. + + +.. function:: iterencode(iterator, encoding, errors='strict', **kwargs) + + Uses an incremental encoder to iteratively encode the input provided by + *iterator*. This function is a :term:`generator`. + The *errors* argument (as well as any + other keyword argument) is passed through to the incremental encoder. + + This function requires that the codec accept text :class:`str` objects + to encode. Therefore it does not support bytes-to-bytes encoders such as + ``base64_codec``. + + +.. function:: iterdecode(iterator, encoding, errors='strict', **kwargs) + + Uses an incremental decoder to iteratively decode the input provided by + *iterator*. This function is a :term:`generator`. + The *errors* argument (as well as any + other keyword argument) is passed through to the incremental decoder. + + This function requires that the codec accept :class:`bytes` objects + to decode. Therefore it does not support text-to-text encoders such as + ``rot_13``, although ``rot_13`` may be used equivalently with + :func:`iterencode`. + + +The module also provides the following constants which are useful for reading +and writing to platform dependent files: + + +.. data:: BOM + BOM_BE + BOM_LE + BOM_UTF8 + BOM_UTF16 + BOM_UTF16_BE + BOM_UTF16_LE + BOM_UTF32 + BOM_UTF32_BE + BOM_UTF32_LE + + These constants define various byte sequences, + being Unicode byte order marks (BOMs) for several encodings. They are + used in UTF-16 and UTF-32 data streams to indicate the byte order used, + and in UTF-8 as a Unicode signature. :const:`BOM_UTF16` is either + :const:`BOM_UTF16_BE` or :const:`BOM_UTF16_LE` depending on the platform's + native byte order, :const:`BOM` is an alias for :const:`BOM_UTF16`, + :const:`BOM_LE` for :const:`BOM_UTF16_LE` and :const:`BOM_BE` for + :const:`BOM_UTF16_BE`. The others represent the BOM in UTF-8 and UTF-32 + encodings. + + +.. _codec-base-classes: + +Codec Base Classes +------------------ + +The :mod:`codecs` module defines a set of base classes which define the +interfaces for working with codec objects, and can also be used as the basis +for custom codec implementations. + +Each codec has to define four interfaces to make it usable as codec in Python: +stateless encoder, stateless decoder, stream reader and stream writer. The +stream reader and writers typically reuse the stateless encoder/decoder to +implement the file protocols. Codec authors also need to define how the +codec will handle encoding and decoding errors. + + +.. _surrogateescape: +.. _error-handlers: + +Error Handlers +^^^^^^^^^^^^^^ + +To simplify and standardize error handling, +codecs may implement different error handling schemes by +accepting the *errors* string argument. The following string values are +defined and implemented by all standard Python codecs: + +.. tabularcolumns:: |l|L| + ++-------------------------+-----------------------------------------------+ +| Value | Meaning | ++=========================+===============================================+ +| ``'strict'`` | Raise :exc:`UnicodeError` (or a subclass); | +| | this is the default. Implemented in | +| | :func:`strict_errors`. | ++-------------------------+-----------------------------------------------+ +| ``'ignore'`` | Ignore the malformed data and continue | +| | without further notice. Implemented in | +| | :func:`ignore_errors`. | ++-------------------------+-----------------------------------------------+ + +The following error handlers are only applicable to +:term:`text encodings `: + +.. index:: + single: ? (question mark); replacement character + single: \ (backslash); escape sequence + single: \x; escape sequence + single: \u; escape sequence + single: \U; escape sequence + single: \N; escape sequence + ++-------------------------+-----------------------------------------------+ +| Value | Meaning | ++=========================+===============================================+ +| ``'replace'`` | Replace with a suitable replacement | +| | marker; Python will use the official | +| | ``U+FFFD`` REPLACEMENT CHARACTER for the | +| | built-in codecs on decoding, and '?' on | +| | encoding. Implemented in | +| | :func:`replace_errors`. | ++-------------------------+-----------------------------------------------+ +| ``'xmlcharrefreplace'`` | Replace with the appropriate XML character | +| | reference (only for encoding). Implemented | +| | in :func:`xmlcharrefreplace_errors`. | ++-------------------------+-----------------------------------------------+ +| ``'backslashreplace'`` | Replace with backslashed escape sequences. | +| | Implemented in | +| | :func:`backslashreplace_errors`. | ++-------------------------+-----------------------------------------------+ +| ``'namereplace'`` | Replace with ``\N{...}`` escape sequences | +| | (only for encoding). Implemented in | +| | :func:`namereplace_errors`. | ++-------------------------+-----------------------------------------------+ +| ``'surrogateescape'`` | On decoding, replace byte with individual | +| | surrogate code ranging from ``U+DC80`` to | +| | ``U+DCFF``. This code will then be turned | +| | back into the same byte when the | +| | ``'surrogateescape'`` error handler is used | +| | when encoding the data. (See :pep:`383` for | +| | more.) | ++-------------------------+-----------------------------------------------+ + +In addition, the following error handler is specific to the given codecs: + ++-------------------+------------------------+-------------------------------------------+ +| Value | Codecs | Meaning | ++===================+========================+===========================================+ +|``'surrogatepass'``| utf-8, utf-16, utf-32, | Allow encoding and decoding of surrogate | +| | utf-16-be, utf-16-le, | codes. These codecs normally treat the | +| | utf-32-be, utf-32-le | presence of surrogates as an error. | ++-------------------+------------------------+-------------------------------------------+ + +.. versionadded:: 3.1 + The ``'surrogateescape'`` and ``'surrogatepass'`` error handlers. + +.. versionchanged:: 3.4 + The ``'surrogatepass'`` error handlers now works with utf-16\* and utf-32\* codecs. + +.. versionadded:: 3.5 + The ``'namereplace'`` error handler. + +.. versionchanged:: 3.5 + The ``'backslashreplace'`` error handlers now works with decoding and + translating. + +The set of allowed values can be extended by registering a new named error +handler: + +.. function:: register_error(name, error_handler) + + Register the error handling function *error_handler* under the name *name*. + The *error_handler* argument will be called during encoding and decoding + in case of an error, when *name* is specified as the errors parameter. + + For encoding, *error_handler* will be called with a :exc:`UnicodeEncodeError` + instance, which contains information about the location of the error. The + error handler must either raise this or a different exception, or return a + tuple with a replacement for the unencodable part of the input and a position + where encoding should continue. The replacement may be either :class:`str` or + :class:`bytes`. If the replacement is bytes, the encoder will simply copy + them into the output buffer. If the replacement is a string, the encoder will + encode the replacement. Encoding continues on original input at the + specified position. Negative position values will be treated as being + relative to the end of the input string. If the resulting position is out of + bound an :exc:`IndexError` will be raised. + + Decoding and translating works similarly, except :exc:`UnicodeDecodeError` or + :exc:`UnicodeTranslateError` will be passed to the handler and that the + replacement from the error handler will be put into the output directly. + + +Previously registered error handlers (including the standard error handlers) +can be looked up by name: + +.. function:: lookup_error(name) + + Return the error handler previously registered under the name *name*. + + Raises a :exc:`LookupError` in case the handler cannot be found. + +The following standard error handlers are also made available as module level +functions: + +.. function:: strict_errors(exception) + + Implements the ``'strict'`` error handling: each encoding or + decoding error raises a :exc:`UnicodeError`. + + +.. function:: replace_errors(exception) + + Implements the ``'replace'`` error handling (for :term:`text encodings + ` only): substitutes ``'?'`` for encoding errors + (to be encoded by the codec), and ``'\ufffd'`` (the Unicode replacement + character) for decoding errors. + + +.. function:: ignore_errors(exception) + + Implements the ``'ignore'`` error handling: malformed data is ignored and + encoding or decoding is continued without further notice. + + +.. function:: xmlcharrefreplace_errors(exception) + + Implements the ``'xmlcharrefreplace'`` error handling (for encoding with + :term:`text encodings ` only): the + unencodable character is replaced by an appropriate XML character reference. + + +.. function:: backslashreplace_errors(exception) + + Implements the ``'backslashreplace'`` error handling (for + :term:`text encodings ` only): malformed data is + replaced by a backslashed escape sequence. + +.. function:: namereplace_errors(exception) + + Implements the ``'namereplace'`` error handling (for encoding with + :term:`text encodings ` only): the + unencodable character is replaced by a ``\N{...}`` escape sequence. + + .. versionadded:: 3.5 + + +.. _codec-objects: + +Stateless Encoding and Decoding +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The base :class:`Codec` class defines these methods which also define the +function interfaces of the stateless encoder and decoder: + + +.. method:: Codec.encode(input[, errors]) + + Encodes the object *input* and returns a tuple (output object, length consumed). + For instance, :term:`text encoding` converts + a string object to a bytes object using a particular + character set encoding (e.g., ``cp1252`` or ``iso-8859-1``). + + The *errors* argument defines the error handling to apply. + It defaults to ``'strict'`` handling. + + The method may not store state in the :class:`Codec` instance. Use + :class:`StreamWriter` for codecs which have to keep state in order to make + encoding efficient. + + The encoder must be able to handle zero length input and return an empty object + of the output object type in this situation. + + +.. method:: Codec.decode(input[, errors]) + + Decodes the object *input* and returns a tuple (output object, length + consumed). For instance, for a :term:`text encoding`, decoding converts + a bytes object encoded using a particular + character set encoding to a string object. + + For text encodings and bytes-to-bytes codecs, + *input* must be a bytes object or one which provides the read-only + buffer interface -- for example, buffer objects and memory mapped files. + + The *errors* argument defines the error handling to apply. + It defaults to ``'strict'`` handling. + + The method may not store state in the :class:`Codec` instance. Use + :class:`StreamReader` for codecs which have to keep state in order to make + decoding efficient. + + The decoder must be able to handle zero length input and return an empty object + of the output object type in this situation. + + +Incremental Encoding and Decoding +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The :class:`IncrementalEncoder` and :class:`IncrementalDecoder` classes provide +the basic interface for incremental encoding and decoding. Encoding/decoding the +input isn't done with one call to the stateless encoder/decoder function, but +with multiple calls to the +:meth:`~IncrementalEncoder.encode`/:meth:`~IncrementalDecoder.decode` method of +the incremental encoder/decoder. The incremental encoder/decoder keeps track of +the encoding/decoding process during method calls. + +The joined output of calls to the +:meth:`~IncrementalEncoder.encode`/:meth:`~IncrementalDecoder.decode` method is +the same as if all the single inputs were joined into one, and this input was +encoded/decoded with the stateless encoder/decoder. + + +.. _incremental-encoder-objects: + +IncrementalEncoder Objects +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The :class:`IncrementalEncoder` class is used for encoding an input in multiple +steps. It defines the following methods which every incremental encoder must +define in order to be compatible with the Python codec registry. + + +.. class:: IncrementalEncoder(errors='strict') + + Constructor for an :class:`IncrementalEncoder` instance. + + All incremental encoders must provide this constructor interface. They are free + to add additional keyword arguments, but only the ones defined here are used by + the Python codec registry. + + The :class:`IncrementalEncoder` may implement different error handling schemes + by providing the *errors* keyword argument. See :ref:`error-handlers` for + possible values. + + The *errors* argument will be assigned to an attribute of the same name. + Assigning to this attribute makes it possible to switch between different error + handling strategies during the lifetime of the :class:`IncrementalEncoder` + object. + + + .. method:: encode(object[, final]) + + Encodes *object* (taking the current state of the encoder into account) + and returns the resulting encoded object. If this is the last call to + :meth:`encode` *final* must be true (the default is false). + + + .. method:: reset() + + Reset the encoder to the initial state. The output is discarded: call + ``.encode(object, final=True)``, passing an empty byte or text string + if necessary, to reset the encoder and to get the output. + + + .. method:: getstate() + + Return the current state of the encoder which must be an integer. The + implementation should make sure that ``0`` is the most common + state. (States that are more complicated than integers can be converted + into an integer by marshaling/pickling the state and encoding the bytes + of the resulting string into an integer.) + + + .. method:: setstate(state) + + Set the state of the encoder to *state*. *state* must be an encoder state + returned by :meth:`getstate`. + + +.. _incremental-decoder-objects: + +IncrementalDecoder Objects +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The :class:`IncrementalDecoder` class is used for decoding an input in multiple +steps. It defines the following methods which every incremental decoder must +define in order to be compatible with the Python codec registry. + + +.. class:: IncrementalDecoder(errors='strict') + + Constructor for an :class:`IncrementalDecoder` instance. + + All incremental decoders must provide this constructor interface. They are free + to add additional keyword arguments, but only the ones defined here are used by + the Python codec registry. + + The :class:`IncrementalDecoder` may implement different error handling schemes + by providing the *errors* keyword argument. See :ref:`error-handlers` for + possible values. + + The *errors* argument will be assigned to an attribute of the same name. + Assigning to this attribute makes it possible to switch between different error + handling strategies during the lifetime of the :class:`IncrementalDecoder` + object. + + + .. method:: decode(object[, final]) + + Decodes *object* (taking the current state of the decoder into account) + and returns the resulting decoded object. If this is the last call to + :meth:`decode` *final* must be true (the default is false). If *final* is + true the decoder must decode the input completely and must flush all + buffers. If this isn't possible (e.g. because of incomplete byte sequences + at the end of the input) it must initiate error handling just like in the + stateless case (which might raise an exception). + + + .. method:: reset() + + Reset the decoder to the initial state. + + + .. method:: getstate() + + Return the current state of the decoder. This must be a tuple with two + items, the first must be the buffer containing the still undecoded + input. The second must be an integer and can be additional state + info. (The implementation should make sure that ``0`` is the most common + additional state info.) If this additional state info is ``0`` it must be + possible to set the decoder to the state which has no input buffered and + ``0`` as the additional state info, so that feeding the previously + buffered input to the decoder returns it to the previous state without + producing any output. (Additional state info that is more complicated than + integers can be converted into an integer by marshaling/pickling the info + and encoding the bytes of the resulting string into an integer.) + + + .. method:: setstate(state) + + Set the state of the decoder to *state*. *state* must be a decoder state + returned by :meth:`getstate`. + + +Stream Encoding and Decoding +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + +The :class:`StreamWriter` and :class:`StreamReader` classes provide generic +working interfaces which can be used to implement new encoding submodules very +easily. See :mod:`encodings.utf_8` for an example of how this is done. + + +.. _stream-writer-objects: + +StreamWriter Objects +~~~~~~~~~~~~~~~~~~~~ + +The :class:`StreamWriter` class is a subclass of :class:`Codec` and defines the +following methods which every stream writer must define in order to be +compatible with the Python codec registry. + + +.. class:: StreamWriter(stream, errors='strict') + + Constructor for a :class:`StreamWriter` instance. + + All stream writers must provide this constructor interface. They are free to add + additional keyword arguments, but only the ones defined here are used by the + Python codec registry. + + The *stream* argument must be a file-like object open for writing + text or binary data, as appropriate for the specific codec. + + The :class:`StreamWriter` may implement different error handling schemes by + providing the *errors* keyword argument. See :ref:`error-handlers` for + the standard error handlers the underlying stream codec may support. + + The *errors* argument will be assigned to an attribute of the same name. + Assigning to this attribute makes it possible to switch between different error + handling strategies during the lifetime of the :class:`StreamWriter` object. + + .. method:: write(object) + + Writes the object's contents encoded to the stream. + + + .. method:: writelines(list) + + Writes the concatenated list of strings to the stream (possibly by reusing + the :meth:`write` method). The standard bytes-to-bytes codecs + do not support this method. + + + .. method:: reset() + + Flushes and resets the codec buffers used for keeping state. + + Calling this method should ensure that the data on the output is put into + a clean state that allows appending of new fresh data without having to + rescan the whole stream to recover state. + + +In addition to the above methods, the :class:`StreamWriter` must also inherit +all other methods and attributes from the underlying stream. + + +.. _stream-reader-objects: + +StreamReader Objects +~~~~~~~~~~~~~~~~~~~~ + +The :class:`StreamReader` class is a subclass of :class:`Codec` and defines the +following methods which every stream reader must define in order to be +compatible with the Python codec registry. + + +.. class:: StreamReader(stream, errors='strict') + + Constructor for a :class:`StreamReader` instance. + + All stream readers must provide this constructor interface. They are free to add + additional keyword arguments, but only the ones defined here are used by the + Python codec registry. + + The *stream* argument must be a file-like object open for reading + text or binary data, as appropriate for the specific codec. + + The :class:`StreamReader` may implement different error handling schemes by + providing the *errors* keyword argument. See :ref:`error-handlers` for + the standard error handlers the underlying stream codec may support. + + The *errors* argument will be assigned to an attribute of the same name. + Assigning to this attribute makes it possible to switch between different error + handling strategies during the lifetime of the :class:`StreamReader` object. + + The set of allowed values for the *errors* argument can be extended with + :func:`register_error`. + + + .. method:: read([size[, chars, [firstline]]]) + + Decodes data from the stream and returns the resulting object. + + The *chars* argument indicates the number of decoded + code points or bytes to return. The :func:`read` method will + never return more data than requested, but it might return less, + if there is not enough available. + + The *size* argument indicates the approximate maximum + number of encoded bytes or code points to read + for decoding. The decoder can modify this setting as + appropriate. The default value -1 indicates to read and decode as much as + possible. This parameter is intended to + prevent having to decode huge files in one step. + + The *firstline* flag indicates that + it would be sufficient to only return the first + line, if there are decoding errors on later lines. + + The method should use a greedy read strategy meaning that it should read + as much data as is allowed within the definition of the encoding and the + given size, e.g. if optional encoding endings or state markers are + available on the stream, these should be read too. + + + .. method:: readline([size[, keepends]]) + + Read one line from the input stream and return the decoded data. + + *size*, if given, is passed as size argument to the stream's + :meth:`read` method. + + If *keepends* is false line-endings will be stripped from the lines + returned. + + + .. method:: readlines([sizehint[, keepends]]) + + Read all lines available on the input stream and return them as a list of + lines. + + Line-endings are implemented using the codec's :meth:`decode` method and + are included in the list entries if *keepends* is true. + + *sizehint*, if given, is passed as the *size* argument to the stream's + :meth:`read` method. + + + .. method:: reset() + + Resets the codec buffers used for keeping state. + + Note that no stream repositioning should take place. This method is + primarily intended to be able to recover from decoding errors. + + +In addition to the above methods, the :class:`StreamReader` must also inherit +all other methods and attributes from the underlying stream. + +.. _stream-reader-writer: + +StreamReaderWriter Objects +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The :class:`StreamReaderWriter` is a convenience class that allows wrapping +streams which work in both read and write modes. + +The design is such that one can use the factory functions returned by the +:func:`lookup` function to construct the instance. + + +.. class:: StreamReaderWriter(stream, Reader, Writer, errors='strict') + + Creates a :class:`StreamReaderWriter` instance. *stream* must be a file-like + object. *Reader* and *Writer* must be factory functions or classes providing the + :class:`StreamReader` and :class:`StreamWriter` interface resp. Error handling + is done in the same way as defined for the stream readers and writers. + +:class:`StreamReaderWriter` instances define the combined interfaces of +:class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other +methods and attributes from the underlying stream. + + +.. _stream-recoder-objects: + +StreamRecoder Objects +~~~~~~~~~~~~~~~~~~~~~ + +The :class:`StreamRecoder` translates data from one encoding to another, +which is sometimes useful when dealing with different encoding environments. + +The design is such that one can use the factory functions returned by the +:func:`lookup` function to construct the instance. + + +.. class:: StreamRecoder(stream, encode, decode, Reader, Writer, errors='strict') + + Creates a :class:`StreamRecoder` instance which implements a two-way conversion: + *encode* and *decode* work on the frontend — the data visible to + code calling :meth:`read` and :meth:`write`, while *Reader* and *Writer* + work on the backend — the data in *stream*. + + You can use these objects to do transparent transcodings, e.g., from Latin-1 + to UTF-8 and back. + + The *stream* argument must be a file-like object. + + The *encode* and *decode* arguments must + adhere to the :class:`Codec` interface. *Reader* and + *Writer* must be factory functions or classes providing objects of the + :class:`StreamReader` and :class:`StreamWriter` interface respectively. + + Error handling is done in the same way as defined for the stream readers and + writers. + + +:class:`StreamRecoder` instances define the combined interfaces of +:class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other +methods and attributes from the underlying stream. + + +.. _encodings-overview: + +Encodings and Unicode +--------------------- + +Strings are stored internally as sequences of code points in +range ``0x0``--``0x10FFFF``. (See :pep:`393` for +more details about the implementation.) +Once a string object is used outside of CPU and memory, endianness +and how these arrays are stored as bytes become an issue. As with other +codecs, serialising a string into a sequence of bytes is known as *encoding*, +and recreating the string from the sequence of bytes is known as *decoding*. +There are a variety of different text serialisation codecs, which are +collectivity referred to as :term:`text encodings `. + +The simplest text encoding (called ``'latin-1'`` or ``'iso-8859-1'``) maps +the code points 0--255 to the bytes ``0x0``--``0xff``, which means that a string +object that contains code points above ``U+00FF`` can't be encoded with this +codec. Doing so will raise a :exc:`UnicodeEncodeError` that looks +like the following (although the details of the error message may differ): +``UnicodeEncodeError: 'latin-1' codec can't encode character '\u1234' in +position 3: ordinal not in range(256)``. + +There's another group of encodings (the so called charmap encodings) that choose +a different subset of all Unicode code points and how these code points are +mapped to the bytes ``0x0``--``0xff``. To see how this is done simply open +e.g. :file:`encodings/cp1252.py` (which is an encoding that is used primarily on +Windows). There's a string constant with 256 characters that shows you which +character is mapped to which byte value. + +All of these encodings can only encode 256 of the 1114112 code points +defined in Unicode. A simple and straightforward way that can store each Unicode +code point, is to store each code point as four consecutive bytes. There are two +possibilities: store the bytes in big endian or in little endian order. These +two encodings are called ``UTF-32-BE`` and ``UTF-32-LE`` respectively. Their +disadvantage is that if e.g. you use ``UTF-32-BE`` on a little endian machine you +will always have to swap bytes on encoding and decoding. ``UTF-32`` avoids this +problem: bytes will always be in natural endianness. When these bytes are read +by a CPU with a different endianness, then bytes have to be swapped though. To +be able to detect the endianness of a ``UTF-16`` or ``UTF-32`` byte sequence, +there's the so called BOM ("Byte Order Mark"). This is the Unicode character +``U+FEFF``. This character can be prepended to every ``UTF-16`` or ``UTF-32`` +byte sequence. The byte swapped version of this character (``0xFFFE``) is an +illegal character that may not appear in a Unicode text. So when the +first character in an ``UTF-16`` or ``UTF-32`` byte sequence +appears to be a ``U+FFFE`` the bytes have to be swapped on decoding. +Unfortunately the character ``U+FEFF`` had a second purpose as +a ``ZERO WIDTH NO-BREAK SPACE``: a character that has no width and doesn't allow +a word to be split. It can e.g. be used to give hints to a ligature algorithm. +With Unicode 4.0 using ``U+FEFF`` as a ``ZERO WIDTH NO-BREAK SPACE`` has been +deprecated (with ``U+2060`` (``WORD JOINER``) assuming this role). Nevertheless +Unicode software still must be able to handle ``U+FEFF`` in both roles: as a BOM +it's a device to determine the storage layout of the encoded bytes, and vanishes +once the byte sequence has been decoded into a string; as a ``ZERO WIDTH +NO-BREAK SPACE`` it's a normal character that will be decoded like any other. + +There's another encoding that is able to encoding the full range of Unicode +characters: UTF-8. UTF-8 is an 8-bit encoding, which means there are no issues +with byte order in UTF-8. Each byte in a UTF-8 byte sequence consists of two +parts: marker bits (the most significant bits) and payload bits. The marker bits +are a sequence of zero to four ``1`` bits followed by a ``0`` bit. Unicode characters are +encoded like this (with x being payload bits, which when concatenated give the +Unicode character): + ++-----------------------------------+----------------------------------------------+ +| Range | Encoding | ++===================================+==============================================+ +| ``U-00000000`` ... ``U-0000007F`` | 0xxxxxxx | ++-----------------------------------+----------------------------------------------+ +| ``U-00000080`` ... ``U-000007FF`` | 110xxxxx 10xxxxxx | ++-----------------------------------+----------------------------------------------+ +| ``U-00000800`` ... ``U-0000FFFF`` | 1110xxxx 10xxxxxx 10xxxxxx | ++-----------------------------------+----------------------------------------------+ +| ``U-00010000`` ... ``U-0010FFFF`` | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx | ++-----------------------------------+----------------------------------------------+ + +The least significant bit of the Unicode character is the rightmost x bit. + +As UTF-8 is an 8-bit encoding no BOM is required and any ``U+FEFF`` character in +the decoded string (even if it's the first character) is treated as a ``ZERO +WIDTH NO-BREAK SPACE``. + +Without external information it's impossible to reliably determine which +encoding was used for encoding a string. Each charmap encoding can +decode any random byte sequence. However that's not possible with UTF-8, as +UTF-8 byte sequences have a structure that doesn't allow arbitrary byte +sequences. To increase the reliability with which a UTF-8 encoding can be +detected, Microsoft invented a variant of UTF-8 (that Python 2.5 calls +``"utf-8-sig"``) for its Notepad program: Before any of the Unicode characters +is written to the file, a UTF-8 encoded BOM (which looks like this as a byte +sequence: ``0xef``, ``0xbb``, ``0xbf``) is written. As it's rather improbable +that any charmap encoded file starts with these byte values (which would e.g. +map to + + | LATIN SMALL LETTER I WITH DIAERESIS + | RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK + | INVERTED QUESTION MARK + +in iso-8859-1), this increases the probability that a ``utf-8-sig`` encoding can be +correctly guessed from the byte sequence. So here the BOM is not used to be able +to determine the byte order used for generating the byte sequence, but as a +signature that helps in guessing the encoding. On encoding the utf-8-sig codec +will write ``0xef``, ``0xbb``, ``0xbf`` as the first three bytes to the file. On +decoding ``utf-8-sig`` will skip those three bytes if they appear as the first +three bytes in the file. In UTF-8, the use of the BOM is discouraged and +should generally be avoided. + + +.. _standard-encodings: + +Standard Encodings +------------------ + +Python comes with a number of codecs built-in, either implemented as C functions +or with dictionaries as mapping tables. The following table lists the codecs by +name, together with a few common aliases, and the languages for which the +encoding is likely used. Neither the list of aliases nor the list of languages +is meant to be exhaustive. Notice that spelling alternatives that only differ in +case or use a hyphen instead of an underscore are also valid aliases; therefore, +e.g. ``'utf-8'`` is a valid alias for the ``'utf_8'`` codec. + +.. impl-detail:: + + Some common encodings can bypass the codecs lookup machinery to + improve performance. These optimization opportunities are only + recognized by CPython for a limited set of (case insensitive) + aliases: utf-8, utf8, latin-1, latin1, iso-8859-1, iso8859-1, mbcs + (Windows only), ascii, us-ascii, utf-16, utf16, utf-32, utf32, and + the same using underscores instead of dashes. Using alternative + aliases for these encodings may result in slower execution. + + .. versionchanged:: 3.6 + Optimization opportunity recognized for us-ascii. + +Many of the character sets support the same languages. They vary in individual +characters (e.g. whether the EURO SIGN is supported or not), and in the +assignment of characters to code positions. For the European languages in +particular, the following variants typically exist: + +* an ISO 8859 codeset + +* a Microsoft Windows code page, which is typically derived from an 8859 codeset, + but replaces control characters with additional graphic characters + +* an IBM EBCDIC code page + +* an IBM PC code page, which is ASCII compatible + +.. tabularcolumns:: |l|p{0.3\linewidth}|p{0.3\linewidth}| + ++-----------------+--------------------------------+--------------------------------+ +| Codec | Aliases | Languages | ++=================+================================+================================+ +| ascii | 646, us-ascii | English | ++-----------------+--------------------------------+--------------------------------+ +| big5 | big5-tw, csbig5 | Traditional Chinese | ++-----------------+--------------------------------+--------------------------------+ +| big5hkscs | big5-hkscs, hkscs | Traditional Chinese | ++-----------------+--------------------------------+--------------------------------+ +| cp037 | IBM037, IBM039 | English | ++-----------------+--------------------------------+--------------------------------+ +| cp273 | 273, IBM273, csIBM273 | German | +| | | | +| | | .. versionadded:: 3.4 | ++-----------------+--------------------------------+--------------------------------+ +| cp424 | EBCDIC-CP-HE, IBM424 | Hebrew | ++-----------------+--------------------------------+--------------------------------+ +| cp437 | 437, IBM437 | English | ++-----------------+--------------------------------+--------------------------------+ +| cp500 | EBCDIC-CP-BE, EBCDIC-CP-CH, | Western Europe | +| | IBM500 | | ++-----------------+--------------------------------+--------------------------------+ +| cp720 | | Arabic | ++-----------------+--------------------------------+--------------------------------+ +| cp737 | | Greek | ++-----------------+--------------------------------+--------------------------------+ +| cp775 | IBM775 | Baltic languages | ++-----------------+--------------------------------+--------------------------------+ +| cp850 | 850, IBM850 | Western Europe | ++-----------------+--------------------------------+--------------------------------+ +| cp852 | 852, IBM852 | Central and Eastern Europe | ++-----------------+--------------------------------+--------------------------------+ +| cp855 | 855, IBM855 | Bulgarian, Byelorussian, | +| | | Macedonian, Russian, Serbian | ++-----------------+--------------------------------+--------------------------------+ +| cp856 | | Hebrew | ++-----------------+--------------------------------+--------------------------------+ +| cp857 | 857, IBM857 | Turkish | ++-----------------+--------------------------------+--------------------------------+ +| cp858 | 858, IBM858 | Western Europe | ++-----------------+--------------------------------+--------------------------------+ +| cp860 | 860, IBM860 | Portuguese | ++-----------------+--------------------------------+--------------------------------+ +| cp861 | 861, CP-IS, IBM861 | Icelandic | ++-----------------+--------------------------------+--------------------------------+ +| cp862 | 862, IBM862 | Hebrew | ++-----------------+--------------------------------+--------------------------------+ +| cp863 | 863, IBM863 | Canadian | ++-----------------+--------------------------------+--------------------------------+ +| cp864 | IBM864 | Arabic | ++-----------------+--------------------------------+--------------------------------+ +| cp865 | 865, IBM865 | Danish, Norwegian | ++-----------------+--------------------------------+--------------------------------+ +| cp866 | 866, IBM866 | Russian | ++-----------------+--------------------------------+--------------------------------+ +| cp869 | 869, CP-GR, IBM869 | Greek | ++-----------------+--------------------------------+--------------------------------+ +| cp874 | | Thai | ++-----------------+--------------------------------+--------------------------------+ +| cp875 | | Greek | ++-----------------+--------------------------------+--------------------------------+ +| cp932 | 932, ms932, mskanji, ms-kanji | Japanese | ++-----------------+--------------------------------+--------------------------------+ +| cp949 | 949, ms949, uhc | Korean | ++-----------------+--------------------------------+--------------------------------+ +| cp950 | 950, ms950 | Traditional Chinese | ++-----------------+--------------------------------+--------------------------------+ +| cp1006 | | Urdu | ++-----------------+--------------------------------+--------------------------------+ +| cp1026 | ibm1026 | Turkish | ++-----------------+--------------------------------+--------------------------------+ +| cp1125 | 1125, ibm1125, cp866u, ruscii | Ukrainian | +| | | | +| | | .. versionadded:: 3.4 | ++-----------------+--------------------------------+--------------------------------+ +| cp1140 | ibm1140 | Western Europe | ++-----------------+--------------------------------+--------------------------------+ +| cp1250 | windows-1250 | Central and Eastern Europe | ++-----------------+--------------------------------+--------------------------------+ +| cp1251 | windows-1251 | Bulgarian, Byelorussian, | +| | | Macedonian, Russian, Serbian | ++-----------------+--------------------------------+--------------------------------+ +| cp1252 | windows-1252 | Western Europe | ++-----------------+--------------------------------+--------------------------------+ +| cp1253 | windows-1253 | Greek | ++-----------------+--------------------------------+--------------------------------+ +| cp1254 | windows-1254 | Turkish | ++-----------------+--------------------------------+--------------------------------+ +| cp1255 | windows-1255 | Hebrew | ++-----------------+--------------------------------+--------------------------------+ +| cp1256 | windows-1256 | Arabic | ++-----------------+--------------------------------+--------------------------------+ +| cp1257 | windows-1257 | Baltic languages | ++-----------------+--------------------------------+--------------------------------+ +| cp1258 | windows-1258 | Vietnamese | ++-----------------+--------------------------------+--------------------------------+ +| euc_jp | eucjp, ujis, u-jis | Japanese | ++-----------------+--------------------------------+--------------------------------+ +| euc_jis_2004 | jisx0213, eucjis2004 | Japanese | ++-----------------+--------------------------------+--------------------------------+ +| euc_jisx0213 | eucjisx0213 | Japanese | ++-----------------+--------------------------------+--------------------------------+ +| euc_kr | euckr, korean, ksc5601, | Korean | +| | ks_c-5601, ks_c-5601-1987, | | +| | ksx1001, ks_x-1001 | | ++-----------------+--------------------------------+--------------------------------+ +| gb2312 | chinese, csiso58gb231280, | Simplified Chinese | +| | euc-cn, euccn, eucgb2312-cn, | | +| | gb2312-1980, gb2312-80, | | +| | iso-ir-58 | | ++-----------------+--------------------------------+--------------------------------+ +| gbk | 936, cp936, ms936 | Unified Chinese | ++-----------------+--------------------------------+--------------------------------+ +| gb18030 | gb18030-2000 | Unified Chinese | ++-----------------+--------------------------------+--------------------------------+ +| hz | hzgb, hz-gb, hz-gb-2312 | Simplified Chinese | ++-----------------+--------------------------------+--------------------------------+ +| iso2022_jp | csiso2022jp, iso2022jp, | Japanese | +| | iso-2022-jp | | ++-----------------+--------------------------------+--------------------------------+ +| iso2022_jp_1 | iso2022jp-1, iso-2022-jp-1 | Japanese | ++-----------------+--------------------------------+--------------------------------+ +| iso2022_jp_2 | iso2022jp-2, iso-2022-jp-2 | Japanese, Korean, Simplified | +| | | Chinese, Western Europe, Greek | ++-----------------+--------------------------------+--------------------------------+ +| iso2022_jp_2004 | iso2022jp-2004, | Japanese | +| | iso-2022-jp-2004 | | ++-----------------+--------------------------------+--------------------------------+ +| iso2022_jp_3 | iso2022jp-3, iso-2022-jp-3 | Japanese | ++-----------------+--------------------------------+--------------------------------+ +| iso2022_jp_ext | iso2022jp-ext, iso-2022-jp-ext | Japanese | ++-----------------+--------------------------------+--------------------------------+ +| iso2022_kr | csiso2022kr, iso2022kr, | Korean | +| | iso-2022-kr | | ++-----------------+--------------------------------+--------------------------------+ +| latin_1 | iso-8859-1, iso8859-1, 8859, | Western Europe | +| | cp819, latin, latin1, L1 | | ++-----------------+--------------------------------+--------------------------------+ +| iso8859_2 | iso-8859-2, latin2, L2 | Central and Eastern Europe | ++-----------------+--------------------------------+--------------------------------+ +| iso8859_3 | iso-8859-3, latin3, L3 | Esperanto, Maltese | ++-----------------+--------------------------------+--------------------------------+ +| iso8859_4 | iso-8859-4, latin4, L4 | Baltic languages | ++-----------------+--------------------------------+--------------------------------+ +| iso8859_5 | iso-8859-5, cyrillic | Bulgarian, Byelorussian, | +| | | Macedonian, Russian, Serbian | ++-----------------+--------------------------------+--------------------------------+ +| iso8859_6 | iso-8859-6, arabic | Arabic | ++-----------------+--------------------------------+--------------------------------+ +| iso8859_7 | iso-8859-7, greek, greek8 | Greek | ++-----------------+--------------------------------+--------------------------------+ +| iso8859_8 | iso-8859-8, hebrew | Hebrew | ++-----------------+--------------------------------+--------------------------------+ +| iso8859_9 | iso-8859-9, latin5, L5 | Turkish | ++-----------------+--------------------------------+--------------------------------+ +| iso8859_10 | iso-8859-10, latin6, L6 | Nordic languages | ++-----------------+--------------------------------+--------------------------------+ +| iso8859_11 | iso-8859-11, thai | Thai languages | ++-----------------+--------------------------------+--------------------------------+ +| iso8859_13 | iso-8859-13, latin7, L7 | Baltic languages | ++-----------------+--------------------------------+--------------------------------+ +| iso8859_14 | iso-8859-14, latin8, L8 | Celtic languages | ++-----------------+--------------------------------+--------------------------------+ +| iso8859_15 | iso-8859-15, latin9, L9 | Western Europe | ++-----------------+--------------------------------+--------------------------------+ +| iso8859_16 | iso-8859-16, latin10, L10 | South-Eastern Europe | ++-----------------+--------------------------------+--------------------------------+ +| johab | cp1361, ms1361 | Korean | ++-----------------+--------------------------------+--------------------------------+ +| koi8_r | | Russian | ++-----------------+--------------------------------+--------------------------------+ +| koi8_t | | Tajik | +| | | | +| | | .. versionadded:: 3.5 | ++-----------------+--------------------------------+--------------------------------+ +| koi8_u | | Ukrainian | ++-----------------+--------------------------------+--------------------------------+ +| kz1048 | kz_1048, strk1048_2002, rk1048 | Kazakh | +| | | | +| | | .. versionadded:: 3.5 | ++-----------------+--------------------------------+--------------------------------+ +| mac_cyrillic | maccyrillic | Bulgarian, Byelorussian, | +| | | Macedonian, Russian, Serbian | ++-----------------+--------------------------------+--------------------------------+ +| mac_greek | macgreek | Greek | ++-----------------+--------------------------------+--------------------------------+ +| mac_iceland | maciceland | Icelandic | ++-----------------+--------------------------------+--------------------------------+ +| mac_latin2 | maclatin2, maccentraleurope, | Central and Eastern Europe | +| | mac_centeuro | | ++-----------------+--------------------------------+--------------------------------+ +| mac_roman | macroman, macintosh | Western Europe | ++-----------------+--------------------------------+--------------------------------+ +| mac_turkish | macturkish | Turkish | ++-----------------+--------------------------------+--------------------------------+ +| ptcp154 | csptcp154, pt154, cp154, | Kazakh | +| | cyrillic-asian | | ++-----------------+--------------------------------+--------------------------------+ +| shift_jis | csshiftjis, shiftjis, sjis, | Japanese | +| | s_jis | | ++-----------------+--------------------------------+--------------------------------+ +| shift_jis_2004 | shiftjis2004, sjis_2004, | Japanese | +| | sjis2004 | | ++-----------------+--------------------------------+--------------------------------+ +| shift_jisx0213 | shiftjisx0213, sjisx0213, | Japanese | +| | s_jisx0213 | | ++-----------------+--------------------------------+--------------------------------+ +| utf_32 | U32, utf32 | all languages | ++-----------------+--------------------------------+--------------------------------+ +| utf_32_be | UTF-32BE | all languages | ++-----------------+--------------------------------+--------------------------------+ +| utf_32_le | UTF-32LE | all languages | ++-----------------+--------------------------------+--------------------------------+ +| utf_16 | U16, utf16 | all languages | ++-----------------+--------------------------------+--------------------------------+ +| utf_16_be | UTF-16BE | all languages | ++-----------------+--------------------------------+--------------------------------+ +| utf_16_le | UTF-16LE | all languages | ++-----------------+--------------------------------+--------------------------------+ +| utf_7 | U7, unicode-1-1-utf-7 | all languages | ++-----------------+--------------------------------+--------------------------------+ +| utf_8 | U8, UTF, utf8, cp65001 | all languages | ++-----------------+--------------------------------+--------------------------------+ +| utf_8_sig | | all languages | ++-----------------+--------------------------------+--------------------------------+ + +.. versionchanged:: 3.4 + The utf-16\* and utf-32\* encoders no longer allow surrogate code points + (``U+D800``--``U+DFFF``) to be encoded. + The utf-32\* decoders no longer decode + byte sequences that correspond to surrogate code points. + +.. versionchanged:: 3.8 + ``cp65001`` is now an alias to ``utf_8``. + + +Python Specific Encodings +------------------------- + +A number of predefined codecs are specific to Python, so their codec names have +no meaning outside Python. These are listed in the tables below based on the +expected input and output types (note that while text encodings are the most +common use case for codecs, the underlying codec infrastructure supports +arbitrary data transforms rather than just text encodings). For asymmetric +codecs, the stated meaning describes the encoding direction. + +Text Encodings +^^^^^^^^^^^^^^ + +The following codecs provide :class:`str` to :class:`bytes` encoding and +:term:`bytes-like object` to :class:`str` decoding, similar to the Unicode text +encodings. + +.. tabularcolumns:: |l|p{0.3\linewidth}|p{0.3\linewidth}| + ++--------------------+---------+---------------------------+ +| Codec | Aliases | Meaning | ++====================+=========+===========================+ +| idna | | Implement :rfc:`3490`, | +| | | see also | +| | | :mod:`encodings.idna`. | +| | | Only ``errors='strict'`` | +| | | is supported. | ++--------------------+---------+---------------------------+ +| mbcs | ansi, | Windows only: Encode the | +| | dbcs | operand according to the | +| | | ANSI codepage (CP_ACP). | ++--------------------+---------+---------------------------+ +| oem | | Windows only: Encode the | +| | | operand according to the | +| | | OEM codepage (CP_OEMCP). | +| | | | +| | | .. versionadded:: 3.6 | ++--------------------+---------+---------------------------+ +| palmos | | Encoding of PalmOS 3.5. | ++--------------------+---------+---------------------------+ +| punycode | | Implement :rfc:`3492`. | +| | | Stateful codecs are not | +| | | supported. | ++--------------------+---------+---------------------------+ +| raw_unicode_escape | | Latin-1 encoding with | +| | | ``\uXXXX`` and | +| | | ``\UXXXXXXXX`` for other | +| | | code points. Existing | +| | | backslashes are not | +| | | escaped in any way. | +| | | It is used in the Python | +| | | pickle protocol. | ++--------------------+---------+---------------------------+ +| undefined | | Raise an exception for | +| | | all conversions, even | +| | | empty strings. The error | +| | | handler is ignored. | ++--------------------+---------+---------------------------+ +| unicode_escape | | Encoding suitable as the | +| | | contents of a Unicode | +| | | literal in ASCII-encoded | +| | | Python source code, | +| | | except that quotes are | +| | | not escaped. Decode | +| | | from Latin-1 source code. | +| | | Beware that Python source | +| | | code actually uses UTF-8 | +| | | by default. | ++--------------------+---------+---------------------------+ + +.. versionchanged:: 3.8 + "unicode_internal" codec is removed. + + +.. _binary-transforms: + +Binary Transforms +^^^^^^^^^^^^^^^^^ + +The following codecs provide binary transforms: :term:`bytes-like object` +to :class:`bytes` mappings. They are not supported by :meth:`bytes.decode` +(which only produces :class:`str` output). + + +.. tabularcolumns:: |l|L|L|L| + ++----------------------+------------------+------------------------------+------------------------------+ +| Codec | Aliases | Meaning | Encoder / decoder | ++======================+==================+==============================+==============================+ +| base64_codec [#b64]_ | base64, base_64 | Convert the operand to | :meth:`base64.encodebytes` / | +| | | multiline MIME base64 (the | :meth:`base64.decodebytes` | +| | | result always includes a | | +| | | trailing ``'\n'``). | | +| | | | | +| | | .. versionchanged:: 3.4 | | +| | | accepts any | | +| | | :term:`bytes-like object` | | +| | | as input for encoding and | | +| | | decoding | | ++----------------------+------------------+------------------------------+------------------------------+ +| bz2_codec | bz2 | Compress the operand using | :meth:`bz2.compress` / | +| | | bz2. | :meth:`bz2.decompress` | ++----------------------+------------------+------------------------------+------------------------------+ +| hex_codec | hex | Convert the operand to | :meth:`binascii.b2a_hex` / | +| | | hexadecimal | :meth:`binascii.a2b_hex` | +| | | representation, with two | | +| | | digits per byte. | | ++----------------------+------------------+------------------------------+------------------------------+ +| quopri_codec | quopri, | Convert the operand to MIME | :meth:`quopri.encode` with | +| | quotedprintable, | quoted printable. | ``quotetabs=True`` / | +| | quoted_printable | | :meth:`quopri.decode` | ++----------------------+------------------+------------------------------+------------------------------+ +| uu_codec | uu | Convert the operand using | :meth:`uu.encode` / | +| | | uuencode. | :meth:`uu.decode` | ++----------------------+------------------+------------------------------+------------------------------+ +| zlib_codec | zip, zlib | Compress the operand using | :meth:`zlib.compress` / | +| | | gzip. | :meth:`zlib.decompress` | ++----------------------+------------------+------------------------------+------------------------------+ + +.. [#b64] In addition to :term:`bytes-like objects `, + ``'base64_codec'`` also accepts ASCII-only instances of :class:`str` for + decoding + +.. versionadded:: 3.2 + Restoration of the binary transforms. + +.. versionchanged:: 3.4 + Restoration of the aliases for the binary transforms. + + +.. _text-transforms: + +Text Transforms +^^^^^^^^^^^^^^^ + +The following codec provides a text transform: a :class:`str` to :class:`str` +mapping. It is not supported by :meth:`str.encode` (which only produces +:class:`bytes` output). + +.. tabularcolumns:: |l|l|L| + ++--------------------+---------+---------------------------+ +| Codec | Aliases | Meaning | ++====================+=========+===========================+ +| rot_13 | rot13 | Return the Caesar-cypher | +| | | encryption of the | +| | | operand. | ++--------------------+---------+---------------------------+ + +.. versionadded:: 3.2 + Restoration of the ``rot_13`` text transform. + +.. versionchanged:: 3.4 + Restoration of the ``rot13`` alias. + + +:mod:`encodings.idna` --- Internationalized Domain Names in Applications +------------------------------------------------------------------------ + +.. module:: encodings.idna + :synopsis: Internationalized Domain Names implementation +.. moduleauthor:: Martin v. Löwis + +This module implements :rfc:`3490` (Internationalized Domain Names in +Applications) and :rfc:`3492` (Nameprep: A Stringprep Profile for +Internationalized Domain Names (IDN)). It builds upon the ``punycode`` encoding +and :mod:`stringprep`. + +These RFCs together define a protocol to support non-ASCII characters in domain +names. A domain name containing non-ASCII characters (such as +``www.Alliancefrançaise.nu``) is converted into an ASCII-compatible encoding +(ACE, such as ``www.xn--alliancefranaise-npb.nu``). The ACE form of the domain +name is then used in all places where arbitrary characters are not allowed by +the protocol, such as DNS queries, HTTP :mailheader:`Host` fields, and so +on. This conversion is carried out in the application; if possible invisible to +the user: The application should transparently convert Unicode domain labels to +IDNA on the wire, and convert back ACE labels to Unicode before presenting them +to the user. + +Python supports this conversion in several ways: the ``idna`` codec performs +conversion between Unicode and ACE, separating an input string into labels +based on the separator characters defined in :rfc:`section 3.1 of RFC 3490 <3490#section-3.1>` +and converting each label to ACE as required, and conversely separating an input +byte string into labels based on the ``.`` separator and converting any ACE +labels found into unicode. Furthermore, the :mod:`socket` module +transparently converts Unicode host names to ACE, so that applications need not +be concerned about converting host names themselves when they pass them to the +socket module. On top of that, modules that have host names as function +parameters, such as :mod:`http.client` and :mod:`ftplib`, accept Unicode host +names (:mod:`http.client` then also transparently sends an IDNA hostname in the +:mailheader:`Host` field if it sends that field at all). + +When receiving host names from the wire (such as in reverse name lookup), no +automatic conversion to Unicode is performed: applications wishing to present +such host names to the user should decode them to Unicode. + +The module :mod:`encodings.idna` also implements the nameprep procedure, which +performs certain normalizations on host names, to achieve case-insensitivity of +international domain names, and to unify similar characters. The nameprep +functions can be used directly if desired. + + +.. function:: nameprep(label) + + Return the nameprepped version of *label*. The implementation currently assumes + query strings, so ``AllowUnassigned`` is true. + + +.. function:: ToASCII(label) + + Convert a label to ASCII, as specified in :rfc:`3490`. ``UseSTD3ASCIIRules`` is + assumed to be false. + + +.. function:: ToUnicode(label) + + Convert a label to Unicode, as specified in :rfc:`3490`. + + +:mod:`encodings.mbcs` --- Windows ANSI codepage +----------------------------------------------- + +.. module:: encodings.mbcs + :synopsis: Windows ANSI codepage + +This module implements the ANSI codepage (CP_ACP). + +.. availability:: Windows only. + +.. versionchanged:: 3.3 + Support any error handler. + +.. versionchanged:: 3.2 + Before 3.2, the *errors* argument was ignored; ``'replace'`` was always used + to encode, and ``'ignore'`` to decode. + + +:mod:`encodings.utf_8_sig` --- UTF-8 codec with BOM signature +------------------------------------------------------------- + +.. module:: encodings.utf_8_sig + :synopsis: UTF-8 codec with BOM signature +.. moduleauthor:: Walter Dörwald + +This module implements a variant of the UTF-8 codec. On encoding, a UTF-8 encoded +BOM will be prepended to the UTF-8 encoded bytes. For the stateful encoder this +is only done once (on the first write to the byte stream). On decoding, an +optional UTF-8 encoded BOM at the start of the data will be skipped. diff --git a/cpython_2/environment/repo/Doc/library/codeop.rst b/cpython_2/environment/repo/Doc/library/codeop.rst new file mode 100644 index 0000000000000000000000000000000000000000..c66b9d3ec0a26d40cb99fa01daa038d97448eda0 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/codeop.rst @@ -0,0 +1,73 @@ +:mod:`codeop` --- Compile Python code +===================================== + +.. module:: codeop + :synopsis: Compile (possibly incomplete) Python code. + +.. sectionauthor:: Moshe Zadka +.. sectionauthor:: Michael Hudson + +**Source code:** :source:`Lib/codeop.py` + +-------------- + +The :mod:`codeop` module provides utilities upon which the Python +read-eval-print loop can be emulated, as is done in the :mod:`code` module. As +a result, you probably don't want to use the module directly; if you want to +include such a loop in your program you probably want to use the :mod:`code` +module instead. + +There are two parts to this job: + +#. Being able to tell if a line of input completes a Python statement: in + short, telling whether to print '``>>>``' or '``...``' next. + +#. Remembering which future statements the user has entered, so subsequent + input can be compiled with these in effect. + +The :mod:`codeop` module provides a way of doing each of these things, and a way +of doing them both. + +To do just the former: + +.. function:: compile_command(source, filename="", symbol="single") + + Tries to compile *source*, which should be a string of Python code and return a + code object if *source* is valid Python code. In that case, the filename + attribute of the code object will be *filename*, which defaults to + ``''``. Returns ``None`` if *source* is *not* valid Python code, but is a + prefix of valid Python code. + + If there is a problem with *source*, an exception will be raised. + :exc:`SyntaxError` is raised if there is invalid Python syntax, and + :exc:`OverflowError` or :exc:`ValueError` if there is an invalid literal. + + The *symbol* argument determines whether *source* is compiled as a statement + (``'single'``, the default), as a sequence of statements (``'exec'``) or + as an :term:`expression` (``'eval'``). Any other value will + cause :exc:`ValueError` to be raised. + + .. note:: + + It is possible (but not likely) that the parser stops parsing with a + successful outcome before reaching the end of the source; in this case, + trailing symbols may be ignored instead of causing an error. For example, + a backslash followed by two newlines may be followed by arbitrary garbage. + This will be fixed once the API for the parser is better. + + +.. class:: Compile() + + Instances of this class have :meth:`__call__` methods identical in signature to + the built-in function :func:`compile`, but with the difference that if the + instance compiles program text containing a :mod:`__future__` statement, the + instance 'remembers' and compiles all subsequent program texts with the + statement in force. + + +.. class:: CommandCompiler() + + Instances of this class have :meth:`__call__` methods identical in signature to + :func:`compile_command`; the difference is that if the instance compiles program + text containing a ``__future__`` statement, the instance 'remembers' and + compiles all subsequent program texts with the statement in force. diff --git a/cpython_2/environment/repo/Doc/library/collections.abc.rst b/cpython_2/environment/repo/Doc/library/collections.abc.rst new file mode 100644 index 0000000000000000000000000000000000000000..2a3fb142f7297e56d4294987f9078764ea509894 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/collections.abc.rst @@ -0,0 +1,306 @@ +:mod:`collections.abc` --- Abstract Base Classes for Containers +=============================================================== + +.. module:: collections.abc + :synopsis: Abstract base classes for containers + +.. moduleauthor:: Raymond Hettinger +.. sectionauthor:: Raymond Hettinger + +.. versionadded:: 3.3 + Formerly, this module was part of the :mod:`collections` module. + +**Source code:** :source:`Lib/_collections_abc.py` + +.. testsetup:: * + + from collections import * + import itertools + __name__ = '' + +-------------- + +This module provides :term:`abstract base classes ` that +can be used to test whether a class provides a particular interface; for +example, whether it is hashable or whether it is a mapping. + + +.. _collections-abstract-base-classes: + +Collections Abstract Base Classes +--------------------------------- + +The collections module offers the following :term:`ABCs `: + +.. tabularcolumns:: |l|L|L|L| + +========================== ====================== ======================= ==================================================== +ABC Inherits from Abstract Methods Mixin Methods +========================== ====================== ======================= ==================================================== +:class:`Container` ``__contains__`` +:class:`Hashable` ``__hash__`` +:class:`Iterable` ``__iter__`` +:class:`Iterator` :class:`Iterable` ``__next__`` ``__iter__`` +:class:`Reversible` :class:`Iterable` ``__reversed__`` +:class:`Generator` :class:`Iterator` ``send``, ``throw`` ``close``, ``__iter__``, ``__next__`` +:class:`Sized` ``__len__`` +:class:`Callable` ``__call__`` +:class:`Collection` :class:`Sized`, ``__contains__``, + :class:`Iterable`, ``__iter__``, + :class:`Container` ``__len__`` + +:class:`Sequence` :class:`Reversible`, ``__getitem__``, ``__contains__``, ``__iter__``, ``__reversed__``, + :class:`Collection` ``__len__`` ``index``, and ``count`` + +:class:`MutableSequence` :class:`Sequence` ``__getitem__``, Inherited :class:`Sequence` methods and + ``__setitem__``, ``append``, ``reverse``, ``extend``, ``pop``, + ``__delitem__``, ``remove``, and ``__iadd__`` + ``__len__``, + ``insert`` + +:class:`ByteString` :class:`Sequence` ``__getitem__``, Inherited :class:`Sequence` methods + ``__len__`` + +:class:`Set` :class:`Collection` ``__contains__``, ``__le__``, ``__lt__``, ``__eq__``, ``__ne__``, + ``__iter__``, ``__gt__``, ``__ge__``, ``__and__``, ``__or__``, + ``__len__`` ``__sub__``, ``__xor__``, and ``isdisjoint`` + +:class:`MutableSet` :class:`Set` ``__contains__``, Inherited :class:`Set` methods and + ``__iter__``, ``clear``, ``pop``, ``remove``, ``__ior__``, + ``__len__``, ``__iand__``, ``__ixor__``, and ``__isub__`` + ``add``, + ``discard`` + +:class:`Mapping` :class:`Collection` ``__getitem__``, ``__contains__``, ``keys``, ``items``, ``values``, + ``__iter__``, ``get``, ``__eq__``, and ``__ne__`` + ``__len__`` + +:class:`MutableMapping` :class:`Mapping` ``__getitem__``, Inherited :class:`Mapping` methods and + ``__setitem__``, ``pop``, ``popitem``, ``clear``, ``update``, + ``__delitem__``, and ``setdefault`` + ``__iter__``, + ``__len__`` + + +:class:`MappingView` :class:`Sized` ``__len__`` +:class:`ItemsView` :class:`MappingView`, ``__contains__``, + :class:`Set` ``__iter__`` +:class:`KeysView` :class:`MappingView`, ``__contains__``, + :class:`Set` ``__iter__`` +:class:`ValuesView` :class:`MappingView`, ``__contains__``, ``__iter__`` + :class:`Collection` +:class:`Awaitable` ``__await__`` +:class:`Coroutine` :class:`Awaitable` ``send``, ``throw`` ``close`` +:class:`AsyncIterable` ``__aiter__`` +:class:`AsyncIterator` :class:`AsyncIterable` ``__anext__`` ``__aiter__`` +:class:`AsyncGenerator` :class:`AsyncIterator` ``asend``, ``athrow`` ``aclose``, ``__aiter__``, ``__anext__`` +========================== ====================== ======================= ==================================================== + + +.. class:: Container + Hashable + Sized + Callable + + ABCs for classes that provide respectively the methods :meth:`__contains__`, + :meth:`__hash__`, :meth:`__len__`, and :meth:`__call__`. + +.. class:: Iterable + + ABC for classes that provide the :meth:`__iter__` method. + + Checking ``isinstance(obj, Iterable)`` detects classes that are registered + as :class:`Iterable` or that have an :meth:`__iter__` method, but it does + not detect classes that iterate with the :meth:`__getitem__` method. + The only reliable way to determine whether an object is :term:`iterable` + is to call ``iter(obj)``. + +.. class:: Collection + + ABC for sized iterable container classes. + + .. versionadded:: 3.6 + +.. class:: Iterator + + ABC for classes that provide the :meth:`~iterator.__iter__` and + :meth:`~iterator.__next__` methods. See also the definition of + :term:`iterator`. + +.. class:: Reversible + + ABC for iterable classes that also provide the :meth:`__reversed__` + method. + + .. versionadded:: 3.6 + +.. class:: Generator + + ABC for generator classes that implement the protocol defined in + :pep:`342` that extends iterators with the :meth:`~generator.send`, + :meth:`~generator.throw` and :meth:`~generator.close` methods. + See also the definition of :term:`generator`. + + .. versionadded:: 3.5 + +.. class:: Sequence + MutableSequence + ByteString + + ABCs for read-only and mutable :term:`sequences `. + + Implementation note: Some of the mixin methods, such as + :meth:`__iter__`, :meth:`__reversed__` and :meth:`index`, make + repeated calls to the underlying :meth:`__getitem__` method. + Consequently, if :meth:`__getitem__` is implemented with constant + access speed, the mixin methods will have linear performance; + however, if the underlying method is linear (as it would be with a + linked list), the mixins will have quadratic performance and will + likely need to be overridden. + + .. versionchanged:: 3.5 + The index() method added support for *stop* and *start* + arguments. + +.. class:: Set + MutableSet + + ABCs for read-only and mutable sets. + +.. class:: Mapping + MutableMapping + + ABCs for read-only and mutable :term:`mappings `. + +.. class:: MappingView + ItemsView + KeysView + ValuesView + + ABCs for mapping, items, keys, and values :term:`views `. + +.. class:: Awaitable + + ABC for :term:`awaitable` objects, which can be used in :keyword:`await` + expressions. Custom implementations must provide the :meth:`__await__` + method. + + :term:`Coroutine` objects and instances of the + :class:`~collections.abc.Coroutine` ABC are all instances of this ABC. + + .. note:: + In CPython, generator-based coroutines (generators decorated with + :func:`types.coroutine` or :func:`asyncio.coroutine`) are + *awaitables*, even though they do not have an :meth:`__await__` method. + Using ``isinstance(gencoro, Awaitable)`` for them will return ``False``. + Use :func:`inspect.isawaitable` to detect them. + + .. versionadded:: 3.5 + +.. class:: Coroutine + + ABC for coroutine compatible classes. These implement the + following methods, defined in :ref:`coroutine-objects`: + :meth:`~coroutine.send`, :meth:`~coroutine.throw`, and + :meth:`~coroutine.close`. Custom implementations must also implement + :meth:`__await__`. All :class:`Coroutine` instances are also instances of + :class:`Awaitable`. See also the definition of :term:`coroutine`. + + .. note:: + In CPython, generator-based coroutines (generators decorated with + :func:`types.coroutine` or :func:`asyncio.coroutine`) are + *awaitables*, even though they do not have an :meth:`__await__` method. + Using ``isinstance(gencoro, Coroutine)`` for them will return ``False``. + Use :func:`inspect.isawaitable` to detect them. + + .. versionadded:: 3.5 + +.. class:: AsyncIterable + + ABC for classes that provide ``__aiter__`` method. See also the + definition of :term:`asynchronous iterable`. + + .. versionadded:: 3.5 + +.. class:: AsyncIterator + + ABC for classes that provide ``__aiter__`` and ``__anext__`` + methods. See also the definition of :term:`asynchronous iterator`. + + .. versionadded:: 3.5 + +.. class:: AsyncGenerator + + ABC for asynchronous generator classes that implement the protocol + defined in :pep:`525` and :pep:`492`. + + .. versionadded:: 3.6 + + +These ABCs allow us to ask classes or instances if they provide +particular functionality, for example:: + + size = None + if isinstance(myvar, collections.abc.Sized): + size = len(myvar) + +Several of the ABCs are also useful as mixins that make it easier to develop +classes supporting container APIs. For example, to write a class supporting +the full :class:`Set` API, it is only necessary to supply the three underlying +abstract methods: :meth:`__contains__`, :meth:`__iter__`, and :meth:`__len__`. +The ABC supplies the remaining methods such as :meth:`__and__` and +:meth:`isdisjoint`:: + + class ListBasedSet(collections.abc.Set): + ''' Alternate set implementation favoring space over speed + and not requiring the set elements to be hashable. ''' + def __init__(self, iterable): + self.elements = lst = [] + for value in iterable: + if value not in lst: + lst.append(value) + + def __iter__(self): + return iter(self.elements) + + def __contains__(self, value): + return value in self.elements + + def __len__(self): + return len(self.elements) + + s1 = ListBasedSet('abcdef') + s2 = ListBasedSet('defghi') + overlap = s1 & s2 # The __and__() method is supported automatically + +Notes on using :class:`Set` and :class:`MutableSet` as a mixin: + +(1) + Since some set operations create new sets, the default mixin methods need + a way to create new instances from an iterable. The class constructor is + assumed to have a signature in the form ``ClassName(iterable)``. + That assumption is factored-out to an internal classmethod called + :meth:`_from_iterable` which calls ``cls(iterable)`` to produce a new set. + If the :class:`Set` mixin is being used in a class with a different + constructor signature, you will need to override :meth:`_from_iterable` + with a classmethod that can construct new instances from + an iterable argument. + +(2) + To override the comparisons (presumably for speed, as the + semantics are fixed), redefine :meth:`__le__` and :meth:`__ge__`, + then the other operations will automatically follow suit. + +(3) + The :class:`Set` mixin provides a :meth:`_hash` method to compute a hash value + for the set; however, :meth:`__hash__` is not defined because not all sets + are hashable or immutable. To add set hashability using mixins, + inherit from both :meth:`Set` and :meth:`Hashable`, then define + ``__hash__ = Set._hash``. + +.. seealso:: + + * `OrderedSet recipe `_ for an + example built on :class:`MutableSet`. + + * For more about ABCs, see the :mod:`abc` module and :pep:`3119`. diff --git a/cpython_2/environment/repo/Doc/library/collections.rst b/cpython_2/environment/repo/Doc/library/collections.rst new file mode 100644 index 0000000000000000000000000000000000000000..c9533a3cb8f488562020bd3a32161392cacf0692 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/collections.rst @@ -0,0 +1,1265 @@ +:mod:`collections` --- Container datatypes +========================================== + +.. module:: collections + :synopsis: Container datatypes + +.. moduleauthor:: Raymond Hettinger +.. sectionauthor:: Raymond Hettinger + +**Source code:** :source:`Lib/collections/__init__.py` + +.. testsetup:: * + + from collections import * + import itertools + __name__ = '' + +-------------- + +This module implements specialized container datatypes providing alternatives to +Python's general purpose built-in containers, :class:`dict`, :class:`list`, +:class:`set`, and :class:`tuple`. + +===================== ==================================================================== +:func:`namedtuple` factory function for creating tuple subclasses with named fields +:class:`deque` list-like container with fast appends and pops on either end +:class:`ChainMap` dict-like class for creating a single view of multiple mappings +:class:`Counter` dict subclass for counting hashable objects +:class:`OrderedDict` dict subclass that remembers the order entries were added +:class:`defaultdict` dict subclass that calls a factory function to supply missing values +:class:`UserDict` wrapper around dictionary objects for easier dict subclassing +:class:`UserList` wrapper around list objects for easier list subclassing +:class:`UserString` wrapper around string objects for easier string subclassing +===================== ==================================================================== + +.. deprecated-removed:: 3.3 3.10 + Moved :ref:`collections-abstract-base-classes` to the :mod:`collections.abc` module. + For backwards compatibility, they continue to be visible in this module through + Python 3.9. + + +:class:`ChainMap` objects +------------------------- + +.. versionadded:: 3.3 + +A :class:`ChainMap` class is provided for quickly linking a number of mappings +so they can be treated as a single unit. It is often much faster than creating +a new dictionary and running multiple :meth:`~dict.update` calls. + +The class can be used to simulate nested scopes and is useful in templating. + +.. class:: ChainMap(*maps) + + A :class:`ChainMap` groups multiple dicts or other mappings together to + create a single, updateable view. If no *maps* are specified, a single empty + dictionary is provided so that a new chain always has at least one mapping. + + The underlying mappings are stored in a list. That list is public and can + be accessed or updated using the *maps* attribute. There is no other state. + + Lookups search the underlying mappings successively until a key is found. In + contrast, writes, updates, and deletions only operate on the first mapping. + + A :class:`ChainMap` incorporates the underlying mappings by reference. So, if + one of the underlying mappings gets updated, those changes will be reflected + in :class:`ChainMap`. + + All of the usual dictionary methods are supported. In addition, there is a + *maps* attribute, a method for creating new subcontexts, and a property for + accessing all but the first mapping: + + .. attribute:: maps + + A user updateable list of mappings. The list is ordered from + first-searched to last-searched. It is the only stored state and can + be modified to change which mappings are searched. The list should + always contain at least one mapping. + + .. method:: new_child(m=None) + + Returns a new :class:`ChainMap` containing a new map followed by + all of the maps in the current instance. If ``m`` is specified, + it becomes the new map at the front of the list of mappings; if not + specified, an empty dict is used, so that a call to ``d.new_child()`` + is equivalent to: ``ChainMap({}, *d.maps)``. This method is used for + creating subcontexts that can be updated without altering values in any + of the parent mappings. + + .. versionchanged:: 3.4 + The optional ``m`` parameter was added. + + .. attribute:: parents + + Property returning a new :class:`ChainMap` containing all of the maps in + the current instance except the first one. This is useful for skipping + the first map in the search. Use cases are similar to those for the + :keyword:`nonlocal` keyword used in :term:`nested scopes `. The use cases also parallel those for the built-in + :func:`super` function. A reference to ``d.parents`` is equivalent to: + ``ChainMap(*d.maps[1:])``. + + Note, the iteration order of a :class:`ChainMap()` is determined by + scanning the mappings last to first:: + + >>> baseline = {'music': 'bach', 'art': 'rembrandt'} + >>> adjustments = {'art': 'van gogh', 'opera': 'carmen'} + >>> list(ChainMap(adjustments, baseline)) + ['music', 'art', 'opera'] + + This gives the same ordering as a series of :meth:`dict.update` calls + starting with the last mapping:: + + >>> combined = baseline.copy() + >>> combined.update(adjustments) + >>> list(combined) + ['music', 'art', 'opera'] + + .. versionchanged:: 3.9 + Added support for ``|`` and ``|=`` operators, specified in :pep:`584`. + +.. seealso:: + + * The `MultiContext class + `_ + in the Enthought `CodeTools package + `_ has options to support + writing to any mapping in the chain. + + * Django's `Context class + `_ + for templating is a read-only chain of mappings. It also features + pushing and popping of contexts similar to the + :meth:`~collections.ChainMap.new_child` method and the + :attr:`~collections.ChainMap.parents` property. + + * The `Nested Contexts recipe + `_ has options to control + whether writes and other mutations apply only to the first mapping or to + any mapping in the chain. + + * A `greatly simplified read-only version of Chainmap + `_. + + +:class:`ChainMap` Examples and Recipes +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +This section shows various approaches to working with chained maps. + + +Example of simulating Python's internal lookup chain:: + + import builtins + pylookup = ChainMap(locals(), globals(), vars(builtins)) + +Example of letting user specified command-line arguments take precedence over +environment variables which in turn take precedence over default values:: + + import os, argparse + + defaults = {'color': 'red', 'user': 'guest'} + + parser = argparse.ArgumentParser() + parser.add_argument('-u', '--user') + parser.add_argument('-c', '--color') + namespace = parser.parse_args() + command_line_args = {k: v for k, v in vars(namespace).items() if v is not None} + + combined = ChainMap(command_line_args, os.environ, defaults) + print(combined['color']) + print(combined['user']) + +Example patterns for using the :class:`ChainMap` class to simulate nested +contexts:: + + c = ChainMap() # Create root context + d = c.new_child() # Create nested child context + e = c.new_child() # Child of c, independent from d + e.maps[0] # Current context dictionary -- like Python's locals() + e.maps[-1] # Root context -- like Python's globals() + e.parents # Enclosing context chain -- like Python's nonlocals + + d['x'] = 1 # Set value in current context + d['x'] # Get first key in the chain of contexts + del d['x'] # Delete from current context + list(d) # All nested values + k in d # Check all nested values + len(d) # Number of nested values + d.items() # All nested items + dict(d) # Flatten into a regular dictionary + +The :class:`ChainMap` class only makes updates (writes and deletions) to the +first mapping in the chain while lookups will search the full chain. However, +if deep writes and deletions are desired, it is easy to make a subclass that +updates keys found deeper in the chain:: + + class DeepChainMap(ChainMap): + 'Variant of ChainMap that allows direct updates to inner scopes' + + def __setitem__(self, key, value): + for mapping in self.maps: + if key in mapping: + mapping[key] = value + return + self.maps[0][key] = value + + def __delitem__(self, key): + for mapping in self.maps: + if key in mapping: + del mapping[key] + return + raise KeyError(key) + + >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) + >>> d['lion'] = 'orange' # update an existing key two levels down + >>> d['snake'] = 'red' # new keys get added to the topmost dict + >>> del d['elephant'] # remove an existing key one level down + >>> d # display result + DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'}) + + +:class:`Counter` objects +------------------------ + +A counter tool is provided to support convenient and rapid tallies. +For example:: + + >>> # Tally occurrences of words in a list + >>> cnt = Counter() + >>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']: + ... cnt[word] += 1 + >>> cnt + Counter({'blue': 3, 'red': 2, 'green': 1}) + + >>> # Find the ten most common words in Hamlet + >>> import re + >>> words = re.findall(r'\w+', open('hamlet.txt').read().lower()) + >>> Counter(words).most_common(10) + [('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631), + ('you', 554), ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)] + +.. class:: Counter([iterable-or-mapping]) + + A :class:`Counter` is a :class:`dict` subclass for counting hashable objects. + It is a collection where elements are stored as dictionary keys + and their counts are stored as dictionary values. Counts are allowed to be + any integer value including zero or negative counts. The :class:`Counter` + class is similar to bags or multisets in other languages. + + Elements are counted from an *iterable* or initialized from another + *mapping* (or counter): + + >>> c = Counter() # a new, empty counter + >>> c = Counter('gallahad') # a new counter from an iterable + >>> c = Counter({'red': 4, 'blue': 2}) # a new counter from a mapping + >>> c = Counter(cats=4, dogs=8) # a new counter from keyword args + + Counter objects have a dictionary interface except that they return a zero + count for missing items instead of raising a :exc:`KeyError`: + + >>> c = Counter(['eggs', 'ham']) + >>> c['bacon'] # count of a missing element is zero + 0 + + Setting a count to zero does not remove an element from a counter. + Use ``del`` to remove it entirely: + + >>> c['sausage'] = 0 # counter entry with a zero count + >>> del c['sausage'] # del actually removes the entry + + .. versionadded:: 3.1 + + .. versionchanged:: 3.7 As a :class:`dict` subclass, :class:`Counter` + Inherited the capability to remember insertion order. Math operations + on *Counter* objects also preserve order. Results are ordered + according to when an element is first encountered in the left operand + and then by the order encountered in the right operand. + + Counter objects support three methods beyond those available for all + dictionaries: + + .. method:: elements() + + Return an iterator over elements repeating each as many times as its + count. Elements are returned in the order first encountered. If an + element's count is less than one, :meth:`elements` will ignore it. + + >>> c = Counter(a=4, b=2, c=0, d=-2) + >>> sorted(c.elements()) + ['a', 'a', 'a', 'a', 'b', 'b'] + + .. method:: most_common([n]) + + Return a list of the *n* most common elements and their counts from the + most common to the least. If *n* is omitted or ``None``, + :meth:`most_common` returns *all* elements in the counter. + Elements with equal counts are ordered in the order first encountered: + + >>> Counter('abracadabra').most_common(3) + [('a', 5), ('b', 2), ('r', 2)] + + .. method:: subtract([iterable-or-mapping]) + + Elements are subtracted from an *iterable* or from another *mapping* + (or counter). Like :meth:`dict.update` but subtracts counts instead + of replacing them. Both inputs and outputs may be zero or negative. + + >>> c = Counter(a=4, b=2, c=0, d=-2) + >>> d = Counter(a=1, b=2, c=3, d=4) + >>> c.subtract(d) + >>> c + Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6}) + + .. versionadded:: 3.2 + + The usual dictionary methods are available for :class:`Counter` objects + except for two which work differently for counters. + + .. method:: fromkeys(iterable) + + This class method is not implemented for :class:`Counter` objects. + + .. method:: update([iterable-or-mapping]) + + Elements are counted from an *iterable* or added-in from another + *mapping* (or counter). Like :meth:`dict.update` but adds counts + instead of replacing them. Also, the *iterable* is expected to be a + sequence of elements, not a sequence of ``(key, value)`` pairs. + +Common patterns for working with :class:`Counter` objects:: + + sum(c.values()) # total of all counts + c.clear() # reset all counts + list(c) # list unique elements + set(c) # convert to a set + dict(c) # convert to a regular dictionary + c.items() # convert to a list of (elem, cnt) pairs + Counter(dict(list_of_pairs)) # convert from a list of (elem, cnt) pairs + c.most_common()[:-n-1:-1] # n least common elements + +c # remove zero and negative counts + +Several mathematical operations are provided for combining :class:`Counter` +objects to produce multisets (counters that have counts greater than zero). +Addition and subtraction combine counters by adding or subtracting the counts +of corresponding elements. Intersection and union return the minimum and +maximum of corresponding counts. Each operation can accept inputs with signed +counts, but the output will exclude results with counts of zero or less. + + >>> c = Counter(a=3, b=1) + >>> d = Counter(a=1, b=2) + >>> c + d # add two counters together: c[x] + d[x] + Counter({'a': 4, 'b': 3}) + >>> c - d # subtract (keeping only positive counts) + Counter({'a': 2}) + >>> c & d # intersection: min(c[x], d[x]) # doctest: +SKIP + Counter({'a': 1, 'b': 1}) + >>> c | d # union: max(c[x], d[x]) + Counter({'a': 3, 'b': 2}) + +Unary addition and subtraction are shortcuts for adding an empty counter +or subtracting from an empty counter. + + >>> c = Counter(a=2, b=-4) + >>> +c + Counter({'a': 2}) + >>> -c + Counter({'b': 4}) + +.. versionadded:: 3.3 + Added support for unary plus, unary minus, and in-place multiset operations. + +.. note:: + + Counters were primarily designed to work with positive integers to represent + running counts; however, care was taken to not unnecessarily preclude use + cases needing other types or negative values. To help with those use cases, + this section documents the minimum range and type restrictions. + + * The :class:`Counter` class itself is a dictionary subclass with no + restrictions on its keys and values. The values are intended to be numbers + representing counts, but you *could* store anything in the value field. + + * The :meth:`~Counter.most_common` method requires only that the values be orderable. + + * For in-place operations such as ``c[key] += 1``, the value type need only + support addition and subtraction. So fractions, floats, and decimals would + work and negative values are supported. The same is also true for + :meth:`~Counter.update` and :meth:`~Counter.subtract` which allow negative and zero values + for both inputs and outputs. + + * The multiset methods are designed only for use cases with positive values. + The inputs may be negative or zero, but only outputs with positive values + are created. There are no type restrictions, but the value type needs to + support addition, subtraction, and comparison. + + * The :meth:`~Counter.elements` method requires integer counts. It ignores zero and + negative counts. + +.. seealso:: + + * `Bag class `_ + in Smalltalk. + + * Wikipedia entry for `Multisets `_. + + * `C++ multisets `_ + tutorial with examples. + + * For mathematical operations on multisets and their use cases, see + *Knuth, Donald. The Art of Computer Programming Volume II, + Section 4.6.3, Exercise 19*. + + * To enumerate all distinct multisets of a given size over a given set of + elements, see :func:`itertools.combinations_with_replacement`:: + + map(Counter, combinations_with_replacement('ABC', 2)) # --> AA AB AC BB BC CC + + +:class:`deque` objects +---------------------- + +.. class:: deque([iterable, [maxlen]]) + + Returns a new deque object initialized left-to-right (using :meth:`append`) with + data from *iterable*. If *iterable* is not specified, the new deque is empty. + + Deques are a generalization of stacks and queues (the name is pronounced "deck" + and is short for "double-ended queue"). Deques support thread-safe, memory + efficient appends and pops from either side of the deque with approximately the + same O(1) performance in either direction. + + Though :class:`list` objects support similar operations, they are optimized for + fast fixed-length operations and incur O(n) memory movement costs for + ``pop(0)`` and ``insert(0, v)`` operations which change both the size and + position of the underlying data representation. + + + If *maxlen* is not specified or is ``None``, deques may grow to an + arbitrary length. Otherwise, the deque is bounded to the specified maximum + length. Once a bounded length deque is full, when new items are added, a + corresponding number of items are discarded from the opposite end. Bounded + length deques provide functionality similar to the ``tail`` filter in + Unix. They are also useful for tracking transactions and other pools of data + where only the most recent activity is of interest. + + + Deque objects support the following methods: + + .. method:: append(x) + + Add *x* to the right side of the deque. + + + .. method:: appendleft(x) + + Add *x* to the left side of the deque. + + + .. method:: clear() + + Remove all elements from the deque leaving it with length 0. + + + .. method:: copy() + + Create a shallow copy of the deque. + + .. versionadded:: 3.5 + + + .. method:: count(x) + + Count the number of deque elements equal to *x*. + + .. versionadded:: 3.2 + + + .. method:: extend(iterable) + + Extend the right side of the deque by appending elements from the iterable + argument. + + + .. method:: extendleft(iterable) + + Extend the left side of the deque by appending elements from *iterable*. + Note, the series of left appends results in reversing the order of + elements in the iterable argument. + + + .. method:: index(x[, start[, stop]]) + + Return the position of *x* in the deque (at or after index *start* + and before index *stop*). Returns the first match or raises + :exc:`ValueError` if not found. + + .. versionadded:: 3.5 + + + .. method:: insert(i, x) + + Insert *x* into the deque at position *i*. + + If the insertion would cause a bounded deque to grow beyond *maxlen*, + an :exc:`IndexError` is raised. + + .. versionadded:: 3.5 + + + .. method:: pop() + + Remove and return an element from the right side of the deque. If no + elements are present, raises an :exc:`IndexError`. + + + .. method:: popleft() + + Remove and return an element from the left side of the deque. If no + elements are present, raises an :exc:`IndexError`. + + + .. method:: remove(value) + + Remove the first occurrence of *value*. If not found, raises a + :exc:`ValueError`. + + + .. method:: reverse() + + Reverse the elements of the deque in-place and then return ``None``. + + .. versionadded:: 3.2 + + + .. method:: rotate(n=1) + + Rotate the deque *n* steps to the right. If *n* is negative, rotate + to the left. + + When the deque is not empty, rotating one step to the right is equivalent + to ``d.appendleft(d.pop())``, and rotating one step to the left is + equivalent to ``d.append(d.popleft())``. + + + Deque objects also provide one read-only attribute: + + .. attribute:: maxlen + + Maximum size of a deque or ``None`` if unbounded. + + .. versionadded:: 3.1 + + +In addition to the above, deques support iteration, pickling, ``len(d)``, +``reversed(d)``, ``copy.copy(d)``, ``copy.deepcopy(d)``, membership testing with +the :keyword:`in` operator, and subscript references such as ``d[0]`` to access +the first element. Indexed access is O(1) at both ends but slows to O(n) in +the middle. For fast random access, use lists instead. + +Starting in version 3.5, deques support ``__add__()``, ``__mul__()``, +and ``__imul__()``. + +Example: + +.. doctest:: + + >>> from collections import deque + >>> d = deque('ghi') # make a new deque with three items + >>> for elem in d: # iterate over the deque's elements + ... print(elem.upper()) + G + H + I + + >>> d.append('j') # add a new entry to the right side + >>> d.appendleft('f') # add a new entry to the left side + >>> d # show the representation of the deque + deque(['f', 'g', 'h', 'i', 'j']) + + >>> d.pop() # return and remove the rightmost item + 'j' + >>> d.popleft() # return and remove the leftmost item + 'f' + >>> list(d) # list the contents of the deque + ['g', 'h', 'i'] + >>> d[0] # peek at leftmost item + 'g' + >>> d[-1] # peek at rightmost item + 'i' + + >>> list(reversed(d)) # list the contents of a deque in reverse + ['i', 'h', 'g'] + >>> 'h' in d # search the deque + True + >>> d.extend('jkl') # add multiple elements at once + >>> d + deque(['g', 'h', 'i', 'j', 'k', 'l']) + >>> d.rotate(1) # right rotation + >>> d + deque(['l', 'g', 'h', 'i', 'j', 'k']) + >>> d.rotate(-1) # left rotation + >>> d + deque(['g', 'h', 'i', 'j', 'k', 'l']) + + >>> deque(reversed(d)) # make a new deque in reverse order + deque(['l', 'k', 'j', 'i', 'h', 'g']) + >>> d.clear() # empty the deque + >>> d.pop() # cannot pop from an empty deque + Traceback (most recent call last): + File "", line 1, in -toplevel- + d.pop() + IndexError: pop from an empty deque + + >>> d.extendleft('abc') # extendleft() reverses the input order + >>> d + deque(['c', 'b', 'a']) + + +:class:`deque` Recipes +^^^^^^^^^^^^^^^^^^^^^^ + +This section shows various approaches to working with deques. + +Bounded length deques provide functionality similar to the ``tail`` filter +in Unix:: + + def tail(filename, n=10): + 'Return the last n lines of a file' + with open(filename) as f: + return deque(f, n) + +Another approach to using deques is to maintain a sequence of recently +added elements by appending to the right and popping to the left:: + + def moving_average(iterable, n=3): + # moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0 + # http://en.wikipedia.org/wiki/Moving_average + it = iter(iterable) + d = deque(itertools.islice(it, n-1)) + d.appendleft(0) + s = sum(d) + for elem in it: + s += elem - d.popleft() + d.append(elem) + yield s / n + +A `round-robin scheduler +`_ can be implemented with +input iterators stored in a :class:`deque`. Values are yielded from the active +iterator in position zero. If that iterator is exhausted, it can be removed +with :meth:`~deque.popleft`; otherwise, it can be cycled back to the end with +the :meth:`~deque.rotate` method:: + + def roundrobin(*iterables): + "roundrobin('ABC', 'D', 'EF') --> A D E B F C" + iterators = deque(map(iter, iterables)) + while iterators: + try: + while True: + yield next(iterators[0]) + iterators.rotate(-1) + except StopIteration: + # Remove an exhausted iterator. + iterators.popleft() + +The :meth:`~deque.rotate` method provides a way to implement :class:`deque` slicing and +deletion. For example, a pure Python implementation of ``del d[n]`` relies on +the ``rotate()`` method to position elements to be popped:: + + def delete_nth(d, n): + d.rotate(-n) + d.popleft() + d.rotate(n) + +To implement :class:`deque` slicing, use a similar approach applying +:meth:`~deque.rotate` to bring a target element to the left side of the deque. Remove +old entries with :meth:`~deque.popleft`, add new entries with :meth:`~deque.extend`, and then +reverse the rotation. +With minor variations on that approach, it is easy to implement Forth style +stack manipulations such as ``dup``, ``drop``, ``swap``, ``over``, ``pick``, +``rot``, and ``roll``. + + +:class:`defaultdict` objects +---------------------------- + +.. class:: defaultdict([default_factory[, ...]]) + + Returns a new dictionary-like object. :class:`defaultdict` is a subclass of the + built-in :class:`dict` class. It overrides one method and adds one writable + instance variable. The remaining functionality is the same as for the + :class:`dict` class and is not documented here. + + The first argument provides the initial value for the :attr:`default_factory` + attribute; it defaults to ``None``. All remaining arguments are treated the same + as if they were passed to the :class:`dict` constructor, including keyword + arguments. + + + :class:`defaultdict` objects support the following method in addition to the + standard :class:`dict` operations: + + .. method:: __missing__(key) + + If the :attr:`default_factory` attribute is ``None``, this raises a + :exc:`KeyError` exception with the *key* as argument. + + If :attr:`default_factory` is not ``None``, it is called without arguments + to provide a default value for the given *key*, this value is inserted in + the dictionary for the *key*, and returned. + + If calling :attr:`default_factory` raises an exception this exception is + propagated unchanged. + + This method is called by the :meth:`__getitem__` method of the + :class:`dict` class when the requested key is not found; whatever it + returns or raises is then returned or raised by :meth:`__getitem__`. + + Note that :meth:`__missing__` is *not* called for any operations besides + :meth:`__getitem__`. This means that :meth:`get` will, like normal + dictionaries, return ``None`` as a default rather than using + :attr:`default_factory`. + + + :class:`defaultdict` objects support the following instance variable: + + + .. attribute:: default_factory + + This attribute is used by the :meth:`__missing__` method; it is + initialized from the first argument to the constructor, if present, or to + ``None``, if absent. + + .. versionchanged:: 3.9 + Added merge (``|``) and update (``|=``) operators, specified in + :pep:`584`. + + +:class:`defaultdict` Examples +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Using :class:`list` as the :attr:`~defaultdict.default_factory`, it is easy to group a +sequence of key-value pairs into a dictionary of lists: + + >>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] + >>> d = defaultdict(list) + >>> for k, v in s: + ... d[k].append(v) + ... + >>> sorted(d.items()) + [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])] + +When each key is encountered for the first time, it is not already in the +mapping; so an entry is automatically created using the :attr:`~defaultdict.default_factory` +function which returns an empty :class:`list`. The :meth:`list.append` +operation then attaches the value to the new list. When keys are encountered +again, the look-up proceeds normally (returning the list for that key) and the +:meth:`list.append` operation adds another value to the list. This technique is +simpler and faster than an equivalent technique using :meth:`dict.setdefault`: + + >>> d = {} + >>> for k, v in s: + ... d.setdefault(k, []).append(v) + ... + >>> sorted(d.items()) + [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])] + +Setting the :attr:`~defaultdict.default_factory` to :class:`int` makes the +:class:`defaultdict` useful for counting (like a bag or multiset in other +languages): + + >>> s = 'mississippi' + >>> d = defaultdict(int) + >>> for k in s: + ... d[k] += 1 + ... + >>> sorted(d.items()) + [('i', 4), ('m', 1), ('p', 2), ('s', 4)] + +When a letter is first encountered, it is missing from the mapping, so the +:attr:`~defaultdict.default_factory` function calls :func:`int` to supply a default count of +zero. The increment operation then builds up the count for each letter. + +The function :func:`int` which always returns zero is just a special case of +constant functions. A faster and more flexible way to create constant functions +is to use a lambda function which can supply any constant value (not just +zero): + + >>> def constant_factory(value): + ... return lambda: value + >>> d = defaultdict(constant_factory('')) + >>> d.update(name='John', action='ran') + >>> '%(name)s %(action)s to %(object)s' % d + 'John ran to ' + +Setting the :attr:`~defaultdict.default_factory` to :class:`set` makes the +:class:`defaultdict` useful for building a dictionary of sets: + + >>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)] + >>> d = defaultdict(set) + >>> for k, v in s: + ... d[k].add(v) + ... + >>> sorted(d.items()) + [('blue', {2, 4}), ('red', {1, 3})] + + +:func:`namedtuple` Factory Function for Tuples with Named Fields +---------------------------------------------------------------- + +Named tuples assign meaning to each position in a tuple and allow for more readable, +self-documenting code. They can be used wherever regular tuples are used, and +they add the ability to access fields by name instead of position index. + +.. function:: namedtuple(typename, field_names, *, rename=False, defaults=None, module=None) + + Returns a new tuple subclass named *typename*. The new subclass is used to + create tuple-like objects that have fields accessible by attribute lookup as + well as being indexable and iterable. Instances of the subclass also have a + helpful docstring (with typename and field_names) and a helpful :meth:`__repr__` + method which lists the tuple contents in a ``name=value`` format. + + The *field_names* are a sequence of strings such as ``['x', 'y']``. + Alternatively, *field_names* can be a single string with each fieldname + separated by whitespace and/or commas, for example ``'x y'`` or ``'x, y'``. + + Any valid Python identifier may be used for a fieldname except for names + starting with an underscore. Valid identifiers consist of letters, digits, + and underscores but do not start with a digit or underscore and cannot be + a :mod:`keyword` such as *class*, *for*, *return*, *global*, *pass*, + or *raise*. + + If *rename* is true, invalid fieldnames are automatically replaced + with positional names. For example, ``['abc', 'def', 'ghi', 'abc']`` is + converted to ``['abc', '_1', 'ghi', '_3']``, eliminating the keyword + ``def`` and the duplicate fieldname ``abc``. + + *defaults* can be ``None`` or an :term:`iterable` of default values. + Since fields with a default value must come after any fields without a + default, the *defaults* are applied to the rightmost parameters. For + example, if the fieldnames are ``['x', 'y', 'z']`` and the defaults are + ``(1, 2)``, then ``x`` will be a required argument, ``y`` will default to + ``1``, and ``z`` will default to ``2``. + + If *module* is defined, the ``__module__`` attribute of the named tuple is + set to that value. + + Named tuple instances do not have per-instance dictionaries, so they are + lightweight and require no more memory than regular tuples. + + .. versionchanged:: 3.1 + Added support for *rename*. + + .. versionchanged:: 3.6 + The *verbose* and *rename* parameters became + :ref:`keyword-only arguments `. + + .. versionchanged:: 3.6 + Added the *module* parameter. + + .. versionchanged:: 3.7 + Removed the *verbose* parameter and the :attr:`_source` attribute. + + .. versionchanged:: 3.7 + Added the *defaults* parameter and the :attr:`_field_defaults` + attribute. + +.. doctest:: + :options: +NORMALIZE_WHITESPACE + + >>> # Basic example + >>> Point = namedtuple('Point', ['x', 'y']) + >>> p = Point(11, y=22) # instantiate with positional or keyword arguments + >>> p[0] + p[1] # indexable like the plain tuple (11, 22) + 33 + >>> x, y = p # unpack like a regular tuple + >>> x, y + (11, 22) + >>> p.x + p.y # fields also accessible by name + 33 + >>> p # readable __repr__ with a name=value style + Point(x=11, y=22) + +Named tuples are especially useful for assigning field names to result tuples returned +by the :mod:`csv` or :mod:`sqlite3` modules:: + + EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade') + + import csv + for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))): + print(emp.name, emp.title) + + import sqlite3 + conn = sqlite3.connect('/companydata') + cursor = conn.cursor() + cursor.execute('SELECT name, age, title, department, paygrade FROM employees') + for emp in map(EmployeeRecord._make, cursor.fetchall()): + print(emp.name, emp.title) + +In addition to the methods inherited from tuples, named tuples support +three additional methods and two attributes. To prevent conflicts with +field names, the method and attribute names start with an underscore. + +.. classmethod:: somenamedtuple._make(iterable) + + Class method that makes a new instance from an existing sequence or iterable. + + .. doctest:: + + >>> t = [11, 22] + >>> Point._make(t) + Point(x=11, y=22) + +.. method:: somenamedtuple._asdict() + + Return a new :class:`dict` which maps field names to their corresponding + values: + + .. doctest:: + + >>> p = Point(x=11, y=22) + >>> p._asdict() + {'x': 11, 'y': 22} + + .. versionchanged:: 3.1 + Returns an :class:`OrderedDict` instead of a regular :class:`dict`. + + .. versionchanged:: 3.8 + Returns a regular :class:`dict` instead of an :class:`OrderedDict`. + As of Python 3.7, regular dicts are guaranteed to be ordered. If the + extra features of :class:`OrderedDict` are required, the suggested + remediation is to cast the result to the desired type: + ``OrderedDict(nt._asdict())``. + +.. method:: somenamedtuple._replace(**kwargs) + + Return a new instance of the named tuple replacing specified fields with new + values:: + + >>> p = Point(x=11, y=22) + >>> p._replace(x=33) + Point(x=33, y=22) + + >>> for partnum, record in inventory.items(): + ... inventory[partnum] = record._replace(price=newprices[partnum], timestamp=time.now()) + +.. attribute:: somenamedtuple._fields + + Tuple of strings listing the field names. Useful for introspection + and for creating new named tuple types from existing named tuples. + + .. doctest:: + + >>> p._fields # view the field names + ('x', 'y') + + >>> Color = namedtuple('Color', 'red green blue') + >>> Pixel = namedtuple('Pixel', Point._fields + Color._fields) + >>> Pixel(11, 22, 128, 255, 0) + Pixel(x=11, y=22, red=128, green=255, blue=0) + +.. attribute:: somenamedtuple._field_defaults + + Dictionary mapping field names to default values. + + .. doctest:: + + >>> Account = namedtuple('Account', ['type', 'balance'], defaults=[0]) + >>> Account._field_defaults + {'balance': 0} + >>> Account('premium') + Account(type='premium', balance=0) + +To retrieve a field whose name is stored in a string, use the :func:`getattr` +function: + + >>> getattr(p, 'x') + 11 + +To convert a dictionary to a named tuple, use the double-star-operator +(as described in :ref:`tut-unpacking-arguments`): + + >>> d = {'x': 11, 'y': 22} + >>> Point(**d) + Point(x=11, y=22) + +Since a named tuple is a regular Python class, it is easy to add or change +functionality with a subclass. Here is how to add a calculated field and +a fixed-width print format: + +.. doctest:: + + >>> class Point(namedtuple('Point', ['x', 'y'])): + ... __slots__ = () + ... @property + ... def hypot(self): + ... return (self.x ** 2 + self.y ** 2) ** 0.5 + ... def __str__(self): + ... return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, self.hypot) + + >>> for p in Point(3, 4), Point(14, 5/7): + ... print(p) + Point: x= 3.000 y= 4.000 hypot= 5.000 + Point: x=14.000 y= 0.714 hypot=14.018 + +The subclass shown above sets ``__slots__`` to an empty tuple. This helps +keep memory requirements low by preventing the creation of instance dictionaries. + +Subclassing is not useful for adding new, stored fields. Instead, simply +create a new named tuple type from the :attr:`~somenamedtuple._fields` attribute: + + >>> Point3D = namedtuple('Point3D', Point._fields + ('z',)) + +Docstrings can be customized by making direct assignments to the ``__doc__`` +fields: + + >>> Book = namedtuple('Book', ['id', 'title', 'authors']) + >>> Book.__doc__ += ': Hardcover book in active collection' + >>> Book.id.__doc__ = '13-digit ISBN' + >>> Book.title.__doc__ = 'Title of first printing' + >>> Book.authors.__doc__ = 'List of authors sorted by last name' + +.. versionchanged:: 3.5 + Property docstrings became writeable. + +.. seealso:: + + * See :class:`typing.NamedTuple` for a way to add type hints for named + tuples. It also provides an elegant notation using the :keyword:`class` + keyword:: + + class Component(NamedTuple): + part_number: int + weight: float + description: Optional[str] = None + + * See :meth:`types.SimpleNamespace` for a mutable namespace based on an + underlying dictionary instead of a tuple. + + * The :mod:`dataclasses` module provides a decorator and functions for + automatically adding generated special methods to user-defined classes. + + +:class:`OrderedDict` objects +---------------------------- + +Ordered dictionaries are just like regular dictionaries but have some extra +capabilities relating to ordering operations. They have become less +important now that the built-in :class:`dict` class gained the ability +to remember insertion order (this new behavior became guaranteed in +Python 3.7). + +Some differences from :class:`dict` still remain: + +* The regular :class:`dict` was designed to be very good at mapping + operations. Tracking insertion order was secondary. + +* The :class:`OrderedDict` was designed to be good at reordering operations. + Space efficiency, iteration speed, and the performance of update + operations were secondary. + +* Algorithmically, :class:`OrderedDict` can handle frequent reordering + operations better than :class:`dict`. This makes it suitable for tracking + recent accesses (for example in an `LRU cache + `_). + +* The equality operation for :class:`OrderedDict` checks for matching order. + +* The :meth:`popitem` method of :class:`OrderedDict` has a different + signature. It accepts an optional argument to specify which item is popped. + +* :class:`OrderedDict` has a :meth:`move_to_end` method to + efficiently reposition an element to an endpoint. + +* Until Python 3.8, :class:`dict` lacked a :meth:`__reversed__` method. + + +.. class:: OrderedDict([items]) + + Return an instance of a :class:`dict` subclass that has methods + specialized for rearranging dictionary order. + + .. versionadded:: 3.1 + + .. method:: popitem(last=True) + + The :meth:`popitem` method for ordered dictionaries returns and removes a + (key, value) pair. The pairs are returned in + :abbr:`LIFO (last-in, first-out)` order if *last* is true + or :abbr:`FIFO (first-in, first-out)` order if false. + + .. method:: move_to_end(key, last=True) + + Move an existing *key* to either end of an ordered dictionary. The item + is moved to the right end if *last* is true (the default) or to the + beginning if *last* is false. Raises :exc:`KeyError` if the *key* does + not exist:: + + >>> d = OrderedDict.fromkeys('abcde') + >>> d.move_to_end('b') + >>> ''.join(d.keys()) + 'acdeb' + >>> d.move_to_end('b', last=False) + >>> ''.join(d.keys()) + 'bacde' + + .. versionadded:: 3.2 + +In addition to the usual mapping methods, ordered dictionaries also support +reverse iteration using :func:`reversed`. + +Equality tests between :class:`OrderedDict` objects are order-sensitive +and are implemented as ``list(od1.items())==list(od2.items())``. +Equality tests between :class:`OrderedDict` objects and other +:class:`~collections.abc.Mapping` objects are order-insensitive like regular +dictionaries. This allows :class:`OrderedDict` objects to be substituted +anywhere a regular dictionary is used. + +.. versionchanged:: 3.5 + The items, keys, and values :term:`views ` + of :class:`OrderedDict` now support reverse iteration using :func:`reversed`. + +.. versionchanged:: 3.6 + With the acceptance of :pep:`468`, order is retained for keyword arguments + passed to the :class:`OrderedDict` constructor and its :meth:`update` + method. + +.. versionchanged:: 3.9 + Added merge (``|``) and update (``|=``) operators, specified in :pep:`584`. + + +:class:`OrderedDict` Examples and Recipes +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +It is straightforward to create an ordered dictionary variant +that remembers the order the keys were *last* inserted. +If a new entry overwrites an existing entry, the +original insertion position is changed and moved to the end:: + + class LastUpdatedOrderedDict(OrderedDict): + 'Store items in the order the keys were last added' + + def __setitem__(self, key, value): + super().__setitem__(key, value) + self.move_to_end(key) + +An :class:`OrderedDict` would also be useful for implementing +variants of :func:`functools.lru_cache`:: + + class LRU(OrderedDict): + 'Limit size, evicting the least recently looked-up key when full' + + def __init__(self, maxsize=128, /, *args, **kwds): + self.maxsize = maxsize + super().__init__(*args, **kwds) + + def __getitem__(self, key): + value = super().__getitem__(key) + self.move_to_end(key) + return value + + def __setitem__(self, key, value): + super().__setitem__(key, value) + if len(self) > self.maxsize: + oldest = next(iter(self)) + del self[oldest] + + +:class:`UserDict` objects +------------------------- + +The class, :class:`UserDict` acts as a wrapper around dictionary objects. +The need for this class has been partially supplanted by the ability to +subclass directly from :class:`dict`; however, this class can be easier +to work with because the underlying dictionary is accessible as an +attribute. + +.. class:: UserDict([initialdata]) + + Class that simulates a dictionary. The instance's contents are kept in a + regular dictionary, which is accessible via the :attr:`data` attribute of + :class:`UserDict` instances. If *initialdata* is provided, :attr:`data` is + initialized with its contents; note that a reference to *initialdata* will not + be kept, allowing it be used for other purposes. + + In addition to supporting the methods and operations of mappings, + :class:`UserDict` instances provide the following attribute: + + .. attribute:: data + + A real dictionary used to store the contents of the :class:`UserDict` + class. + + + +:class:`UserList` objects +------------------------- + +This class acts as a wrapper around list objects. It is a useful base class +for your own list-like classes which can inherit from them and override +existing methods or add new ones. In this way, one can add new behaviors to +lists. + +The need for this class has been partially supplanted by the ability to +subclass directly from :class:`list`; however, this class can be easier +to work with because the underlying list is accessible as an attribute. + +.. class:: UserList([list]) + + Class that simulates a list. The instance's contents are kept in a regular + list, which is accessible via the :attr:`data` attribute of :class:`UserList` + instances. The instance's contents are initially set to a copy of *list*, + defaulting to the empty list ``[]``. *list* can be any iterable, for + example a real Python list or a :class:`UserList` object. + + In addition to supporting the methods and operations of mutable sequences, + :class:`UserList` instances provide the following attribute: + + .. attribute:: data + + A real :class:`list` object used to store the contents of the + :class:`UserList` class. + +**Subclassing requirements:** Subclasses of :class:`UserList` are expected to +offer a constructor which can be called with either no arguments or one +argument. List operations which return a new sequence attempt to create an +instance of the actual implementation class. To do so, it assumes that the +constructor can be called with a single parameter, which is a sequence object +used as a data source. + +If a derived class does not wish to comply with this requirement, all of the +special methods supported by this class will need to be overridden; please +consult the sources for information about the methods which need to be provided +in that case. + +:class:`UserString` objects +--------------------------- + +The class, :class:`UserString` acts as a wrapper around string objects. +The need for this class has been partially supplanted by the ability to +subclass directly from :class:`str`; however, this class can be easier +to work with because the underlying string is accessible as an +attribute. + +.. class:: UserString(seq) + + Class that simulates a string object. The instance's + content is kept in a regular string object, which is accessible via the + :attr:`data` attribute of :class:`UserString` instances. The instance's + contents are initially set to a copy of *seq*. The *seq* argument can + be any object which can be converted into a string using the built-in + :func:`str` function. + + In addition to supporting the methods and operations of strings, + :class:`UserString` instances provide the following attribute: + + .. attribute:: data + + A real :class:`str` object used to store the contents of the + :class:`UserString` class. + + .. versionchanged:: 3.5 + New methods ``__getnewargs__``, ``__rmod__``, ``casefold``, + ``format_map``, ``isprintable``, and ``maketrans``. diff --git a/cpython_2/environment/repo/Doc/library/colorsys.rst b/cpython_2/environment/repo/Doc/library/colorsys.rst new file mode 100644 index 0000000000000000000000000000000000000000..b672a05b39145d45ce0de160c4717aa2edfd37d8 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/colorsys.rst @@ -0,0 +1,65 @@ +:mod:`colorsys` --- Conversions between color systems +===================================================== + +.. module:: colorsys + :synopsis: Conversion functions between RGB and other color systems. + +.. sectionauthor:: David Ascher + +**Source code:** :source:`Lib/colorsys.py` + +-------------- + +The :mod:`colorsys` module defines bidirectional conversions of color values +between colors expressed in the RGB (Red Green Blue) color space used in +computer monitors and three other coordinate systems: YIQ, HLS (Hue Lightness +Saturation) and HSV (Hue Saturation Value). Coordinates in all of these color +spaces are floating point values. In the YIQ space, the Y coordinate is between +0 and 1, but the I and Q coordinates can be positive or negative. In all other +spaces, the coordinates are all between 0 and 1. + +.. seealso:: + + More information about color spaces can be found at + https://poynton.ca/ColorFAQ.html and + https://www.cambridgeincolour.com/tutorials/color-spaces.htm. + +The :mod:`colorsys` module defines the following functions: + + +.. function:: rgb_to_yiq(r, g, b) + + Convert the color from RGB coordinates to YIQ coordinates. + + +.. function:: yiq_to_rgb(y, i, q) + + Convert the color from YIQ coordinates to RGB coordinates. + + +.. function:: rgb_to_hls(r, g, b) + + Convert the color from RGB coordinates to HLS coordinates. + + +.. function:: hls_to_rgb(h, l, s) + + Convert the color from HLS coordinates to RGB coordinates. + + +.. function:: rgb_to_hsv(r, g, b) + + Convert the color from RGB coordinates to HSV coordinates. + + +.. function:: hsv_to_rgb(h, s, v) + + Convert the color from HSV coordinates to RGB coordinates. + +Example:: + + >>> import colorsys + >>> colorsys.rgb_to_hsv(0.2, 0.4, 0.4) + (0.5, 0.5, 0.4) + >>> colorsys.hsv_to_rgb(0.5, 0.5, 0.4) + (0.2, 0.4, 0.4) diff --git a/cpython_2/environment/repo/Doc/library/compileall.rst b/cpython_2/environment/repo/Doc/library/compileall.rst new file mode 100644 index 0000000000000000000000000000000000000000..01ab7461e9b1cbe121b02bb6547f0501f44fdea0 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/compileall.rst @@ -0,0 +1,334 @@ +:mod:`compileall` --- Byte-compile Python libraries +=================================================== + +.. module:: compileall + :synopsis: Tools for byte-compiling all Python source files in a directory tree. + +**Source code:** :source:`Lib/compileall.py` + +-------------- + +This module provides some utility functions to support installing Python +libraries. These functions compile Python source files in a directory tree. +This module can be used to create the cached byte-code files at library +installation time, which makes them available for use even by users who don't +have write permission to the library directories. + + +Command-line use +---------------- + +This module can work as a script (using :program:`python -m compileall`) to +compile Python sources. + +.. program:: compileall + +.. cmdoption:: directory ... + file ... + + Positional arguments are files to compile or directories that contain + source files, traversed recursively. If no argument is given, behave as if + the command line was ``-l ``. + +.. cmdoption:: -l + + Do not recurse into subdirectories, only compile source code files directly + contained in the named or implied directories. + +.. cmdoption:: -f + + Force rebuild even if timestamps are up-to-date. + +.. cmdoption:: -q + + Do not print the list of files compiled. If passed once, error messages will + still be printed. If passed twice (``-qq``), all output is suppressed. + +.. cmdoption:: -d destdir + + Directory prepended to the path to each file being compiled. This will + appear in compilation time tracebacks, and is also compiled in to the + byte-code file, where it will be used in tracebacks and other messages in + cases where the source file does not exist at the time the byte-code file is + executed. + +.. cmdoption:: -s strip_prefix +.. cmdoption:: -p prepend_prefix + + Remove (``-s``) or append (``-p``) the given prefix of paths + recorded in the ``.pyc`` files. + Cannot be combined with ``-d``. + +.. cmdoption:: -x regex + + regex is used to search the full path to each file considered for + compilation, and if the regex produces a match, the file is skipped. + +.. cmdoption:: -i list + + Read the file ``list`` and add each line that it contains to the list of + files and directories to compile. If ``list`` is ``-``, read lines from + ``stdin``. + +.. cmdoption:: -b + + Write the byte-code files to their legacy locations and names, which may + overwrite byte-code files created by another version of Python. The default + is to write files to their :pep:`3147` locations and names, which allows + byte-code files from multiple versions of Python to coexist. + +.. cmdoption:: -r + + Control the maximum recursion level for subdirectories. + If this is given, then ``-l`` option will not be taken into account. + :program:`python -m compileall -r 0` is equivalent to + :program:`python -m compileall -l`. + +.. cmdoption:: -j N + + Use *N* workers to compile the files within the given directory. + If ``0`` is used, then the result of :func:`os.cpu_count()` + will be used. + +.. cmdoption:: --invalidation-mode [timestamp|checked-hash|unchecked-hash] + + Control how the generated byte-code files are invalidated at runtime. + The ``timestamp`` value, means that ``.pyc`` files with the source timestamp + and size embedded will be generated. The ``checked-hash`` and + ``unchecked-hash`` values cause hash-based pycs to be generated. Hash-based + pycs embed a hash of the source file contents rather than a timestamp. See + :ref:`pyc-invalidation` for more information on how Python validates + bytecode cache files at runtime. + The default is ``timestamp`` if the :envvar:`SOURCE_DATE_EPOCH` environment + variable is not set, and ``checked-hash`` if the ``SOURCE_DATE_EPOCH`` + environment variable is set. + +.. cmdoption:: -o level + + Compile with the given optimization level. May be used multiple times + to compile for multiple levels at a time (for example, + ``compileall -o 1 -o 2``). + +.. cmdoption:: -e dir + + Ignore symlinks pointing outside the given directory. + +.. cmdoption:: --hardlink-dupes + + If two ``.pyc`` files with different optimization level have + the same content, use hard links to consolidate duplicate files. + +.. versionchanged:: 3.2 + Added the ``-i``, ``-b`` and ``-h`` options. + +.. versionchanged:: 3.5 + Added the ``-j``, ``-r``, and ``-qq`` options. ``-q`` option + was changed to a multilevel value. ``-b`` will always produce a + byte-code file ending in ``.pyc``, never ``.pyo``. + +.. versionchanged:: 3.7 + Added the ``--invalidation-mode`` option. + +.. versionchanged:: 3.9 + Added the ``-s``, ``-p``, ``-e`` and ``--hardlink-dupes`` options. + Raised the default recursion limit from 10 to + :py:func:`sys.getrecursionlimit()`. + Added the possibility to specify the ``-o`` option multiple times. + + +There is no command-line option to control the optimization level used by the +:func:`compile` function, because the Python interpreter itself already +provides the option: :program:`python -O -m compileall`. + +Similarly, the :func:`compile` function respects the :attr:`sys.pycache_prefix` +setting. The generated bytecode cache will only be useful if :func:`compile` is +run with the same :attr:`sys.pycache_prefix` (if any) that will be used at +runtime. + +Public functions +---------------- + +.. function:: compile_dir(dir, maxlevels=sys.getrecursionlimit(), ddir=None, force=False, rx=None, quiet=0, legacy=False, optimize=-1, workers=1, invalidation_mode=None, \*, stripdir=None, prependdir=None, limit_sl_dest=None, hardlink_dupes=False) + + Recursively descend the directory tree named by *dir*, compiling all :file:`.py` + files along the way. Return a true value if all the files compiled successfully, + and a false value otherwise. + + The *maxlevels* parameter is used to limit the depth of the recursion; it + defaults to ``sys.getrecursionlimit()``. + + If *ddir* is given, it is prepended to the path to each file being compiled + for use in compilation time tracebacks, and is also compiled in to the + byte-code file, where it will be used in tracebacks and other messages in + cases where the source file does not exist at the time the byte-code file is + executed. + + If *force* is true, modules are re-compiled even if the timestamps are up to + date. + + If *rx* is given, its search method is called on the complete path to each + file considered for compilation, and if it returns a true value, the file + is skipped. + + If *quiet* is ``False`` or ``0`` (the default), the filenames and other + information are printed to standard out. Set to ``1``, only errors are + printed. Set to ``2``, all output is suppressed. + + If *legacy* is true, byte-code files are written to their legacy locations + and names, which may overwrite byte-code files created by another version of + Python. The default is to write files to their :pep:`3147` locations and + names, which allows byte-code files from multiple versions of Python to + coexist. + + *optimize* specifies the optimization level for the compiler. It is passed to + the built-in :func:`compile` function. + + The argument *workers* specifies how many workers are used to + compile files in parallel. The default is to not use multiple workers. + If the platform can't use multiple workers and *workers* argument is given, + then sequential compilation will be used as a fallback. If *workers* + is 0, the number of cores in the system is used. If *workers* is + lower than ``0``, a :exc:`ValueError` will be raised. + + *invalidation_mode* should be a member of the + :class:`py_compile.PycInvalidationMode` enum and controls how the generated + pycs are invalidated at runtime. + + The *stripdir*, *prependdir* and *limit_sl_dest* arguments correspond to + the ``-s``, ``-p`` and ``-e`` options described above. + They may be specified as ``str``, ``bytes`` or :py:class:`os.PathLike`. + + If *hardlink_dupes* is true and two ``.pyc`` files with different optimization + level have the same content, use hard links to consolidate duplicate files. + + .. versionchanged:: 3.2 + Added the *legacy* and *optimize* parameter. + + .. versionchanged:: 3.5 + Added the *workers* parameter. + + .. versionchanged:: 3.5 + *quiet* parameter was changed to a multilevel value. + + .. versionchanged:: 3.5 + The *legacy* parameter only writes out ``.pyc`` files, not ``.pyo`` files + no matter what the value of *optimize* is. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + .. versionchanged:: 3.7 + The *invalidation_mode* parameter was added. + + .. versionchanged:: 3.7.2 + The *invalidation_mode* parameter's default value is updated to None. + + .. versionchanged:: 3.8 + Setting *workers* to 0 now chooses the optimal number of cores. + + .. versionchanged:: 3.9 + Added *stripdir*, *prependdir*, *limit_sl_dest* and *hardlink_dupes* arguments. + Default value of *maxlevels* was changed from ``10`` to ``sys.getrecursionlimit()`` + +.. function:: compile_file(fullname, ddir=None, force=False, rx=None, quiet=0, legacy=False, optimize=-1, invalidation_mode=None, \*, stripdir=None, prependdir=None, limit_sl_dest=None, hardlink_dupes=False) + + Compile the file with path *fullname*. Return a true value if the file + compiled successfully, and a false value otherwise. + + If *ddir* is given, it is prepended to the path to the file being compiled + for use in compilation time tracebacks, and is also compiled in to the + byte-code file, where it will be used in tracebacks and other messages in + cases where the source file does not exist at the time the byte-code file is + executed. + + If *rx* is given, its search method is passed the full path name to the + file being compiled, and if it returns a true value, the file is not + compiled and ``True`` is returned. + + If *quiet* is ``False`` or ``0`` (the default), the filenames and other + information are printed to standard out. Set to ``1``, only errors are + printed. Set to ``2``, all output is suppressed. + + If *legacy* is true, byte-code files are written to their legacy locations + and names, which may overwrite byte-code files created by another version of + Python. The default is to write files to their :pep:`3147` locations and + names, which allows byte-code files from multiple versions of Python to + coexist. + + *optimize* specifies the optimization level for the compiler. It is passed to + the built-in :func:`compile` function. + + *invalidation_mode* should be a member of the + :class:`py_compile.PycInvalidationMode` enum and controls how the generated + pycs are invalidated at runtime. + + The *stripdir*, *prependdir* and *limit_sl_dest* arguments correspond to + the ``-s``, ``-p`` and ``-e`` options described above. + They may be specified as ``str``, ``bytes`` or :py:class:`os.PathLike`. + + If *hardlink_dupes* is true and two ``.pyc`` files with different optimization + level have the same content, use hard links to consolidate duplicate files. + + .. versionadded:: 3.2 + + .. versionchanged:: 3.5 + *quiet* parameter was changed to a multilevel value. + + .. versionchanged:: 3.5 + The *legacy* parameter only writes out ``.pyc`` files, not ``.pyo`` files + no matter what the value of *optimize* is. + + .. versionchanged:: 3.7 + The *invalidation_mode* parameter was added. + + .. versionchanged:: 3.7.2 + The *invalidation_mode* parameter's default value is updated to None. + + .. versionchanged:: 3.9 + Added *stripdir*, *prependdir*, *limit_sl_dest* and *hardlink_dupes* arguments. + +.. function:: compile_path(skip_curdir=True, maxlevels=0, force=False, quiet=0, legacy=False, optimize=-1, invalidation_mode=None) + + Byte-compile all the :file:`.py` files found along ``sys.path``. Return a + true value if all the files compiled successfully, and a false value otherwise. + + If *skip_curdir* is true (the default), the current directory is not included + in the search. All other parameters are passed to the :func:`compile_dir` + function. Note that unlike the other compile functions, ``maxlevels`` + defaults to ``0``. + + .. versionchanged:: 3.2 + Added the *legacy* and *optimize* parameter. + + .. versionchanged:: 3.5 + *quiet* parameter was changed to a multilevel value. + + .. versionchanged:: 3.5 + The *legacy* parameter only writes out ``.pyc`` files, not ``.pyo`` files + no matter what the value of *optimize* is. + + .. versionchanged:: 3.7 + The *invalidation_mode* parameter was added. + + .. versionchanged:: 3.7.2 + The *invalidation_mode* parameter's default value is updated to None. + +To force a recompile of all the :file:`.py` files in the :file:`Lib/` +subdirectory and all its subdirectories:: + + import compileall + + compileall.compile_dir('Lib/', force=True) + + # Perform same compilation, excluding files in .svn directories. + import re + compileall.compile_dir('Lib/', rx=re.compile(r'[/\\][.]svn'), force=True) + + # pathlib.Path objects can also be used. + import pathlib + compileall.compile_dir(pathlib.Path('Lib/'), force=True) + +.. seealso:: + + Module :mod:`py_compile` + Byte-compile a single source file. diff --git a/cpython_2/environment/repo/Doc/library/concurrency.rst b/cpython_2/environment/repo/Doc/library/concurrency.rst new file mode 100644 index 0000000000000000000000000000000000000000..b150990b83b75b4b20ee1882d0244f5678dbc203 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/concurrency.rst @@ -0,0 +1,30 @@ +.. _concurrency: + +******************** +Concurrent Execution +******************** + +The modules described in this chapter provide support for concurrent +execution of code. The appropriate choice of tool will depend on the +task to be executed (CPU bound vs IO bound) and preferred style of +development (event driven cooperative multitasking vs preemptive +multitasking). Here's an overview: + + +.. toctree:: + + threading.rst + multiprocessing.rst + multiprocessing.shared_memory.rst + concurrent.rst + concurrent.futures.rst + subprocess.rst + sched.rst + queue.rst + + +The following are support modules for some of the above services: + +.. toctree:: + + _thread.rst diff --git a/cpython_2/environment/repo/Doc/library/concurrent.futures.rst b/cpython_2/environment/repo/Doc/library/concurrent.futures.rst new file mode 100644 index 0000000000000000000000000000000000000000..b21d5594c84fa026a23a060f4b714c46e89ca2d5 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/concurrent.futures.rst @@ -0,0 +1,535 @@ +:mod:`concurrent.futures` --- Launching parallel tasks +====================================================== + +.. module:: concurrent.futures + :synopsis: Execute computations concurrently using threads or processes. + +.. versionadded:: 3.2 + +**Source code:** :source:`Lib/concurrent/futures/thread.py` +and :source:`Lib/concurrent/futures/process.py` + +-------------- + +The :mod:`concurrent.futures` module provides a high-level interface for +asynchronously executing callables. + +The asynchronous execution can be performed with threads, using +:class:`ThreadPoolExecutor`, or separate processes, using +:class:`ProcessPoolExecutor`. Both implement the same interface, which is +defined by the abstract :class:`Executor` class. + + +Executor Objects +---------------- + +.. class:: Executor + + An abstract class that provides methods to execute calls asynchronously. It + should not be used directly, but through its concrete subclasses. + + .. method:: submit(fn, /, *args, **kwargs) + + Schedules the callable, *fn*, to be executed as ``fn(*args **kwargs)`` + and returns a :class:`Future` object representing the execution of the + callable. :: + + with ThreadPoolExecutor(max_workers=1) as executor: + future = executor.submit(pow, 323, 1235) + print(future.result()) + + .. method:: map(func, *iterables, timeout=None, chunksize=1) + + Similar to :func:`map(func, *iterables) ` except: + + * the *iterables* are collected immediately rather than lazily; + + * *func* is executed asynchronously and several calls to + *func* may be made concurrently. + + The returned iterator raises a :exc:`concurrent.futures.TimeoutError` + if :meth:`~iterator.__next__` is called and the result isn't available + after *timeout* seconds from the original call to :meth:`Executor.map`. + *timeout* can be an int or a float. If *timeout* is not specified or + ``None``, there is no limit to the wait time. + + If a *func* call raises an exception, then that exception will be + raised when its value is retrieved from the iterator. + + When using :class:`ProcessPoolExecutor`, this method chops *iterables* + into a number of chunks which it submits to the pool as separate + tasks. The (approximate) size of these chunks can be specified by + setting *chunksize* to a positive integer. For very long iterables, + using a large value for *chunksize* can significantly improve + performance compared to the default size of 1. With + :class:`ThreadPoolExecutor`, *chunksize* has no effect. + + .. versionchanged:: 3.5 + Added the *chunksize* argument. + + .. method:: shutdown(wait=True, \*, cancel_futures=False) + + Signal the executor that it should free any resources that it is using + when the currently pending futures are done executing. Calls to + :meth:`Executor.submit` and :meth:`Executor.map` made after shutdown will + raise :exc:`RuntimeError`. + + If *wait* is ``True`` then this method will not return until all the + pending futures are done executing and the resources associated with the + executor have been freed. If *wait* is ``False`` then this method will + return immediately and the resources associated with the executor will be + freed when all pending futures are done executing. Regardless of the + value of *wait*, the entire Python program will not exit until all + pending futures are done executing. + + If *cancel_futures* is ``True``, this method will cancel all pending + futures that the executor has not started running. Any futures that + are completed or running won't be cancelled, regardless of the value + of *cancel_futures*. + + If both *cancel_futures* and *wait* are ``True``, all futures that the + executor has started running will be completed prior to this method + returning. The remaining futures are cancelled. + + You can avoid having to call this method explicitly if you use the + :keyword:`with` statement, which will shutdown the :class:`Executor` + (waiting as if :meth:`Executor.shutdown` were called with *wait* set to + ``True``):: + + import shutil + with ThreadPoolExecutor(max_workers=4) as e: + e.submit(shutil.copy, 'src1.txt', 'dest1.txt') + e.submit(shutil.copy, 'src2.txt', 'dest2.txt') + e.submit(shutil.copy, 'src3.txt', 'dest3.txt') + e.submit(shutil.copy, 'src4.txt', 'dest4.txt') + + .. versionchanged:: 3.9 + Added *cancel_futures*. + + +ThreadPoolExecutor +------------------ + +:class:`ThreadPoolExecutor` is an :class:`Executor` subclass that uses a pool of +threads to execute calls asynchronously. + +Deadlocks can occur when the callable associated with a :class:`Future` waits on +the results of another :class:`Future`. For example:: + + import time + def wait_on_b(): + time.sleep(5) + print(b.result()) # b will never complete because it is waiting on a. + return 5 + + def wait_on_a(): + time.sleep(5) + print(a.result()) # a will never complete because it is waiting on b. + return 6 + + + executor = ThreadPoolExecutor(max_workers=2) + a = executor.submit(wait_on_b) + b = executor.submit(wait_on_a) + +And:: + + def wait_on_future(): + f = executor.submit(pow, 5, 2) + # This will never complete because there is only one worker thread and + # it is executing this function. + print(f.result()) + + executor = ThreadPoolExecutor(max_workers=1) + executor.submit(wait_on_future) + + +.. class:: ThreadPoolExecutor(max_workers=None, thread_name_prefix='', initializer=None, initargs=()) + + An :class:`Executor` subclass that uses a pool of at most *max_workers* + threads to execute calls asynchronously. + + *initializer* is an optional callable that is called at the start of + each worker thread; *initargs* is a tuple of arguments passed to the + initializer. Should *initializer* raise an exception, all currently + pending jobs will raise a :exc:`~concurrent.futures.thread.BrokenThreadPool`, + as well as any attempt to submit more jobs to the pool. + + .. versionchanged:: 3.5 + If *max_workers* is ``None`` or + not given, it will default to the number of processors on the machine, + multiplied by ``5``, assuming that :class:`ThreadPoolExecutor` is often + used to overlap I/O instead of CPU work and the number of workers + should be higher than the number of workers + for :class:`ProcessPoolExecutor`. + + .. versionadded:: 3.6 + The *thread_name_prefix* argument was added to allow users to + control the :class:`threading.Thread` names for worker threads created by + the pool for easier debugging. + + .. versionchanged:: 3.7 + Added the *initializer* and *initargs* arguments. + + .. versionchanged:: 3.8 + Default value of *max_workers* is changed to ``min(32, os.cpu_count() + 4)``. + This default value preserves at least 5 workers for I/O bound tasks. + It utilizes at most 32 CPU cores for CPU bound tasks which release the GIL. + And it avoids using very large resources implicitly on many-core machines. + + ThreadPoolExecutor now reuses idle worker threads before starting + *max_workers* worker threads too. + + +.. _threadpoolexecutor-example: + +ThreadPoolExecutor Example +~~~~~~~~~~~~~~~~~~~~~~~~~~ +:: + + import concurrent.futures + import urllib.request + + URLS = ['http://www.foxnews.com/', + 'http://www.cnn.com/', + 'http://europe.wsj.com/', + 'http://www.bbc.co.uk/', + 'http://some-made-up-domain.com/'] + + # Retrieve a single page and report the URL and contents + def load_url(url, timeout): + with urllib.request.urlopen(url, timeout=timeout) as conn: + return conn.read() + + # We can use a with statement to ensure threads are cleaned up promptly + with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor: + # Start the load operations and mark each future with its URL + future_to_url = {executor.submit(load_url, url, 60): url for url in URLS} + for future in concurrent.futures.as_completed(future_to_url): + url = future_to_url[future] + try: + data = future.result() + except Exception as exc: + print('%r generated an exception: %s' % (url, exc)) + else: + print('%r page is %d bytes' % (url, len(data))) + + +ProcessPoolExecutor +------------------- + +The :class:`ProcessPoolExecutor` class is an :class:`Executor` subclass that +uses a pool of processes to execute calls asynchronously. +:class:`ProcessPoolExecutor` uses the :mod:`multiprocessing` module, which +allows it to side-step the :term:`Global Interpreter Lock` but also means that +only picklable objects can be executed and returned. + +The ``__main__`` module must be importable by worker subprocesses. This means +that :class:`ProcessPoolExecutor` will not work in the interactive interpreter. + +Calling :class:`Executor` or :class:`Future` methods from a callable submitted +to a :class:`ProcessPoolExecutor` will result in deadlock. + +.. class:: ProcessPoolExecutor(max_workers=None, mp_context=None, initializer=None, initargs=()) + + An :class:`Executor` subclass that executes calls asynchronously using a pool + of at most *max_workers* processes. If *max_workers* is ``None`` or not + given, it will default to the number of processors on the machine. + If *max_workers* is lower or equal to ``0``, then a :exc:`ValueError` + will be raised. + On Windows, *max_workers* must be equal or lower than ``61``. If it is not + then :exc:`ValueError` will be raised. If *max_workers* is ``None``, then + the default chosen will be at most ``61``, even if more processors are + available. + *mp_context* can be a multiprocessing context or None. It will be used to + launch the workers. If *mp_context* is ``None`` or not given, the default + multiprocessing context is used. + + *initializer* is an optional callable that is called at the start of + each worker process; *initargs* is a tuple of arguments passed to the + initializer. Should *initializer* raise an exception, all currently + pending jobs will raise a :exc:`~concurrent.futures.process.BrokenProcessPool`, + as well any attempt to submit more jobs to the pool. + + .. versionchanged:: 3.3 + When one of the worker processes terminates abruptly, a + :exc:`BrokenProcessPool` error is now raised. Previously, behaviour + was undefined but operations on the executor or its futures would often + freeze or deadlock. + + .. versionchanged:: 3.7 + The *mp_context* argument was added to allow users to control the + start_method for worker processes created by the pool. + + Added the *initializer* and *initargs* arguments. + + +.. _processpoolexecutor-example: + +ProcessPoolExecutor Example +~~~~~~~~~~~~~~~~~~~~~~~~~~~ +:: + + import concurrent.futures + import math + + PRIMES = [ + 112272535095293, + 112582705942171, + 112272535095293, + 115280095190773, + 115797848077099, + 1099726899285419] + + def is_prime(n): + if n < 2: + return False + if n == 2: + return True + if n % 2 == 0: + return False + + sqrt_n = int(math.floor(math.sqrt(n))) + for i in range(3, sqrt_n + 1, 2): + if n % i == 0: + return False + return True + + def main(): + with concurrent.futures.ProcessPoolExecutor() as executor: + for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)): + print('%d is prime: %s' % (number, prime)) + + if __name__ == '__main__': + main() + + +Future Objects +-------------- + +The :class:`Future` class encapsulates the asynchronous execution of a callable. +:class:`Future` instances are created by :meth:`Executor.submit`. + +.. class:: Future + + Encapsulates the asynchronous execution of a callable. :class:`Future` + instances are created by :meth:`Executor.submit` and should not be created + directly except for testing. + + .. method:: cancel() + + Attempt to cancel the call. If the call is currently being executed or + finished running and cannot be cancelled then the method will return + ``False``, otherwise the call will be cancelled and the method will + return ``True``. + + .. method:: cancelled() + + Return ``True`` if the call was successfully cancelled. + + .. method:: running() + + Return ``True`` if the call is currently being executed and cannot be + cancelled. + + .. method:: done() + + Return ``True`` if the call was successfully cancelled or finished + running. + + .. method:: result(timeout=None) + + Return the value returned by the call. If the call hasn't yet completed + then this method will wait up to *timeout* seconds. If the call hasn't + completed in *timeout* seconds, then a + :exc:`concurrent.futures.TimeoutError` will be raised. *timeout* can be + an int or float. If *timeout* is not specified or ``None``, there is no + limit to the wait time. + + If the future is cancelled before completing then :exc:`.CancelledError` + will be raised. + + If the call raised, this method will raise the same exception. + + .. method:: exception(timeout=None) + + Return the exception raised by the call. If the call hasn't yet + completed then this method will wait up to *timeout* seconds. If the + call hasn't completed in *timeout* seconds, then a + :exc:`concurrent.futures.TimeoutError` will be raised. *timeout* can be + an int or float. If *timeout* is not specified or ``None``, there is no + limit to the wait time. + + If the future is cancelled before completing then :exc:`.CancelledError` + will be raised. + + If the call completed without raising, ``None`` is returned. + + .. method:: add_done_callback(fn) + + Attaches the callable *fn* to the future. *fn* will be called, with the + future as its only argument, when the future is cancelled or finishes + running. + + Added callables are called in the order that they were added and are + always called in a thread belonging to the process that added them. If + the callable raises an :exc:`Exception` subclass, it will be logged and + ignored. If the callable raises a :exc:`BaseException` subclass, the + behavior is undefined. + + If the future has already completed or been cancelled, *fn* will be + called immediately. + + The following :class:`Future` methods are meant for use in unit tests and + :class:`Executor` implementations. + + .. method:: set_running_or_notify_cancel() + + This method should only be called by :class:`Executor` implementations + before executing the work associated with the :class:`Future` and by unit + tests. + + If the method returns ``False`` then the :class:`Future` was cancelled, + i.e. :meth:`Future.cancel` was called and returned `True`. Any threads + waiting on the :class:`Future` completing (i.e. through + :func:`as_completed` or :func:`wait`) will be woken up. + + If the method returns ``True`` then the :class:`Future` was not cancelled + and has been put in the running state, i.e. calls to + :meth:`Future.running` will return `True`. + + This method can only be called once and cannot be called after + :meth:`Future.set_result` or :meth:`Future.set_exception` have been + called. + + .. method:: set_result(result) + + Sets the result of the work associated with the :class:`Future` to + *result*. + + This method should only be used by :class:`Executor` implementations and + unit tests. + + .. versionchanged:: 3.8 + This method raises + :exc:`concurrent.futures.InvalidStateError` if the :class:`Future` is + already done. + + .. method:: set_exception(exception) + + Sets the result of the work associated with the :class:`Future` to the + :class:`Exception` *exception*. + + This method should only be used by :class:`Executor` implementations and + unit tests. + + .. versionchanged:: 3.8 + This method raises + :exc:`concurrent.futures.InvalidStateError` if the :class:`Future` is + already done. + +Module Functions +---------------- + +.. function:: wait(fs, timeout=None, return_when=ALL_COMPLETED) + + Wait for the :class:`Future` instances (possibly created by different + :class:`Executor` instances) given by *fs* to complete. Returns a named + 2-tuple of sets. The first set, named ``done``, contains the futures that + completed (finished or cancelled futures) before the wait completed. The + second set, named ``not_done``, contains the futures that did not complete + (pending or running futures). + + *timeout* can be used to control the maximum number of seconds to wait before + returning. *timeout* can be an int or float. If *timeout* is not specified + or ``None``, there is no limit to the wait time. + + *return_when* indicates when this function should return. It must be one of + the following constants: + + .. tabularcolumns:: |l|L| + + +-----------------------------+----------------------------------------+ + | Constant | Description | + +=============================+========================================+ + | :const:`FIRST_COMPLETED` | The function will return when any | + | | future finishes or is cancelled. | + +-----------------------------+----------------------------------------+ + | :const:`FIRST_EXCEPTION` | The function will return when any | + | | future finishes by raising an | + | | exception. If no future raises an | + | | exception then it is equivalent to | + | | :const:`ALL_COMPLETED`. | + +-----------------------------+----------------------------------------+ + | :const:`ALL_COMPLETED` | The function will return when all | + | | futures finish or are cancelled. | + +-----------------------------+----------------------------------------+ + +.. function:: as_completed(fs, timeout=None) + + Returns an iterator over the :class:`Future` instances (possibly created by + different :class:`Executor` instances) given by *fs* that yields futures as + they complete (finished or cancelled futures). Any futures given by *fs* that + are duplicated will be returned once. Any futures that completed before + :func:`as_completed` is called will be yielded first. The returned iterator + raises a :exc:`concurrent.futures.TimeoutError` if :meth:`~iterator.__next__` + is called and the result isn't available after *timeout* seconds from the + original call to :func:`as_completed`. *timeout* can be an int or float. If + *timeout* is not specified or ``None``, there is no limit to the wait time. + + +.. seealso:: + + :pep:`3148` -- futures - execute computations asynchronously + The proposal which described this feature for inclusion in the Python + standard library. + + +Exception classes +----------------- + +.. currentmodule:: concurrent.futures + +.. exception:: CancelledError + + Raised when a future is cancelled. + +.. exception:: TimeoutError + + Raised when a future operation exceeds the given timeout. + +.. exception:: BrokenExecutor + + Derived from :exc:`RuntimeError`, this exception class is raised + when an executor is broken for some reason, and cannot be used + to submit or execute new tasks. + + .. versionadded:: 3.7 + +.. exception:: InvalidStateError + + Raised when an operation is performed on a future that is not allowed + in the current state. + + .. versionadded:: 3.8 + +.. currentmodule:: concurrent.futures.thread + +.. exception:: BrokenThreadPool + + Derived from :exc:`~concurrent.futures.BrokenExecutor`, this exception + class is raised when one of the workers of a :class:`ThreadPoolExecutor` + has failed initializing. + + .. versionadded:: 3.7 + +.. currentmodule:: concurrent.futures.process + +.. exception:: BrokenProcessPool + + Derived from :exc:`~concurrent.futures.BrokenExecutor` (formerly + :exc:`RuntimeError`), this exception class is raised when one of the + workers of a :class:`ProcessPoolExecutor` has terminated in a non-clean + fashion (for example, if it was killed from the outside). + + .. versionadded:: 3.3 diff --git a/cpython_2/environment/repo/Doc/library/concurrent.rst b/cpython_2/environment/repo/Doc/library/concurrent.rst new file mode 100644 index 0000000000000000000000000000000000000000..2eba5365125805d6a03afd4c3f65517c14486979 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/concurrent.rst @@ -0,0 +1,6 @@ +The :mod:`concurrent` package +============================= + +Currently, there is only one module in this package: + +* :mod:`concurrent.futures` -- Launching parallel tasks diff --git a/cpython_2/environment/repo/Doc/library/configparser.rst b/cpython_2/environment/repo/Doc/library/configparser.rst new file mode 100644 index 0000000000000000000000000000000000000000..739477f55fddda8f3bd27ac49760552d3b13f7ea --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/configparser.rst @@ -0,0 +1,1330 @@ +:mod:`configparser` --- Configuration file parser +================================================= + +.. module:: configparser + :synopsis: Configuration file parser. + +.. moduleauthor:: Ken Manheimer +.. moduleauthor:: Barry Warsaw +.. moduleauthor:: Eric S. Raymond +.. moduleauthor:: Łukasz Langa +.. sectionauthor:: Christopher G. Petrilli +.. sectionauthor:: Łukasz Langa + +**Source code:** :source:`Lib/configparser.py` + +.. index:: + pair: .ini; file + pair: configuration; file + single: ini file + single: Windows ini file + +-------------- + +This module provides the :class:`ConfigParser` class which implements a basic +configuration language which provides a structure similar to what's found in +Microsoft Windows INI files. You can use this to write Python programs which +can be customized by end users easily. + +.. note:: + + This library does *not* interpret or write the value-type prefixes used in + the Windows Registry extended version of INI syntax. + +.. seealso:: + + Module :mod:`shlex` + Support for creating Unix shell-like mini-languages which can be used as + an alternate format for application configuration files. + + Module :mod:`json` + The json module implements a subset of JavaScript syntax which can also + be used for this purpose. + + +.. testsetup:: + + import configparser + + +Quick Start +----------- + +Let's take a very basic configuration file that looks like this: + +.. code-block:: ini + + [DEFAULT] + ServerAliveInterval = 45 + Compression = yes + CompressionLevel = 9 + ForwardX11 = yes + + [bitbucket.org] + User = hg + + [topsecret.server.com] + Port = 50022 + ForwardX11 = no + +The structure of INI files is described `in the following section +<#supported-ini-file-structure>`_. Essentially, the file +consists of sections, each of which contains keys with values. +:mod:`configparser` classes can read and write such files. Let's start by +creating the above configuration file programmatically. + +.. doctest:: + + >>> import configparser + >>> config = configparser.ConfigParser() + >>> config['DEFAULT'] = {'ServerAliveInterval': '45', + ... 'Compression': 'yes', + ... 'CompressionLevel': '9'} + >>> config['bitbucket.org'] = {} + >>> config['bitbucket.org']['User'] = 'hg' + >>> config['topsecret.server.com'] = {} + >>> topsecret = config['topsecret.server.com'] + >>> topsecret['Port'] = '50022' # mutates the parser + >>> topsecret['ForwardX11'] = 'no' # same here + >>> config['DEFAULT']['ForwardX11'] = 'yes' + >>> with open('example.ini', 'w') as configfile: + ... config.write(configfile) + ... + +As you can see, we can treat a config parser much like a dictionary. +There are differences, `outlined later <#mapping-protocol-access>`_, but +the behavior is very close to what you would expect from a dictionary. + +Now that we have created and saved a configuration file, let's read it +back and explore the data it holds. + +.. doctest:: + + >>> config = configparser.ConfigParser() + >>> config.sections() + [] + >>> config.read('example.ini') + ['example.ini'] + >>> config.sections() + ['bitbucket.org', 'topsecret.server.com'] + >>> 'bitbucket.org' in config + True + >>> 'bytebong.com' in config + False + >>> config['bitbucket.org']['User'] + 'hg' + >>> config['DEFAULT']['Compression'] + 'yes' + >>> topsecret = config['topsecret.server.com'] + >>> topsecret['ForwardX11'] + 'no' + >>> topsecret['Port'] + '50022' + >>> for key in config['bitbucket.org']: # doctest: +SKIP + ... print(key) + user + compressionlevel + serveraliveinterval + compression + forwardx11 + >>> config['bitbucket.org']['ForwardX11'] + 'yes' + +As we can see above, the API is pretty straightforward. The only bit of magic +involves the ``DEFAULT`` section which provides default values for all other +sections [1]_. Note also that keys in sections are +case-insensitive and stored in lowercase [1]_. + + +Supported Datatypes +------------------- + +Config parsers do not guess datatypes of values in configuration files, always +storing them internally as strings. This means that if you need other +datatypes, you should convert on your own: + +.. doctest:: + + >>> int(topsecret['Port']) + 50022 + >>> float(topsecret['CompressionLevel']) + 9.0 + +Since this task is so common, config parsers provide a range of handy getter +methods to handle integers, floats and booleans. The last one is the most +interesting because simply passing the value to ``bool()`` would do no good +since ``bool('False')`` is still ``True``. This is why config parsers also +provide :meth:`~ConfigParser.getboolean`. This method is case-insensitive and +recognizes Boolean values from ``'yes'``/``'no'``, ``'on'``/``'off'``, +``'true'``/``'false'`` and ``'1'``/``'0'`` [1]_. For example: + +.. doctest:: + + >>> topsecret.getboolean('ForwardX11') + False + >>> config['bitbucket.org'].getboolean('ForwardX11') + True + >>> config.getboolean('bitbucket.org', 'Compression') + True + +Apart from :meth:`~ConfigParser.getboolean`, config parsers also +provide equivalent :meth:`~ConfigParser.getint` and +:meth:`~ConfigParser.getfloat` methods. You can register your own +converters and customize the provided ones. [1]_ + +Fallback Values +--------------- + +As with a dictionary, you can use a section's :meth:`get` method to +provide fallback values: + +.. doctest:: + + >>> topsecret.get('Port') + '50022' + >>> topsecret.get('CompressionLevel') + '9' + >>> topsecret.get('Cipher') + >>> topsecret.get('Cipher', '3des-cbc') + '3des-cbc' + +Please note that default values have precedence over fallback values. +For instance, in our example the ``'CompressionLevel'`` key was +specified only in the ``'DEFAULT'`` section. If we try to get it from +the section ``'topsecret.server.com'``, we will always get the default, +even if we specify a fallback: + +.. doctest:: + + >>> topsecret.get('CompressionLevel', '3') + '9' + +One more thing to be aware of is that the parser-level :meth:`get` method +provides a custom, more complex interface, maintained for backwards +compatibility. When using this method, a fallback value can be provided via +the ``fallback`` keyword-only argument: + +.. doctest:: + + >>> config.get('bitbucket.org', 'monster', + ... fallback='No such things as monsters') + 'No such things as monsters' + +The same ``fallback`` argument can be used with the +:meth:`~ConfigParser.getint`, :meth:`~ConfigParser.getfloat` and +:meth:`~ConfigParser.getboolean` methods, for example: + +.. doctest:: + + >>> 'BatchMode' in topsecret + False + >>> topsecret.getboolean('BatchMode', fallback=True) + True + >>> config['DEFAULT']['BatchMode'] = 'no' + >>> topsecret.getboolean('BatchMode', fallback=True) + False + + +Supported INI File Structure +---------------------------- + +A configuration file consists of sections, each led by a ``[section]`` header, +followed by key/value entries separated by a specific string (``=`` or ``:`` by +default [1]_). By default, section names are case sensitive but keys are not +[1]_. Leading and trailing whitespace is removed from keys and values. +Values can be omitted, in which case the key/value delimiter may also be left +out. Values can also span multiple lines, as long as they are indented deeper +than the first line of the value. Depending on the parser's mode, blank lines +may be treated as parts of multiline values or ignored. + +Configuration files may include comments, prefixed by specific +characters (``#`` and ``;`` by default [1]_). Comments may appear on +their own on an otherwise empty line, possibly indented. [1]_ + +For example: + +.. code-block:: ini + + [Simple Values] + key=value + spaces in keys=allowed + spaces in values=allowed as well + spaces around the delimiter = obviously + you can also use : to delimit keys from values + + [All Values Are Strings] + values like this: 1000000 + or this: 3.14159265359 + are they treated as numbers? : no + integers, floats and booleans are held as: strings + can use the API to get converted values directly: true + + [Multiline Values] + chorus: I'm a lumberjack, and I'm okay + I sleep all night and I work all day + + [No Values] + key_without_value + empty string value here = + + [You can use comments] + # like this + ; or this + + # By default only in an empty line. + # Inline comments can be harmful because they prevent users + # from using the delimiting characters as parts of values. + # That being said, this can be customized. + + [Sections Can Be Indented] + can_values_be_as_well = True + does_that_mean_anything_special = False + purpose = formatting for readability + multiline_values = are + handled just fine as + long as they are indented + deeper than the first line + of a value + # Did I mention we can indent comments, too? + + +Interpolation of values +----------------------- + +On top of the core functionality, :class:`ConfigParser` supports +interpolation. This means values can be preprocessed before returning them +from ``get()`` calls. + +.. index:: single: % (percent); interpolation in configuration files + +.. class:: BasicInterpolation() + + The default implementation used by :class:`ConfigParser`. It enables + values to contain format strings which refer to other values in the same + section, or values in the special default section [1]_. Additional default + values can be provided on initialization. + + For example: + + .. code-block:: ini + + [Paths] + home_dir: /Users + my_dir: %(home_dir)s/lumberjack + my_pictures: %(my_dir)s/Pictures + + [Escape] + gain: 80%% # use a %% to escape the % sign (% is the only character that needs to be escaped) + + In the example above, :class:`ConfigParser` with *interpolation* set to + ``BasicInterpolation()`` would resolve ``%(home_dir)s`` to the value of + ``home_dir`` (``/Users`` in this case). ``%(my_dir)s`` in effect would + resolve to ``/Users/lumberjack``. All interpolations are done on demand so + keys used in the chain of references do not have to be specified in any + specific order in the configuration file. + + With ``interpolation`` set to ``None``, the parser would simply return + ``%(my_dir)s/Pictures`` as the value of ``my_pictures`` and + ``%(home_dir)s/lumberjack`` as the value of ``my_dir``. + +.. index:: single: $ (dollar); interpolation in configuration files + +.. class:: ExtendedInterpolation() + + An alternative handler for interpolation which implements a more advanced + syntax, used for instance in ``zc.buildout``. Extended interpolation is + using ``${section:option}`` to denote a value from a foreign section. + Interpolation can span multiple levels. For convenience, if the + ``section:`` part is omitted, interpolation defaults to the current section + (and possibly the default values from the special section). + + For example, the configuration specified above with basic interpolation, + would look like this with extended interpolation: + + .. code-block:: ini + + [Paths] + home_dir: /Users + my_dir: ${home_dir}/lumberjack + my_pictures: ${my_dir}/Pictures + + [Escape] + cost: $$80 # use a $$ to escape the $ sign ($ is the only character that needs to be escaped) + + Values from other sections can be fetched as well: + + .. code-block:: ini + + [Common] + home_dir: /Users + library_dir: /Library + system_dir: /System + macports_dir: /opt/local + + [Frameworks] + Python: 3.2 + path: ${Common:system_dir}/Library/Frameworks/ + + [Arthur] + nickname: Two Sheds + last_name: Jackson + my_dir: ${Common:home_dir}/twosheds + my_pictures: ${my_dir}/Pictures + python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python} + +Mapping Protocol Access +----------------------- + +.. versionadded:: 3.2 + +Mapping protocol access is a generic name for functionality that enables using +custom objects as if they were dictionaries. In case of :mod:`configparser`, +the mapping interface implementation is using the +``parser['section']['option']`` notation. + +``parser['section']`` in particular returns a proxy for the section's data in +the parser. This means that the values are not copied but they are taken from +the original parser on demand. What's even more important is that when values +are changed on a section proxy, they are actually mutated in the original +parser. + +:mod:`configparser` objects behave as close to actual dictionaries as possible. +The mapping interface is complete and adheres to the +:class:`~collections.abc.MutableMapping` ABC. +However, there are a few differences that should be taken into account: + +* By default, all keys in sections are accessible in a case-insensitive manner + [1]_. E.g. ``for option in parser["section"]`` yields only ``optionxform``'ed + option key names. This means lowercased keys by default. At the same time, + for a section that holds the key ``'a'``, both expressions return ``True``:: + + "a" in parser["section"] + "A" in parser["section"] + +* All sections include ``DEFAULTSECT`` values as well which means that + ``.clear()`` on a section may not leave the section visibly empty. This is + because default values cannot be deleted from the section (because technically + they are not there). If they are overridden in the section, deleting causes + the default value to be visible again. Trying to delete a default value + causes a :exc:`KeyError`. + +* ``DEFAULTSECT`` cannot be removed from the parser: + + * trying to delete it raises :exc:`ValueError`, + + * ``parser.clear()`` leaves it intact, + + * ``parser.popitem()`` never returns it. + +* ``parser.get(section, option, **kwargs)`` - the second argument is **not** + a fallback value. Note however that the section-level ``get()`` methods are + compatible both with the mapping protocol and the classic configparser API. + +* ``parser.items()`` is compatible with the mapping protocol (returns a list of + *section_name*, *section_proxy* pairs including the DEFAULTSECT). However, + this method can also be invoked with arguments: ``parser.items(section, raw, + vars)``. The latter call returns a list of *option*, *value* pairs for + a specified ``section``, with all interpolations expanded (unless + ``raw=True`` is provided). + +The mapping protocol is implemented on top of the existing legacy API so that +subclasses overriding the original interface still should have mappings working +as expected. + + +Customizing Parser Behaviour +---------------------------- + +There are nearly as many INI format variants as there are applications using it. +:mod:`configparser` goes a long way to provide support for the largest sensible +set of INI styles available. The default functionality is mainly dictated by +historical background and it's very likely that you will want to customize some +of the features. + +The most common way to change the way a specific config parser works is to use +the :meth:`__init__` options: + +* *defaults*, default value: ``None`` + + This option accepts a dictionary of key-value pairs which will be initially + put in the ``DEFAULT`` section. This makes for an elegant way to support + concise configuration files that don't specify values which are the same as + the documented default. + + Hint: if you want to specify default values for a specific section, use + :meth:`read_dict` before you read the actual file. + +* *dict_type*, default value: :class:`dict` + + This option has a major impact on how the mapping protocol will behave and how + the written configuration files look. With the standard dictionary, every + section is stored in the order they were added to the parser. Same goes for + options within sections. + + An alternative dictionary type can be used for example to sort sections and + options on write-back. + + Please note: there are ways to add a set of key-value pairs in a single + operation. When you use a regular dictionary in those operations, the order + of the keys will be ordered. For example: + + .. doctest:: + + >>> parser = configparser.ConfigParser() + >>> parser.read_dict({'section1': {'key1': 'value1', + ... 'key2': 'value2', + ... 'key3': 'value3'}, + ... 'section2': {'keyA': 'valueA', + ... 'keyB': 'valueB', + ... 'keyC': 'valueC'}, + ... 'section3': {'foo': 'x', + ... 'bar': 'y', + ... 'baz': 'z'} + ... }) + >>> parser.sections() + ['section1', 'section2', 'section3'] + >>> [option for option in parser['section3']] + ['foo', 'bar', 'baz'] + +* *allow_no_value*, default value: ``False`` + + Some configuration files are known to include settings without values, but + which otherwise conform to the syntax supported by :mod:`configparser`. The + *allow_no_value* parameter to the constructor can be used to + indicate that such values should be accepted: + + .. doctest:: + + >>> import configparser + + >>> sample_config = """ + ... [mysqld] + ... user = mysql + ... pid-file = /var/run/mysqld/mysqld.pid + ... skip-external-locking + ... old_passwords = 1 + ... skip-bdb + ... # we don't need ACID today + ... skip-innodb + ... """ + >>> config = configparser.ConfigParser(allow_no_value=True) + >>> config.read_string(sample_config) + + >>> # Settings with values are treated as before: + >>> config["mysqld"]["user"] + 'mysql' + + >>> # Settings without values provide None: + >>> config["mysqld"]["skip-bdb"] + + >>> # Settings which aren't specified still raise an error: + >>> config["mysqld"]["does-not-exist"] + Traceback (most recent call last): + ... + KeyError: 'does-not-exist' + +* *delimiters*, default value: ``('=', ':')`` + + Delimiters are substrings that delimit keys from values within a section. + The first occurrence of a delimiting substring on a line is considered + a delimiter. This means values (but not keys) can contain the delimiters. + + See also the *space_around_delimiters* argument to + :meth:`ConfigParser.write`. + +* *comment_prefixes*, default value: ``('#', ';')`` + +* *inline_comment_prefixes*, default value: ``None`` + + Comment prefixes are strings that indicate the start of a valid comment within + a config file. *comment_prefixes* are used only on otherwise empty lines + (optionally indented) whereas *inline_comment_prefixes* can be used after + every valid value (e.g. section names, options and empty lines as well). By + default inline comments are disabled and ``'#'`` and ``';'`` are used as + prefixes for whole line comments. + + .. versionchanged:: 3.2 + In previous versions of :mod:`configparser` behaviour matched + ``comment_prefixes=('#',';')`` and ``inline_comment_prefixes=(';',)``. + + Please note that config parsers don't support escaping of comment prefixes so + using *inline_comment_prefixes* may prevent users from specifying option + values with characters used as comment prefixes. When in doubt, avoid + setting *inline_comment_prefixes*. In any circumstances, the only way of + storing comment prefix characters at the beginning of a line in multiline + values is to interpolate the prefix, for example:: + + >>> from configparser import ConfigParser, ExtendedInterpolation + >>> parser = ConfigParser(interpolation=ExtendedInterpolation()) + >>> # the default BasicInterpolation could be used as well + >>> parser.read_string(""" + ... [DEFAULT] + ... hash = # + ... + ... [hashes] + ... shebang = + ... ${hash}!/usr/bin/env python + ... ${hash} -*- coding: utf-8 -*- + ... + ... extensions = + ... enabled_extension + ... another_extension + ... #disabled_by_comment + ... yet_another_extension + ... + ... interpolation not necessary = if # is not at line start + ... even in multiline values = line #1 + ... line #2 + ... line #3 + ... """) + >>> print(parser['hashes']['shebang']) + + #!/usr/bin/env python + # -*- coding: utf-8 -*- + >>> print(parser['hashes']['extensions']) + + enabled_extension + another_extension + yet_another_extension + >>> print(parser['hashes']['interpolation not necessary']) + if # is not at line start + >>> print(parser['hashes']['even in multiline values']) + line #1 + line #2 + line #3 + +* *strict*, default value: ``True`` + + When set to ``True``, the parser will not allow for any section or option + duplicates while reading from a single source (using :meth:`read_file`, + :meth:`read_string` or :meth:`read_dict`). It is recommended to use strict + parsers in new applications. + + .. versionchanged:: 3.2 + In previous versions of :mod:`configparser` behaviour matched + ``strict=False``. + +* *empty_lines_in_values*, default value: ``True`` + + In config parsers, values can span multiple lines as long as they are + indented more than the key that holds them. By default parsers also let + empty lines to be parts of values. At the same time, keys can be arbitrarily + indented themselves to improve readability. In consequence, when + configuration files get big and complex, it is easy for the user to lose + track of the file structure. Take for instance: + + .. code-block:: ini + + [Section] + key = multiline + value with a gotcha + + this = is still a part of the multiline value of 'key' + + This can be especially problematic for the user to see if she's using a + proportional font to edit the file. That is why when your application does + not need values with empty lines, you should consider disallowing them. This + will make empty lines split keys every time. In the example above, it would + produce two keys, ``key`` and ``this``. + +* *default_section*, default value: ``configparser.DEFAULTSECT`` (that is: + ``"DEFAULT"``) + + The convention of allowing a special section of default values for other + sections or interpolation purposes is a powerful concept of this library, + letting users create complex declarative configurations. This section is + normally called ``"DEFAULT"`` but this can be customized to point to any + other valid section name. Some typical values include: ``"general"`` or + ``"common"``. The name provided is used for recognizing default sections + when reading from any source and is used when writing configuration back to + a file. Its current value can be retrieved using the + ``parser_instance.default_section`` attribute and may be modified at runtime + (i.e. to convert files from one format to another). + +* *interpolation*, default value: ``configparser.BasicInterpolation`` + + Interpolation behaviour may be customized by providing a custom handler + through the *interpolation* argument. ``None`` can be used to turn off + interpolation completely, ``ExtendedInterpolation()`` provides a more + advanced variant inspired by ``zc.buildout``. More on the subject in the + `dedicated documentation section <#interpolation-of-values>`_. + :class:`RawConfigParser` has a default value of ``None``. + +* *converters*, default value: not set + + Config parsers provide option value getters that perform type conversion. By + default :meth:`~ConfigParser.getint`, :meth:`~ConfigParser.getfloat`, and + :meth:`~ConfigParser.getboolean` are implemented. Should other getters be + desirable, users may define them in a subclass or pass a dictionary where each + key is a name of the converter and each value is a callable implementing said + conversion. For instance, passing ``{'decimal': decimal.Decimal}`` would add + :meth:`getdecimal` on both the parser object and all section proxies. In + other words, it will be possible to write both + ``parser_instance.getdecimal('section', 'key', fallback=0)`` and + ``parser_instance['section'].getdecimal('key', 0)``. + + If the converter needs to access the state of the parser, it can be + implemented as a method on a config parser subclass. If the name of this + method starts with ``get``, it will be available on all section proxies, in + the dict-compatible form (see the ``getdecimal()`` example above). + +More advanced customization may be achieved by overriding default values of +these parser attributes. The defaults are defined on the classes, so they may +be overridden by subclasses or by attribute assignment. + +.. attribute:: ConfigParser.BOOLEAN_STATES + + By default when using :meth:`~ConfigParser.getboolean`, config parsers + consider the following values ``True``: ``'1'``, ``'yes'``, ``'true'``, + ``'on'`` and the following values ``False``: ``'0'``, ``'no'``, ``'false'``, + ``'off'``. You can override this by specifying a custom dictionary of strings + and their Boolean outcomes. For example: + + .. doctest:: + + >>> custom = configparser.ConfigParser() + >>> custom['section1'] = {'funky': 'nope'} + >>> custom['section1'].getboolean('funky') + Traceback (most recent call last): + ... + ValueError: Not a boolean: nope + >>> custom.BOOLEAN_STATES = {'sure': True, 'nope': False} + >>> custom['section1'].getboolean('funky') + False + + Other typical Boolean pairs include ``accept``/``reject`` or + ``enabled``/``disabled``. + +.. method:: ConfigParser.optionxform(option) + + This method transforms option names on every read, get, or set + operation. The default converts the name to lowercase. This also + means that when a configuration file gets written, all keys will be + lowercase. Override this method if that's unsuitable. + For example: + + .. doctest:: + + >>> config = """ + ... [Section1] + ... Key = Value + ... + ... [Section2] + ... AnotherKey = Value + ... """ + >>> typical = configparser.ConfigParser() + >>> typical.read_string(config) + >>> list(typical['Section1'].keys()) + ['key'] + >>> list(typical['Section2'].keys()) + ['anotherkey'] + >>> custom = configparser.RawConfigParser() + >>> custom.optionxform = lambda option: option + >>> custom.read_string(config) + >>> list(custom['Section1'].keys()) + ['Key'] + >>> list(custom['Section2'].keys()) + ['AnotherKey'] + + .. note:: + The optionxform function transforms option names to a canonical form. + This should be an idempotent function: if the name is already in + canonical form, it should be returned unchanged. + + +.. attribute:: ConfigParser.SECTCRE + + A compiled regular expression used to parse section headers. The default + matches ``[section]`` to the name ``"section"``. Whitespace is considered + part of the section name, thus ``[ larch ]`` will be read as a section of + name ``" larch "``. Override this attribute if that's unsuitable. For + example: + + .. doctest:: + + >>> import re + >>> config = """ + ... [Section 1] + ... option = value + ... + ... [ Section 2 ] + ... another = val + ... """ + >>> typical = configparser.ConfigParser() + >>> typical.read_string(config) + >>> typical.sections() + ['Section 1', ' Section 2 '] + >>> custom = configparser.ConfigParser() + >>> custom.SECTCRE = re.compile(r"\[ *(?P

    [^]]+?) *\]") + >>> custom.read_string(config) + >>> custom.sections() + ['Section 1', 'Section 2'] + + .. note:: + + While ConfigParser objects also use an ``OPTCRE`` attribute for recognizing + option lines, it's not recommended to override it because that would + interfere with constructor options *allow_no_value* and *delimiters*. + + +Legacy API Examples +------------------- + +Mainly because of backwards compatibility concerns, :mod:`configparser` +provides also a legacy API with explicit ``get``/``set`` methods. While there +are valid use cases for the methods outlined below, mapping protocol access is +preferred for new projects. The legacy API is at times more advanced, +low-level and downright counterintuitive. + +An example of writing to a configuration file:: + + import configparser + + config = configparser.RawConfigParser() + + # Please note that using RawConfigParser's set functions, you can assign + # non-string values to keys internally, but will receive an error when + # attempting to write to a file or when you get it in non-raw mode. Setting + # values using the mapping protocol or ConfigParser's set() does not allow + # such assignments to take place. + config.add_section('Section1') + config.set('Section1', 'an_int', '15') + config.set('Section1', 'a_bool', 'true') + config.set('Section1', 'a_float', '3.1415') + config.set('Section1', 'baz', 'fun') + config.set('Section1', 'bar', 'Python') + config.set('Section1', 'foo', '%(bar)s is %(baz)s!') + + # Writing our configuration file to 'example.cfg' + with open('example.cfg', 'w') as configfile: + config.write(configfile) + +An example of reading the configuration file again:: + + import configparser + + config = configparser.RawConfigParser() + config.read('example.cfg') + + # getfloat() raises an exception if the value is not a float + # getint() and getboolean() also do this for their respective types + a_float = config.getfloat('Section1', 'a_float') + an_int = config.getint('Section1', 'an_int') + print(a_float + an_int) + + # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'. + # This is because we are using a RawConfigParser(). + if config.getboolean('Section1', 'a_bool'): + print(config.get('Section1', 'foo')) + +To get interpolation, use :class:`ConfigParser`:: + + import configparser + + cfg = configparser.ConfigParser() + cfg.read('example.cfg') + + # Set the optional *raw* argument of get() to True if you wish to disable + # interpolation in a single get operation. + print(cfg.get('Section1', 'foo', raw=False)) # -> "Python is fun!" + print(cfg.get('Section1', 'foo', raw=True)) # -> "%(bar)s is %(baz)s!" + + # The optional *vars* argument is a dict with members that will take + # precedence in interpolation. + print(cfg.get('Section1', 'foo', vars={'bar': 'Documentation', + 'baz': 'evil'})) + + # The optional *fallback* argument can be used to provide a fallback value + print(cfg.get('Section1', 'foo')) + # -> "Python is fun!" + + print(cfg.get('Section1', 'foo', fallback='Monty is not.')) + # -> "Python is fun!" + + print(cfg.get('Section1', 'monster', fallback='No such things as monsters.')) + # -> "No such things as monsters." + + # A bare print(cfg.get('Section1', 'monster')) would raise NoOptionError + # but we can also use: + + print(cfg.get('Section1', 'monster', fallback=None)) + # -> None + +Default values are available in both types of ConfigParsers. They are used in +interpolation if an option used is not defined elsewhere. :: + + import configparser + + # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each + config = configparser.ConfigParser({'bar': 'Life', 'baz': 'hard'}) + config.read('example.cfg') + + print(config.get('Section1', 'foo')) # -> "Python is fun!" + config.remove_option('Section1', 'bar') + config.remove_option('Section1', 'baz') + print(config.get('Section1', 'foo')) # -> "Life is hard!" + + +.. _configparser-objects: + +ConfigParser Objects +-------------------- + +.. class:: ConfigParser(defaults=None, dict_type=dict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT, interpolation=BasicInterpolation(), converters={}) + + The main configuration parser. When *defaults* is given, it is initialized + into the dictionary of intrinsic defaults. When *dict_type* is given, it + will be used to create the dictionary objects for the list of sections, for + the options within a section, and for the default values. + + When *delimiters* is given, it is used as the set of substrings that + divide keys from values. When *comment_prefixes* is given, it will be used + as the set of substrings that prefix comments in otherwise empty lines. + Comments can be indented. When *inline_comment_prefixes* is given, it will + be used as the set of substrings that prefix comments in non-empty lines. + + When *strict* is ``True`` (the default), the parser won't allow for + any section or option duplicates while reading from a single source (file, + string or dictionary), raising :exc:`DuplicateSectionError` or + :exc:`DuplicateOptionError`. When *empty_lines_in_values* is ``False`` + (default: ``True``), each empty line marks the end of an option. Otherwise, + internal empty lines of a multiline option are kept as part of the value. + When *allow_no_value* is ``True`` (default: ``False``), options without + values are accepted; the value held for these is ``None`` and they are + serialized without the trailing delimiter. + + When *default_section* is given, it specifies the name for the special + section holding default values for other sections and interpolation purposes + (normally named ``"DEFAULT"``). This value can be retrieved and changed on + runtime using the ``default_section`` instance attribute. + + Interpolation behaviour may be customized by providing a custom handler + through the *interpolation* argument. ``None`` can be used to turn off + interpolation completely, ``ExtendedInterpolation()`` provides a more + advanced variant inspired by ``zc.buildout``. More on the subject in the + `dedicated documentation section <#interpolation-of-values>`_. + + All option names used in interpolation will be passed through the + :meth:`optionxform` method just like any other option name reference. For + example, using the default implementation of :meth:`optionxform` (which + converts option names to lower case), the values ``foo %(bar)s`` and ``foo + %(BAR)s`` are equivalent. + + When *converters* is given, it should be a dictionary where each key + represents the name of a type converter and each value is a callable + implementing the conversion from string to the desired datatype. Every + converter gets its own corresponding :meth:`get*()` method on the parser + object and section proxies. + + .. versionchanged:: 3.1 + The default *dict_type* is :class:`collections.OrderedDict`. + + .. versionchanged:: 3.2 + *allow_no_value*, *delimiters*, *comment_prefixes*, *strict*, + *empty_lines_in_values*, *default_section* and *interpolation* were + added. + + .. versionchanged:: 3.5 + The *converters* argument was added. + + .. versionchanged:: 3.7 + The *defaults* argument is read with :meth:`read_dict()`, + providing consistent behavior across the parser: non-string + keys and values are implicitly converted to strings. + + .. versionchanged:: 3.8 + The default *dict_type* is :class:`dict`, since it now preserves + insertion order. + + .. method:: defaults() + + Return a dictionary containing the instance-wide defaults. + + + .. method:: sections() + + Return a list of the sections available; the *default section* is not + included in the list. + + + .. method:: add_section(section) + + Add a section named *section* to the instance. If a section by the given + name already exists, :exc:`DuplicateSectionError` is raised. If the + *default section* name is passed, :exc:`ValueError` is raised. The name + of the section must be a string; if not, :exc:`TypeError` is raised. + + .. versionchanged:: 3.2 + Non-string section names raise :exc:`TypeError`. + + + .. method:: has_section(section) + + Indicates whether the named *section* is present in the configuration. + The *default section* is not acknowledged. + + + .. method:: options(section) + + Return a list of options available in the specified *section*. + + + .. method:: has_option(section, option) + + If the given *section* exists, and contains the given *option*, return + :const:`True`; otherwise return :const:`False`. If the specified + *section* is :const:`None` or an empty string, DEFAULT is assumed. + + + .. method:: read(filenames, encoding=None) + + Attempt to read and parse an iterable of filenames, returning a list of + filenames which were successfully parsed. + + If *filenames* is a string, a :class:`bytes` object or a + :term:`path-like object`, it is treated as + a single filename. If a file named in *filenames* cannot be opened, that + file will be ignored. This is designed so that you can specify an + iterable of potential configuration file locations (for example, the + current directory, the user's home directory, and some system-wide + directory), and all existing configuration files in the iterable will be + read. + + If none of the named files exist, the :class:`ConfigParser` + instance will contain an empty dataset. An application which requires + initial values to be loaded from a file should load the required file or + files using :meth:`read_file` before calling :meth:`read` for any + optional files:: + + import configparser, os + + config = configparser.ConfigParser() + config.read_file(open('defaults.cfg')) + config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')], + encoding='cp1250') + + .. versionadded:: 3.2 + The *encoding* parameter. Previously, all files were read using the + default encoding for :func:`open`. + + .. versionadded:: 3.6.1 + The *filenames* parameter accepts a :term:`path-like object`. + + .. versionadded:: 3.7 + The *filenames* parameter accepts a :class:`bytes` object. + + + .. method:: read_file(f, source=None) + + Read and parse configuration data from *f* which must be an iterable + yielding Unicode strings (for example files opened in text mode). + + Optional argument *source* specifies the name of the file being read. If + not given and *f* has a :attr:`name` attribute, that is used for + *source*; the default is ``''``. + + .. versionadded:: 3.2 + Replaces :meth:`readfp`. + + .. method:: read_string(string, source='') + + Parse configuration data from a string. + + Optional argument *source* specifies a context-specific name of the + string passed. If not given, ``''`` is used. This should + commonly be a filesystem path or a URL. + + .. versionadded:: 3.2 + + + .. method:: read_dict(dictionary, source='') + + Load configuration from any object that provides a dict-like ``items()`` + method. Keys are section names, values are dictionaries with keys and + values that should be present in the section. If the used dictionary + type preserves order, sections and their keys will be added in order. + Values are automatically converted to strings. + + Optional argument *source* specifies a context-specific name of the + dictionary passed. If not given, ```` is used. + + This method can be used to copy state between parsers. + + .. versionadded:: 3.2 + + + .. method:: get(section, option, *, raw=False, vars=None[, fallback]) + + Get an *option* value for the named *section*. If *vars* is provided, it + must be a dictionary. The *option* is looked up in *vars* (if provided), + *section*, and in *DEFAULTSECT* in that order. If the key is not found + and *fallback* is provided, it is used as a fallback value. ``None`` can + be provided as a *fallback* value. + + All the ``'%'`` interpolations are expanded in the return values, unless + the *raw* argument is true. Values for interpolation keys are looked up + in the same manner as the option. + + .. versionchanged:: 3.2 + Arguments *raw*, *vars* and *fallback* are keyword only to protect + users from trying to use the third argument as the *fallback* fallback + (especially when using the mapping protocol). + + + .. method:: getint(section, option, *, raw=False, vars=None[, fallback]) + + A convenience method which coerces the *option* in the specified *section* + to an integer. See :meth:`get` for explanation of *raw*, *vars* and + *fallback*. + + + .. method:: getfloat(section, option, *, raw=False, vars=None[, fallback]) + + A convenience method which coerces the *option* in the specified *section* + to a floating point number. See :meth:`get` for explanation of *raw*, + *vars* and *fallback*. + + + .. method:: getboolean(section, option, *, raw=False, vars=None[, fallback]) + + A convenience method which coerces the *option* in the specified *section* + to a Boolean value. Note that the accepted values for the option are + ``'1'``, ``'yes'``, ``'true'``, and ``'on'``, which cause this method to + return ``True``, and ``'0'``, ``'no'``, ``'false'``, and ``'off'``, which + cause it to return ``False``. These string values are checked in a + case-insensitive manner. Any other value will cause it to raise + :exc:`ValueError`. See :meth:`get` for explanation of *raw*, *vars* and + *fallback*. + + + .. method:: items(raw=False, vars=None) + items(section, raw=False, vars=None) + + When *section* is not given, return a list of *section_name*, + *section_proxy* pairs, including DEFAULTSECT. + + Otherwise, return a list of *name*, *value* pairs for the options in the + given *section*. Optional arguments have the same meaning as for the + :meth:`get` method. + + .. versionchanged:: 3.8 + Items present in *vars* no longer appear in the result. The previous + behaviour mixed actual parser options with variables provided for + interpolation. + + + .. method:: set(section, option, value) + + If the given section exists, set the given option to the specified value; + otherwise raise :exc:`NoSectionError`. *option* and *value* must be + strings; if not, :exc:`TypeError` is raised. + + + .. method:: write(fileobject, space_around_delimiters=True) + + Write a representation of the configuration to the specified :term:`file + object`, which must be opened in text mode (accepting strings). This + representation can be parsed by a future :meth:`read` call. If + *space_around_delimiters* is true, delimiters between + keys and values are surrounded by spaces. + + + .. method:: remove_option(section, option) + + Remove the specified *option* from the specified *section*. If the + section does not exist, raise :exc:`NoSectionError`. If the option + existed to be removed, return :const:`True`; otherwise return + :const:`False`. + + + .. method:: remove_section(section) + + Remove the specified *section* from the configuration. If the section in + fact existed, return ``True``. Otherwise return ``False``. + + + .. method:: optionxform(option) + + Transforms the option name *option* as found in an input file or as passed + in by client code to the form that should be used in the internal + structures. The default implementation returns a lower-case version of + *option*; subclasses may override this or client code can set an attribute + of this name on instances to affect this behavior. + + You don't need to subclass the parser to use this method, you can also + set it on an instance, to a function that takes a string argument and + returns a string. Setting it to ``str``, for example, would make option + names case sensitive:: + + cfgparser = ConfigParser() + cfgparser.optionxform = str + + Note that when reading configuration files, whitespace around the option + names is stripped before :meth:`optionxform` is called. + + + .. method:: readfp(fp, filename=None) + + .. deprecated:: 3.2 + Use :meth:`read_file` instead. + + .. versionchanged:: 3.2 + :meth:`readfp` now iterates on *fp* instead of calling ``fp.readline()``. + + For existing code calling :meth:`readfp` with arguments which don't + support iteration, the following generator may be used as a wrapper + around the file-like object:: + + def readline_generator(fp): + line = fp.readline() + while line: + yield line + line = fp.readline() + + Instead of ``parser.readfp(fp)`` use + ``parser.read_file(readline_generator(fp))``. + + +.. data:: MAX_INTERPOLATION_DEPTH + + The maximum depth for recursive interpolation for :meth:`get` when the *raw* + parameter is false. This is relevant only when the default *interpolation* + is used. + + +.. _rawconfigparser-objects: + +RawConfigParser Objects +----------------------- + +.. class:: RawConfigParser(defaults=None, dict_type=dict, \ + allow_no_value=False, *, delimiters=('=', ':'), \ + comment_prefixes=('#', ';'), \ + inline_comment_prefixes=None, strict=True, \ + empty_lines_in_values=True, \ + default_section=configparser.DEFAULTSECT[, \ + interpolation]) + + Legacy variant of the :class:`ConfigParser`. It has interpolation + disabled by default and allows for non-string section names, option + names, and values via its unsafe ``add_section`` and ``set`` methods, + as well as the legacy ``defaults=`` keyword argument handling. + + .. versionchanged:: 3.8 + The default *dict_type* is :class:`dict`, since it now preserves + insertion order. + + .. note:: + Consider using :class:`ConfigParser` instead which checks types of + the values to be stored internally. If you don't want interpolation, you + can use ``ConfigParser(interpolation=None)``. + + + .. method:: add_section(section) + + Add a section named *section* to the instance. If a section by the given + name already exists, :exc:`DuplicateSectionError` is raised. If the + *default section* name is passed, :exc:`ValueError` is raised. + + Type of *section* is not checked which lets users create non-string named + sections. This behaviour is unsupported and may cause internal errors. + + + .. method:: set(section, option, value) + + If the given section exists, set the given option to the specified value; + otherwise raise :exc:`NoSectionError`. While it is possible to use + :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters + set to true) for *internal* storage of non-string values, full + functionality (including interpolation and output to files) can only be + achieved using string values. + + This method lets users assign non-string values to keys internally. This + behaviour is unsupported and will cause errors when attempting to write + to a file or get it in non-raw mode. **Use the mapping protocol API** + which does not allow such assignments to take place. + + +Exceptions +---------- + +.. exception:: Error + + Base class for all other :mod:`configparser` exceptions. + + +.. exception:: NoSectionError + + Exception raised when a specified section is not found. + + +.. exception:: DuplicateSectionError + + Exception raised if :meth:`add_section` is called with the name of a section + that is already present or in strict parsers when a section if found more + than once in a single input file, string or dictionary. + + .. versionadded:: 3.2 + Optional ``source`` and ``lineno`` attributes and arguments to + :meth:`__init__` were added. + + +.. exception:: DuplicateOptionError + + Exception raised by strict parsers if a single option appears twice during + reading from a single file, string or dictionary. This catches misspellings + and case sensitivity-related errors, e.g. a dictionary may have two keys + representing the same case-insensitive configuration key. + + +.. exception:: NoOptionError + + Exception raised when a specified option is not found in the specified + section. + + +.. exception:: InterpolationError + + Base class for exceptions raised when problems occur performing string + interpolation. + + +.. exception:: InterpolationDepthError + + Exception raised when string interpolation cannot be completed because the + number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of + :exc:`InterpolationError`. + + +.. exception:: InterpolationMissingOptionError + + Exception raised when an option referenced from a value does not exist. + Subclass of :exc:`InterpolationError`. + + +.. exception:: InterpolationSyntaxError + + Exception raised when the source text into which substitutions are made does + not conform to the required syntax. Subclass of :exc:`InterpolationError`. + + +.. exception:: MissingSectionHeaderError + + Exception raised when attempting to parse a file which has no section + headers. + + +.. exception:: ParsingError + + Exception raised when errors occur attempting to parse a file. + + .. versionchanged:: 3.2 + The ``filename`` attribute and :meth:`__init__` argument were renamed to + ``source`` for consistency. + + +.. rubric:: Footnotes + +.. [1] Config parsers allow for heavy customization. If you are interested in + changing the behaviour outlined by the footnote reference, consult the + `Customizing Parser Behaviour`_ section. diff --git a/cpython_2/environment/repo/Doc/library/constants.rst b/cpython_2/environment/repo/Doc/library/constants.rst new file mode 100644 index 0000000000000000000000000000000000000000..f17e1a37875168fa9b4833cf52c5d49038b9e760 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/constants.rst @@ -0,0 +1,104 @@ +.. _built-in-consts: + +Built-in Constants +================== + +A small number of constants live in the built-in namespace. They are: + +.. data:: False + + The false value of the :class:`bool` type. Assignments to ``False`` + are illegal and raise a :exc:`SyntaxError`. + + +.. data:: True + + The true value of the :class:`bool` type. Assignments to ``True`` + are illegal and raise a :exc:`SyntaxError`. + + +.. data:: None + + The sole value of the type ``NoneType``. ``None`` is frequently used to + represent the absence of a value, as when default arguments are not passed to a + function. Assignments to ``None`` are illegal and raise a :exc:`SyntaxError`. + + +.. data:: NotImplemented + + Special value which should be returned by the binary special methods + (e.g. :meth:`__eq__`, :meth:`__lt__`, :meth:`__add__`, :meth:`__rsub__`, + etc.) to indicate that the operation is not implemented with respect to + the other type; may be returned by the in-place binary special methods + (e.g. :meth:`__imul__`, :meth:`__iand__`, etc.) for the same purpose. + It should not be evaluated in a boolean context. + + .. note:: + + When a binary (or in-place) method returns ``NotImplemented`` the + interpreter will try the reflected operation on the other type (or some + other fallback, depending on the operator). If all attempts return + ``NotImplemented``, the interpreter will raise an appropriate exception. + Incorrectly returning ``NotImplemented`` will result in a misleading + error message or the ``NotImplemented`` value being returned to Python code. + + See :ref:`implementing-the-arithmetic-operations` for examples. + + .. note:: + + ``NotImplementedError`` and ``NotImplemented`` are not interchangeable, + even though they have similar names and purposes. + See :exc:`NotImplementedError` for details on when to use it. + + .. versionchanged:: 3.9 + Evaluating ``NotImplemented`` in a boolean context is deprecated. While + it currently evaluates as true, it will emit a :exc:`DeprecationWarning`. + It will raise a :exc:`TypeError` in a future version of Python. + + +.. index:: single: ...; ellipsis literal +.. data:: Ellipsis + + The same as the ellipsis literal "``...``". Special value used mostly in conjunction + with extended slicing syntax for user-defined container data types. + + +.. data:: __debug__ + + This constant is true if Python was not started with an :option:`-O` option. + See also the :keyword:`assert` statement. + + +.. note:: + + The names :data:`None`, :data:`False`, :data:`True` and :data:`__debug__` + cannot be reassigned (assignments to them, even as an attribute name, raise + :exc:`SyntaxError`), so they can be considered "true" constants. + + +Constants added by the :mod:`site` module +----------------------------------------- + +The :mod:`site` module (which is imported automatically during startup, except +if the :option:`-S` command-line option is given) adds several constants to the +built-in namespace. They are useful for the interactive interpreter shell and +should not be used in programs. + +.. data:: quit(code=None) + exit(code=None) + + Objects that when printed, print a message like "Use quit() or Ctrl-D + (i.e. EOF) to exit", and when called, raise :exc:`SystemExit` with the + specified exit code. + +.. data:: copyright + credits + + Objects that when printed or called, print the text of copyright or + credits, respectively. + +.. data:: license + + Object that when printed, prints the message "Type license() to see the + full license text", and when called, displays the full license text in a + pager-like fashion (one screen at a time). diff --git a/cpython_2/environment/repo/Doc/library/contextlib.rst b/cpython_2/environment/repo/Doc/library/contextlib.rst new file mode 100644 index 0000000000000000000000000000000000000000..0aa4ad76523480b5076ddbd386709b231d3b9024 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/contextlib.rst @@ -0,0 +1,872 @@ +:mod:`!contextlib` --- Utilities for :keyword:`!with`\ -statement contexts +========================================================================== + +.. module:: contextlib + :synopsis: Utilities for with-statement contexts. + +**Source code:** :source:`Lib/contextlib.py` + +-------------- + +This module provides utilities for common tasks involving the :keyword:`with` +statement. For more information see also :ref:`typecontextmanager` and +:ref:`context-managers`. + + +Utilities +--------- + +Functions and classes provided: + +.. class:: AbstractContextManager + + An :term:`abstract base class` for classes that implement + :meth:`object.__enter__` and :meth:`object.__exit__`. A default + implementation for :meth:`object.__enter__` is provided which returns + ``self`` while :meth:`object.__exit__` is an abstract method which by default + returns ``None``. See also the definition of :ref:`typecontextmanager`. + + .. versionadded:: 3.6 + + +.. class:: AbstractAsyncContextManager + + An :term:`abstract base class` for classes that implement + :meth:`object.__aenter__` and :meth:`object.__aexit__`. A default + implementation for :meth:`object.__aenter__` is provided which returns + ``self`` while :meth:`object.__aexit__` is an abstract method which by default + returns ``None``. See also the definition of + :ref:`async-context-managers`. + + .. versionadded:: 3.7 + + +.. decorator:: contextmanager + + This function is a :term:`decorator` that can be used to define a factory + function for :keyword:`with` statement context managers, without needing to + create a class or separate :meth:`__enter__` and :meth:`__exit__` methods. + + While many objects natively support use in with statements, sometimes a + resource needs to be managed that isn't a context manager in its own right, + and doesn't implement a ``close()`` method for use with ``contextlib.closing`` + + An abstract example would be the following to ensure correct resource + management:: + + from contextlib import contextmanager + + @contextmanager + def managed_resource(*args, **kwds): + # Code to acquire resource, e.g.: + resource = acquire_resource(*args, **kwds) + try: + yield resource + finally: + # Code to release resource, e.g.: + release_resource(resource) + + >>> with managed_resource(timeout=3600) as resource: + ... # Resource is released at the end of this block, + ... # even if code in the block raises an exception + + The function being decorated must return a :term:`generator`-iterator when + called. This iterator must yield exactly one value, which will be bound to + the targets in the :keyword:`with` statement's :keyword:`!as` clause, if any. + + At the point where the generator yields, the block nested in the :keyword:`with` + statement is executed. The generator is then resumed after the block is exited. + If an unhandled exception occurs in the block, it is reraised inside the + generator at the point where the yield occurred. Thus, you can use a + :keyword:`try`...\ :keyword:`except`...\ :keyword:`finally` statement to trap + the error (if any), or ensure that some cleanup takes place. If an exception is + trapped merely in order to log it or to perform some action (rather than to + suppress it entirely), the generator must reraise that exception. Otherwise the + generator context manager will indicate to the :keyword:`!with` statement that + the exception has been handled, and execution will resume with the statement + immediately following the :keyword:`!with` statement. + + :func:`contextmanager` uses :class:`ContextDecorator` so the context managers + it creates can be used as decorators as well as in :keyword:`with` statements. + When used as a decorator, a new generator instance is implicitly created on + each function call (this allows the otherwise "one-shot" context managers + created by :func:`contextmanager` to meet the requirement that context + managers support multiple invocations in order to be used as decorators). + + .. versionchanged:: 3.2 + Use of :class:`ContextDecorator`. + + +.. decorator:: asynccontextmanager + + Similar to :func:`~contextlib.contextmanager`, but creates an + :ref:`asynchronous context manager `. + + This function is a :term:`decorator` that can be used to define a factory + function for :keyword:`async with` statement asynchronous context managers, + without needing to create a class or separate :meth:`__aenter__` and + :meth:`__aexit__` methods. It must be applied to an :term:`asynchronous + generator` function. + + A simple example:: + + from contextlib import asynccontextmanager + + @asynccontextmanager + async def get_connection(): + conn = await acquire_db_connection() + try: + yield conn + finally: + await release_db_connection(conn) + + async def get_all_users(): + async with get_connection() as conn: + return conn.query('SELECT ...') + + .. versionadded:: 3.7 + + +.. function:: closing(thing) + + Return a context manager that closes *thing* upon completion of the block. This + is basically equivalent to:: + + from contextlib import contextmanager + + @contextmanager + def closing(thing): + try: + yield thing + finally: + thing.close() + + And lets you write code like this:: + + from contextlib import closing + from urllib.request import urlopen + + with closing(urlopen('http://www.python.org')) as page: + for line in page: + print(line) + + without needing to explicitly close ``page``. Even if an error occurs, + ``page.close()`` will be called when the :keyword:`with` block is exited. + + +.. _simplifying-support-for-single-optional-context-managers: + +.. function:: nullcontext(enter_result=None) + + Return a context manager that returns *enter_result* from ``__enter__``, but + otherwise does nothing. It is intended to be used as a stand-in for an + optional context manager, for example:: + + def myfunction(arg, ignore_exceptions=False): + if ignore_exceptions: + # Use suppress to ignore all exceptions. + cm = contextlib.suppress(Exception) + else: + # Do not ignore any exceptions, cm has no effect. + cm = contextlib.nullcontext() + with cm: + # Do something + + An example using *enter_result*:: + + def process_file(file_or_path): + if isinstance(file_or_path, str): + # If string, open file + cm = open(file_or_path) + else: + # Caller is responsible for closing file + cm = nullcontext(file_or_path) + + with cm as file: + # Perform processing on the file + + .. versionadded:: 3.7 + + +.. function:: suppress(*exceptions) + + Return a context manager that suppresses any of the specified exceptions + if they occur in the body of a with statement and then resumes execution + with the first statement following the end of the with statement. + + As with any other mechanism that completely suppresses exceptions, this + context manager should be used only to cover very specific errors where + silently continuing with program execution is known to be the right + thing to do. + + For example:: + + from contextlib import suppress + + with suppress(FileNotFoundError): + os.remove('somefile.tmp') + + with suppress(FileNotFoundError): + os.remove('someotherfile.tmp') + + This code is equivalent to:: + + try: + os.remove('somefile.tmp') + except FileNotFoundError: + pass + + try: + os.remove('someotherfile.tmp') + except FileNotFoundError: + pass + + This context manager is :ref:`reentrant `. + + .. versionadded:: 3.4 + + +.. function:: redirect_stdout(new_target) + + Context manager for temporarily redirecting :data:`sys.stdout` to + another file or file-like object. + + This tool adds flexibility to existing functions or classes whose output + is hardwired to stdout. + + For example, the output of :func:`help` normally is sent to *sys.stdout*. + You can capture that output in a string by redirecting the output to an + :class:`io.StringIO` object:: + + f = io.StringIO() + with redirect_stdout(f): + help(pow) + s = f.getvalue() + + To send the output of :func:`help` to a file on disk, redirect the output + to a regular file:: + + with open('help.txt', 'w') as f: + with redirect_stdout(f): + help(pow) + + To send the output of :func:`help` to *sys.stderr*:: + + with redirect_stdout(sys.stderr): + help(pow) + + Note that the global side effect on :data:`sys.stdout` means that this + context manager is not suitable for use in library code and most threaded + applications. It also has no effect on the output of subprocesses. + However, it is still a useful approach for many utility scripts. + + This context manager is :ref:`reentrant `. + + .. versionadded:: 3.4 + + +.. function:: redirect_stderr(new_target) + + Similar to :func:`~contextlib.redirect_stdout` but redirecting + :data:`sys.stderr` to another file or file-like object. + + This context manager is :ref:`reentrant `. + + .. versionadded:: 3.5 + + +.. class:: ContextDecorator() + + A base class that enables a context manager to also be used as a decorator. + + Context managers inheriting from ``ContextDecorator`` have to implement + ``__enter__`` and ``__exit__`` as normal. ``__exit__`` retains its optional + exception handling even when used as a decorator. + + ``ContextDecorator`` is used by :func:`contextmanager`, so you get this + functionality automatically. + + Example of ``ContextDecorator``:: + + from contextlib import ContextDecorator + + class mycontext(ContextDecorator): + def __enter__(self): + print('Starting') + return self + + def __exit__(self, *exc): + print('Finishing') + return False + + >>> @mycontext() + ... def function(): + ... print('The bit in the middle') + ... + >>> function() + Starting + The bit in the middle + Finishing + + >>> with mycontext(): + ... print('The bit in the middle') + ... + Starting + The bit in the middle + Finishing + + This change is just syntactic sugar for any construct of the following form:: + + def f(): + with cm(): + # Do stuff + + ``ContextDecorator`` lets you instead write:: + + @cm() + def f(): + # Do stuff + + It makes it clear that the ``cm`` applies to the whole function, rather than + just a piece of it (and saving an indentation level is nice, too). + + Existing context managers that already have a base class can be extended by + using ``ContextDecorator`` as a mixin class:: + + from contextlib import ContextDecorator + + class mycontext(ContextBaseClass, ContextDecorator): + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + .. note:: + As the decorated function must be able to be called multiple times, the + underlying context manager must support use in multiple :keyword:`with` + statements. If this is not the case, then the original construct with the + explicit :keyword:`!with` statement inside the function should be used. + + .. versionadded:: 3.2 + + +.. class:: ExitStack() + + A context manager that is designed to make it easy to programmatically + combine other context managers and cleanup functions, especially those + that are optional or otherwise driven by input data. + + For example, a set of files may easily be handled in a single with + statement as follows:: + + with ExitStack() as stack: + files = [stack.enter_context(open(fname)) for fname in filenames] + # All opened files will automatically be closed at the end of + # the with statement, even if attempts to open files later + # in the list raise an exception + + Each instance maintains a stack of registered callbacks that are called in + reverse order when the instance is closed (either explicitly or implicitly + at the end of a :keyword:`with` statement). Note that callbacks are *not* + invoked implicitly when the context stack instance is garbage collected. + + This stack model is used so that context managers that acquire their + resources in their ``__init__`` method (such as file objects) can be + handled correctly. + + Since registered callbacks are invoked in the reverse order of + registration, this ends up behaving as if multiple nested :keyword:`with` + statements had been used with the registered set of callbacks. This even + extends to exception handling - if an inner callback suppresses or replaces + an exception, then outer callbacks will be passed arguments based on that + updated state. + + This is a relatively low level API that takes care of the details of + correctly unwinding the stack of exit callbacks. It provides a suitable + foundation for higher level context managers that manipulate the exit + stack in application specific ways. + + .. versionadded:: 3.3 + + .. method:: enter_context(cm) + + Enters a new context manager and adds its :meth:`__exit__` method to + the callback stack. The return value is the result of the context + manager's own :meth:`__enter__` method. + + These context managers may suppress exceptions just as they normally + would if used directly as part of a :keyword:`with` statement. + + .. method:: push(exit) + + Adds a context manager's :meth:`__exit__` method to the callback stack. + + As ``__enter__`` is *not* invoked, this method can be used to cover + part of an :meth:`__enter__` implementation with a context manager's own + :meth:`__exit__` method. + + If passed an object that is not a context manager, this method assumes + it is a callback with the same signature as a context manager's + :meth:`__exit__` method and adds it directly to the callback stack. + + By returning true values, these callbacks can suppress exceptions the + same way context manager :meth:`__exit__` methods can. + + The passed in object is returned from the function, allowing this + method to be used as a function decorator. + + .. method:: callback(callback, /, *args, **kwds) + + Accepts an arbitrary callback function and arguments and adds it to + the callback stack. + + Unlike the other methods, callbacks added this way cannot suppress + exceptions (as they are never passed the exception details). + + The passed in callback is returned from the function, allowing this + method to be used as a function decorator. + + .. method:: pop_all() + + Transfers the callback stack to a fresh :class:`ExitStack` instance + and returns it. No callbacks are invoked by this operation - instead, + they will now be invoked when the new stack is closed (either + explicitly or implicitly at the end of a :keyword:`with` statement). + + For example, a group of files can be opened as an "all or nothing" + operation as follows:: + + with ExitStack() as stack: + files = [stack.enter_context(open(fname)) for fname in filenames] + # Hold onto the close method, but don't call it yet. + close_files = stack.pop_all().close + # If opening any file fails, all previously opened files will be + # closed automatically. If all files are opened successfully, + # they will remain open even after the with statement ends. + # close_files() can then be invoked explicitly to close them all. + + .. method:: close() + + Immediately unwinds the callback stack, invoking callbacks in the + reverse order of registration. For any context managers and exit + callbacks registered, the arguments passed in will indicate that no + exception occurred. + +.. class:: AsyncExitStack() + + An :ref:`asynchronous context manager `, similar + to :class:`ExitStack`, that supports combining both synchronous and + asynchronous context managers, as well as having coroutines for + cleanup logic. + + The :meth:`close` method is not implemented, :meth:`aclose` must be used + instead. + + .. method:: enter_async_context(cm) + + Similar to :meth:`enter_context` but expects an asynchronous context + manager. + + .. method:: push_async_exit(exit) + + Similar to :meth:`push` but expects either an asynchronous context manager + or a coroutine function. + + .. method:: push_async_callback(callback, /, *args, **kwds) + + Similar to :meth:`callback` but expects a coroutine function. + + .. method:: aclose() + + Similar to :meth:`close` but properly handles awaitables. + + Continuing the example for :func:`asynccontextmanager`:: + + async with AsyncExitStack() as stack: + connections = [await stack.enter_async_context(get_connection()) + for i in range(5)] + # All opened connections will automatically be released at the end of + # the async with statement, even if attempts to open a connection + # later in the list raise an exception. + + .. versionadded:: 3.7 + +Examples and Recipes +-------------------- + +This section describes some examples and recipes for making effective use of +the tools provided by :mod:`contextlib`. + + +Supporting a variable number of context managers +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The primary use case for :class:`ExitStack` is the one given in the class +documentation: supporting a variable number of context managers and other +cleanup operations in a single :keyword:`with` statement. The variability +may come from the number of context managers needed being driven by user +input (such as opening a user specified collection of files), or from +some of the context managers being optional:: + + with ExitStack() as stack: + for resource in resources: + stack.enter_context(resource) + if need_special_resource(): + special = acquire_special_resource() + stack.callback(release_special_resource, special) + # Perform operations that use the acquired resources + +As shown, :class:`ExitStack` also makes it quite easy to use :keyword:`with` +statements to manage arbitrary resources that don't natively support the +context management protocol. + + +Catching exceptions from ``__enter__`` methods +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +It is occasionally desirable to catch exceptions from an ``__enter__`` +method implementation, *without* inadvertently catching exceptions from +the :keyword:`with` statement body or the context manager's ``__exit__`` +method. By using :class:`ExitStack` the steps in the context management +protocol can be separated slightly in order to allow this:: + + stack = ExitStack() + try: + x = stack.enter_context(cm) + except Exception: + # handle __enter__ exception + else: + with stack: + # Handle normal case + +Actually needing to do this is likely to indicate that the underlying API +should be providing a direct resource management interface for use with +:keyword:`try`/:keyword:`except`/:keyword:`finally` statements, but not +all APIs are well designed in that regard. When a context manager is the +only resource management API provided, then :class:`ExitStack` can make it +easier to handle various situations that can't be handled directly in a +:keyword:`with` statement. + + +Cleaning up in an ``__enter__`` implementation +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +As noted in the documentation of :meth:`ExitStack.push`, this +method can be useful in cleaning up an already allocated resource if later +steps in the :meth:`__enter__` implementation fail. + +Here's an example of doing this for a context manager that accepts resource +acquisition and release functions, along with an optional validation function, +and maps them to the context management protocol:: + + from contextlib import contextmanager, AbstractContextManager, ExitStack + + class ResourceManager(AbstractContextManager): + + def __init__(self, acquire_resource, release_resource, check_resource_ok=None): + self.acquire_resource = acquire_resource + self.release_resource = release_resource + if check_resource_ok is None: + def check_resource_ok(resource): + return True + self.check_resource_ok = check_resource_ok + + @contextmanager + def _cleanup_on_error(self): + with ExitStack() as stack: + stack.push(self) + yield + # The validation check passed and didn't raise an exception + # Accordingly, we want to keep the resource, and pass it + # back to our caller + stack.pop_all() + + def __enter__(self): + resource = self.acquire_resource() + with self._cleanup_on_error(): + if not self.check_resource_ok(resource): + msg = "Failed validation for {!r}" + raise RuntimeError(msg.format(resource)) + return resource + + def __exit__(self, *exc_details): + # We don't need to duplicate any of our resource release logic + self.release_resource() + + +Replacing any use of ``try-finally`` and flag variables +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +A pattern you will sometimes see is a ``try-finally`` statement with a flag +variable to indicate whether or not the body of the ``finally`` clause should +be executed. In its simplest form (that can't already be handled just by +using an ``except`` clause instead), it looks something like this:: + + cleanup_needed = True + try: + result = perform_operation() + if result: + cleanup_needed = False + finally: + if cleanup_needed: + cleanup_resources() + +As with any ``try`` statement based code, this can cause problems for +development and review, because the setup code and the cleanup code can end +up being separated by arbitrarily long sections of code. + +:class:`ExitStack` makes it possible to instead register a callback for +execution at the end of a ``with`` statement, and then later decide to skip +executing that callback:: + + from contextlib import ExitStack + + with ExitStack() as stack: + stack.callback(cleanup_resources) + result = perform_operation() + if result: + stack.pop_all() + +This allows the intended cleanup up behaviour to be made explicit up front, +rather than requiring a separate flag variable. + +If a particular application uses this pattern a lot, it can be simplified +even further by means of a small helper class:: + + from contextlib import ExitStack + + class Callback(ExitStack): + def __init__(self, callback, /, *args, **kwds): + super(Callback, self).__init__() + self.callback(callback, *args, **kwds) + + def cancel(self): + self.pop_all() + + with Callback(cleanup_resources) as cb: + result = perform_operation() + if result: + cb.cancel() + +If the resource cleanup isn't already neatly bundled into a standalone +function, then it is still possible to use the decorator form of +:meth:`ExitStack.callback` to declare the resource cleanup in +advance:: + + from contextlib import ExitStack + + with ExitStack() as stack: + @stack.callback + def cleanup_resources(): + ... + result = perform_operation() + if result: + stack.pop_all() + +Due to the way the decorator protocol works, a callback function +declared this way cannot take any parameters. Instead, any resources to +be released must be accessed as closure variables. + + +Using a context manager as a function decorator +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +:class:`ContextDecorator` makes it possible to use a context manager in +both an ordinary ``with`` statement and also as a function decorator. + +For example, it is sometimes useful to wrap functions or groups of statements +with a logger that can track the time of entry and time of exit. Rather than +writing both a function decorator and a context manager for the task, +inheriting from :class:`ContextDecorator` provides both capabilities in a +single definition:: + + from contextlib import ContextDecorator + import logging + + logging.basicConfig(level=logging.INFO) + + class track_entry_and_exit(ContextDecorator): + def __init__(self, name): + self.name = name + + def __enter__(self): + logging.info('Entering: %s', self.name) + + def __exit__(self, exc_type, exc, exc_tb): + logging.info('Exiting: %s', self.name) + +Instances of this class can be used as both a context manager:: + + with track_entry_and_exit('widget loader'): + print('Some time consuming activity goes here') + load_widget() + +And also as a function decorator:: + + @track_entry_and_exit('widget loader') + def activity(): + print('Some time consuming activity goes here') + load_widget() + +Note that there is one additional limitation when using context managers +as function decorators: there's no way to access the return value of +:meth:`__enter__`. If that value is needed, then it is still necessary to use +an explicit ``with`` statement. + +.. seealso:: + + :pep:`343` - The "with" statement + The specification, background, and examples for the Python :keyword:`with` + statement. + +.. _single-use-reusable-and-reentrant-cms: + +Single use, reusable and reentrant context managers +--------------------------------------------------- + +Most context managers are written in a way that means they can only be +used effectively in a :keyword:`with` statement once. These single use +context managers must be created afresh each time they're used - +attempting to use them a second time will trigger an exception or +otherwise not work correctly. + +This common limitation means that it is generally advisable to create +context managers directly in the header of the :keyword:`with` statement +where they are used (as shown in all of the usage examples above). + +Files are an example of effectively single use context managers, since +the first :keyword:`with` statement will close the file, preventing any +further IO operations using that file object. + +Context managers created using :func:`contextmanager` are also single use +context managers, and will complain about the underlying generator failing +to yield if an attempt is made to use them a second time:: + + >>> from contextlib import contextmanager + >>> @contextmanager + ... def singleuse(): + ... print("Before") + ... yield + ... print("After") + ... + >>> cm = singleuse() + >>> with cm: + ... pass + ... + Before + After + >>> with cm: + ... pass + ... + Traceback (most recent call last): + ... + RuntimeError: generator didn't yield + + +.. _reentrant-cms: + +Reentrant context managers +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +More sophisticated context managers may be "reentrant". These context +managers can not only be used in multiple :keyword:`with` statements, +but may also be used *inside* a :keyword:`!with` statement that is already +using the same context manager. + +:class:`threading.RLock` is an example of a reentrant context manager, as are +:func:`suppress` and :func:`redirect_stdout`. Here's a very simple example of +reentrant use:: + + >>> from contextlib import redirect_stdout + >>> from io import StringIO + >>> stream = StringIO() + >>> write_to_stream = redirect_stdout(stream) + >>> with write_to_stream: + ... print("This is written to the stream rather than stdout") + ... with write_to_stream: + ... print("This is also written to the stream") + ... + >>> print("This is written directly to stdout") + This is written directly to stdout + >>> print(stream.getvalue()) + This is written to the stream rather than stdout + This is also written to the stream + +Real world examples of reentrancy are more likely to involve multiple +functions calling each other and hence be far more complicated than this +example. + +Note also that being reentrant is *not* the same thing as being thread safe. +:func:`redirect_stdout`, for example, is definitely not thread safe, as it +makes a global modification to the system state by binding :data:`sys.stdout` +to a different stream. + + +.. _reusable-cms: + +Reusable context managers +^^^^^^^^^^^^^^^^^^^^^^^^^ + +Distinct from both single use and reentrant context managers are "reusable" +context managers (or, to be completely explicit, "reusable, but not +reentrant" context managers, since reentrant context managers are also +reusable). These context managers support being used multiple times, but +will fail (or otherwise not work correctly) if the specific context manager +instance has already been used in a containing with statement. + +:class:`threading.Lock` is an example of a reusable, but not reentrant, +context manager (for a reentrant lock, it is necessary to use +:class:`threading.RLock` instead). + +Another example of a reusable, but not reentrant, context manager is +:class:`ExitStack`, as it invokes *all* currently registered callbacks +when leaving any with statement, regardless of where those callbacks +were added:: + + >>> from contextlib import ExitStack + >>> stack = ExitStack() + >>> with stack: + ... stack.callback(print, "Callback: from first context") + ... print("Leaving first context") + ... + Leaving first context + Callback: from first context + >>> with stack: + ... stack.callback(print, "Callback: from second context") + ... print("Leaving second context") + ... + Leaving second context + Callback: from second context + >>> with stack: + ... stack.callback(print, "Callback: from outer context") + ... with stack: + ... stack.callback(print, "Callback: from inner context") + ... print("Leaving inner context") + ... print("Leaving outer context") + ... + Leaving inner context + Callback: from inner context + Callback: from outer context + Leaving outer context + +As the output from the example shows, reusing a single stack object across +multiple with statements works correctly, but attempting to nest them +will cause the stack to be cleared at the end of the innermost with +statement, which is unlikely to be desirable behaviour. + +Using separate :class:`ExitStack` instances instead of reusing a single +instance avoids that problem:: + + >>> from contextlib import ExitStack + >>> with ExitStack() as outer_stack: + ... outer_stack.callback(print, "Callback: from outer context") + ... with ExitStack() as inner_stack: + ... inner_stack.callback(print, "Callback: from inner context") + ... print("Leaving inner context") + ... print("Leaving outer context") + ... + Leaving inner context + Callback: from inner context + Leaving outer context + Callback: from outer context diff --git a/cpython_2/environment/repo/Doc/library/contextvars.rst b/cpython_2/environment/repo/Doc/library/contextvars.rst new file mode 100644 index 0000000000000000000000000000000000000000..8805661c456edb611c877ee1823cf8a1feb47f7c --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/contextvars.rst @@ -0,0 +1,281 @@ +:mod:`contextvars` --- Context Variables +======================================== + +.. module:: contextvars + :synopsis: Context Variables + +.. sectionauthor:: Yury Selivanov + +-------------- + +This module provides APIs to manage, store, and access context-local +state. The :class:`~contextvars.ContextVar` class is used to declare +and work with *Context Variables*. The :func:`~contextvars.copy_context` +function and the :class:`~contextvars.Context` class should be used to +manage the current context in asynchronous frameworks. + +Context managers that have state should use Context Variables +instead of :func:`threading.local()` to prevent their state from +bleeding to other code unexpectedly, when used in concurrent code. + +See also :pep:`567` for additional details. + +.. versionadded:: 3.7 + + +Context Variables +----------------- + +.. class:: ContextVar(name, [\*, default]) + + This class is used to declare a new Context Variable, e.g.:: + + var: ContextVar[int] = ContextVar('var', default=42) + + The required *name* parameter is used for introspection and debug + purposes. + + The optional keyword-only *default* parameter is returned by + :meth:`ContextVar.get` when no value for the variable is found + in the current context. + + **Important:** Context Variables should be created at the top module + level and never in closures. :class:`Context` objects hold strong + references to context variables which prevents context variables + from being properly garbage collected. + + .. attribute:: ContextVar.name + + The name of the variable. This is a read-only property. + + .. versionadded:: 3.7.1 + + .. method:: get([default]) + + Return a value for the context variable for the current context. + + If there is no value for the variable in the current context, + the method will: + + * return the value of the *default* argument of the method, + if provided; or + + * return the default value for the context variable, + if it was created with one; or + + * raise a :exc:`LookupError`. + + .. method:: set(value) + + Call to set a new value for the context variable in the current + context. + + The required *value* argument is the new value for the context + variable. + + Returns a :class:`~contextvars.Token` object that can be used + to restore the variable to its previous value via the + :meth:`ContextVar.reset` method. + + .. method:: reset(token) + + Reset the context variable to the value it had before the + :meth:`ContextVar.set` that created the *token* was used. + + For example:: + + var = ContextVar('var') + + token = var.set('new value') + # code that uses 'var'; var.get() returns 'new value'. + var.reset(token) + + # After the reset call the var has no value again, so + # var.get() would raise a LookupError. + + +.. class:: contextvars.Token + + *Token* objects are returned by the :meth:`ContextVar.set` method. + They can be passed to the :meth:`ContextVar.reset` method to revert + the value of the variable to what it was before the corresponding + *set*. + + .. attribute:: Token.var + + A read-only property. Points to the :class:`ContextVar` object + that created the token. + + .. attribute:: Token.old_value + + A read-only property. Set to the value the variable had before + the :meth:`ContextVar.set` method call that created the token. + It points to :attr:`Token.MISSING` is the variable was not set + before the call. + + .. attribute:: Token.MISSING + + A marker object used by :attr:`Token.old_value`. + + +Manual Context Management +------------------------- + +.. function:: copy_context() + + Returns a copy of the current :class:`~contextvars.Context` object. + + The following snippet gets a copy of the current context and prints + all variables and their values that are set in it:: + + ctx: Context = copy_context() + print(list(ctx.items())) + + The function has an O(1) complexity, i.e. works equally fast for + contexts with a few context variables and for contexts that have + a lot of them. + + +.. class:: Context() + + A mapping of :class:`ContextVars ` to their values. + + ``Context()`` creates an empty context with no values in it. + To get a copy of the current context use the + :func:`~contextvars.copy_context` function. + + Context implements the :class:`collections.abc.Mapping` interface. + + .. method:: run(callable, \*args, \*\*kwargs) + + Execute ``callable(*args, **kwargs)`` code in the context object + the *run* method is called on. Return the result of the execution + or propagate an exception if one occurred. + + Any changes to any context variables that *callable* makes will + be contained in the context object:: + + var = ContextVar('var') + var.set('spam') + + def main(): + # 'var' was set to 'spam' before + # calling 'copy_context()' and 'ctx.run(main)', so: + # var.get() == ctx[var] == 'spam' + + var.set('ham') + + # Now, after setting 'var' to 'ham': + # var.get() == ctx[var] == 'ham' + + ctx = copy_context() + + # Any changes that the 'main' function makes to 'var' + # will be contained in 'ctx'. + ctx.run(main) + + # The 'main()' function was run in the 'ctx' context, + # so changes to 'var' are contained in it: + # ctx[var] == 'ham' + + # However, outside of 'ctx', 'var' is still set to 'spam': + # var.get() == 'spam' + + The method raises a :exc:`RuntimeError` when called on the same + context object from more than one OS thread, or when called + recursively. + + .. method:: copy() + + Return a shallow copy of the context object. + + .. describe:: var in context + + Return ``True`` if the *context* has a value for *var* set; + return ``False`` otherwise. + + .. describe:: context[var] + + Return the value of the *var* :class:`ContextVar` variable. + If the variable is not set in the context object, a + :exc:`KeyError` is raised. + + .. method:: get(var, [default]) + + Return the value for *var* if *var* has the value in the context + object. Return *default* otherwise. If *default* is not given, + return ``None``. + + .. describe:: iter(context) + + Return an iterator over the variables stored in the context + object. + + .. describe:: len(proxy) + + Return the number of variables set in the context object. + + .. method:: keys() + + Return a list of all variables in the context object. + + .. method:: values() + + Return a list of all variables' values in the context object. + + + .. method:: items() + + Return a list of 2-tuples containing all variables and their + values in the context object. + + +asyncio support +--------------- + +Context variables are natively supported in :mod:`asyncio` and are +ready to be used without any extra configuration. For example, here +is a simple echo server, that uses a context variable to make the +address of a remote client available in the Task that handles that +client:: + + import asyncio + import contextvars + + client_addr_var = contextvars.ContextVar('client_addr') + + def render_goodbye(): + # The address of the currently handled client can be accessed + # without passing it explicitly to this function. + + client_addr = client_addr_var.get() + return f'Good bye, client @ {client_addr}\n'.encode() + + async def handle_request(reader, writer): + addr = writer.transport.get_extra_info('socket').getpeername() + client_addr_var.set(addr) + + # In any code that we call is now possible to get + # client's address by calling 'client_addr_var.get()'. + + while True: + line = await reader.readline() + print(line) + if not line.strip(): + break + writer.write(line) + + writer.write(render_goodbye()) + writer.close() + + async def main(): + srv = await asyncio.start_server( + handle_request, '127.0.0.1', 8081) + + async with srv: + await srv.serve_forever() + + asyncio.run(main()) + + # To test it you can use telnet: + # telnet 127.0.0.1 8081 diff --git a/cpython_2/environment/repo/Doc/library/copy.rst b/cpython_2/environment/repo/Doc/library/copy.rst new file mode 100644 index 0000000000000000000000000000000000000000..a8e8bfb1e832bb2dc569ff04edd27c731a28b3f0 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/copy.rst @@ -0,0 +1,96 @@ +:mod:`copy` --- Shallow and deep copy operations +================================================ + +.. module:: copy + :synopsis: Shallow and deep copy operations. + +**Source code:** :source:`Lib/copy.py` + +-------------- + +Assignment statements in Python do not copy objects, they create bindings +between a target and an object. For collections that are mutable or contain +mutable items, a copy is sometimes needed so one can change one copy without +changing the other. This module provides generic shallow and deep copy +operations (explained below). + + +Interface summary: + +.. function:: copy(x) + + Return a shallow copy of *x*. + + +.. function:: deepcopy(x[, memo]) + + Return a deep copy of *x*. + + +.. exception:: error + + Raised for module specific errors. + +.. _shallow_vs_deep_copy: + +The difference between shallow and deep copying is only relevant for compound +objects (objects that contain other objects, like lists or class instances): + +* A *shallow copy* constructs a new compound object and then (to the extent + possible) inserts *references* into it to the objects found in the original. + +* A *deep copy* constructs a new compound object and then, recursively, inserts + *copies* into it of the objects found in the original. + +Two problems often exist with deep copy operations that don't exist with shallow +copy operations: + +* Recursive objects (compound objects that, directly or indirectly, contain a + reference to themselves) may cause a recursive loop. + +* Because deep copy copies everything it may copy too much, such as data + which is intended to be shared between copies. + +The :func:`deepcopy` function avoids these problems by: + +* keeping a ``memo`` dictionary of objects already copied during the current + copying pass; and + +* letting user-defined classes override the copying operation or the set of + components copied. + +This module does not copy types like module, method, stack trace, stack frame, +file, socket, window, array, or any similar types. It does "copy" functions and +classes (shallow and deeply), by returning the original object unchanged; this +is compatible with the way these are treated by the :mod:`pickle` module. + +Shallow copies of dictionaries can be made using :meth:`dict.copy`, and +of lists by assigning a slice of the entire list, for example, +``copied_list = original_list[:]``. + +.. index:: module: pickle + +Classes can use the same interfaces to control copying that they use to control +pickling. See the description of module :mod:`pickle` for information on these +methods. In fact, the :mod:`copy` module uses the registered +pickle functions from the :mod:`copyreg` module. + +.. index:: + single: __copy__() (copy protocol) + single: __deepcopy__() (copy protocol) + +In order for a class to define its own copy implementation, it can define +special methods :meth:`__copy__` and :meth:`__deepcopy__`. The former is called +to implement the shallow copy operation; no additional arguments are passed. +The latter is called to implement the deep copy operation; it is passed one +argument, the ``memo`` dictionary. If the :meth:`__deepcopy__` implementation needs +to make a deep copy of a component, it should call the :func:`deepcopy` function +with the component as first argument and the memo dictionary as second argument. + + +.. seealso:: + + Module :mod:`pickle` + Discussion of the special methods used to support object state retrieval and + restoration. + diff --git a/cpython_2/environment/repo/Doc/library/copyreg.rst b/cpython_2/environment/repo/Doc/library/copyreg.rst new file mode 100644 index 0000000000000000000000000000000000000000..439202100959516f1e492f82292a1b288776bf93 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/copyreg.rst @@ -0,0 +1,65 @@ +:mod:`copyreg` --- Register :mod:`pickle` support functions +=========================================================== + +.. module:: copyreg + :synopsis: Register pickle support functions. + +**Source code:** :source:`Lib/copyreg.py` + +.. index:: + module: pickle + module: copy + +-------------- + +The :mod:`copyreg` module offers a way to define functions used while pickling +specific objects. The :mod:`pickle` and :mod:`copy` modules use those functions +when pickling/copying those objects. The module provides configuration +information about object constructors which are not classes. +Such constructors may be factory functions or class instances. + + +.. function:: constructor(object) + + Declares *object* to be a valid constructor. If *object* is not callable (and + hence not valid as a constructor), raises :exc:`TypeError`. + + +.. function:: pickle(type, function, constructor=None) + + Declares that *function* should be used as a "reduction" function for objects + of type *type*. *function* should return either a string or a tuple + containing two or three elements. + + The optional *constructor* parameter, if provided, is a callable object which + can be used to reconstruct the object when called with the tuple of arguments + returned by *function* at pickling time. :exc:`TypeError` will be raised if + *object* is a class or *constructor* is not callable. + + See the :mod:`pickle` module for more details on the interface + expected of *function* and *constructor*. Note that the + :attr:`~pickle.Pickler.dispatch_table` attribute of a pickler + object or subclass of :class:`pickle.Pickler` can also be used for + declaring reduction functions. + +Example +------- + +The example below would like to show how to register a pickle function and how +it will be used: + + >>> import copyreg, copy, pickle + >>> class C: + ... def __init__(self, a): + ... self.a = a + ... + >>> def pickle_c(c): + ... print("pickling a C instance...") + ... return C, (c.a,) + ... + >>> copyreg.pickle(C, pickle_c) + >>> c = C(1) + >>> d = copy.copy(c) # doctest: +SKIP + pickling a C instance... + >>> p = pickle.dumps(c) # doctest: +SKIP + pickling a C instance... diff --git a/cpython_2/environment/repo/Doc/library/crypt.rst b/cpython_2/environment/repo/Doc/library/crypt.rst new file mode 100644 index 0000000000000000000000000000000000000000..d25c626a175854ac5edca4c2f5d30a30bdb60e94 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/crypt.rst @@ -0,0 +1,175 @@ +:mod:`crypt` --- Function to check Unix passwords +================================================= + +.. module:: crypt + :platform: Unix + :synopsis: The crypt() function used to check Unix passwords. + +.. moduleauthor:: Steven D. Majewski +.. sectionauthor:: Steven D. Majewski +.. sectionauthor:: Peter Funk + +**Source code:** :source:`Lib/crypt.py` + +.. index:: + single: crypt(3) + pair: cipher; DES + +-------------- + +This module implements an interface to the :manpage:`crypt(3)` routine, which is +a one-way hash function based upon a modified DES algorithm; see the Unix man +page for further details. Possible uses include storing hashed passwords +so you can check passwords without storing the actual password, or attempting +to crack Unix passwords with a dictionary. + +.. index:: single: crypt(3) + +Notice that the behavior of this module depends on the actual implementation of +the :manpage:`crypt(3)` routine in the running system. Therefore, any +extensions available on the current implementation will also be available on +this module. + +.. availability:: Unix. Not available on VxWorks. + +Hashing Methods +--------------- + +.. versionadded:: 3.3 + +The :mod:`crypt` module defines the list of hashing methods (not all methods +are available on all platforms): + +.. data:: METHOD_SHA512 + + A Modular Crypt Format method with 16 character salt and 86 character + hash based on the SHA-512 hash function. This is the strongest method. + +.. data:: METHOD_SHA256 + + Another Modular Crypt Format method with 16 character salt and 43 + character hash based on the SHA-256 hash function. + +.. data:: METHOD_BLOWFISH + + Another Modular Crypt Format method with 22 character salt and 31 + character hash based on the Blowfish cipher. + + .. versionadded:: 3.7 + +.. data:: METHOD_MD5 + + Another Modular Crypt Format method with 8 character salt and 22 + character hash based on the MD5 hash function. + +.. data:: METHOD_CRYPT + + The traditional method with a 2 character salt and 13 characters of + hash. This is the weakest method. + + +Module Attributes +----------------- + +.. versionadded:: 3.3 + +.. attribute:: methods + + A list of available password hashing algorithms, as + ``crypt.METHOD_*`` objects. This list is sorted from strongest to + weakest. + + +Module Functions +---------------- + +The :mod:`crypt` module defines the following functions: + +.. function:: crypt(word, salt=None) + + *word* will usually be a user's password as typed at a prompt or in a graphical + interface. The optional *salt* is either a string as returned from + :func:`mksalt`, one of the ``crypt.METHOD_*`` values (though not all + may be available on all platforms), or a full encrypted password + including salt, as returned by this function. If *salt* is not + provided, the strongest method will be used (as returned by + :func:`methods`). + + Checking a password is usually done by passing the plain-text password + as *word* and the full results of a previous :func:`crypt` call, + which should be the same as the results of this call. + + *salt* (either a random 2 or 16 character string, possibly prefixed with + ``$digit$`` to indicate the method) which will be used to perturb the + encryption algorithm. The characters in *salt* must be in the set + ``[./a-zA-Z0-9]``, with the exception of Modular Crypt Format which + prefixes a ``$digit$``. + + Returns the hashed password as a string, which will be composed of + characters from the same alphabet as the salt. + + .. index:: single: crypt(3) + + Since a few :manpage:`crypt(3)` extensions allow different values, with + different sizes in the *salt*, it is recommended to use the full crypted + password as salt when checking for a password. + + .. versionchanged:: 3.3 + Accept ``crypt.METHOD_*`` values in addition to strings for *salt*. + + +.. function:: mksalt(method=None, *, rounds=None) + + Return a randomly generated salt of the specified method. If no + *method* is given, the strongest method available as returned by + :func:`methods` is used. + + The return value is a string suitable for passing as the *salt* argument + to :func:`crypt`. + + *rounds* specifies the number of rounds for ``METHOD_SHA256``, + ``METHOD_SHA512`` and ``METHOD_BLOWFISH``. + For ``METHOD_SHA256`` and ``METHOD_SHA512`` it must be an integer between + ``1000`` and ``999_999_999``, the default is ``5000``. For + ``METHOD_BLOWFISH`` it must be a power of two between ``16`` (2\ :sup:`4`) + and ``2_147_483_648`` (2\ :sup:`31`), the default is ``4096`` + (2\ :sup:`12`). + + .. versionadded:: 3.3 + + .. versionchanged:: 3.7 + Added the *rounds* parameter. + + +Examples +-------- + +A simple example illustrating typical use (a constant-time comparison +operation is needed to limit exposure to timing attacks. +:func:`hmac.compare_digest` is suitable for this purpose):: + + import pwd + import crypt + import getpass + from hmac import compare_digest as compare_hash + + def login(): + username = input('Python login: ') + cryptedpasswd = pwd.getpwnam(username)[1] + if cryptedpasswd: + if cryptedpasswd == 'x' or cryptedpasswd == '*': + raise ValueError('no support for shadow passwords') + cleartext = getpass.getpass() + return compare_hash(crypt.crypt(cleartext, cryptedpasswd), cryptedpasswd) + else: + return True + +To generate a hash of a password using the strongest available method and +check it against the original:: + + import crypt + from hmac import compare_digest as compare_hash + + hashed = crypt.crypt(plaintext) + if not compare_hash(hashed, crypt.crypt(plaintext, hashed)): + raise ValueError("hashed version doesn't validate against original") diff --git a/cpython_2/environment/repo/Doc/library/crypto.rst b/cpython_2/environment/repo/Doc/library/crypto.rst new file mode 100644 index 0000000000000000000000000000000000000000..ae45549a6d8941df9dbd82b2ceecd1088d1ef29d --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/crypto.rst @@ -0,0 +1,19 @@ +.. _crypto: + +********************** +Cryptographic Services +********************** + +.. index:: single: cryptography + +The modules described in this chapter implement various algorithms of a +cryptographic nature. They are available at the discretion of the installation. +On Unix systems, the :mod:`crypt` module may also be available. +Here's an overview: + + +.. toctree:: + + hashlib.rst + hmac.rst + secrets.rst diff --git a/cpython_2/environment/repo/Doc/library/csv.rst b/cpython_2/environment/repo/Doc/library/csv.rst new file mode 100644 index 0000000000000000000000000000000000000000..61d39828e0194add42fac1e47fd1393c8a9d10fe --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/csv.rst @@ -0,0 +1,557 @@ +:mod:`csv` --- CSV File Reading and Writing +=========================================== + +.. module:: csv + :synopsis: Write and read tabular data to and from delimited files. + +.. sectionauthor:: Skip Montanaro + +**Source code:** :source:`Lib/csv.py` + +.. index:: + single: csv + pair: data; tabular + +-------------- + +The so-called CSV (Comma Separated Values) format is the most common import and +export format for spreadsheets and databases. CSV format was used for many +years prior to attempts to describe the format in a standardized way in +:rfc:`4180`. The lack of a well-defined standard means that subtle differences +often exist in the data produced and consumed by different applications. These +differences can make it annoying to process CSV files from multiple sources. +Still, while the delimiters and quoting characters vary, the overall format is +similar enough that it is possible to write a single module which can +efficiently manipulate such data, hiding the details of reading and writing the +data from the programmer. + +The :mod:`csv` module implements classes to read and write tabular data in CSV +format. It allows programmers to say, "write this data in the format preferred +by Excel," or "read data from this file which was generated by Excel," without +knowing the precise details of the CSV format used by Excel. Programmers can +also describe the CSV formats understood by other applications or define their +own special-purpose CSV formats. + +The :mod:`csv` module's :class:`reader` and :class:`writer` objects read and +write sequences. Programmers can also read and write data in dictionary form +using the :class:`DictReader` and :class:`DictWriter` classes. + +.. seealso:: + + :pep:`305` - CSV File API + The Python Enhancement Proposal which proposed this addition to Python. + + +.. _csv-contents: + +Module Contents +--------------- + +The :mod:`csv` module defines the following functions: + + +.. index:: + single: universal newlines; csv.reader function + +.. function:: reader(csvfile, dialect='excel', **fmtparams) + + Return a reader object which will iterate over lines in the given *csvfile*. + *csvfile* can be any object which supports the :term:`iterator` protocol and returns a + string each time its :meth:`!__next__` method is called --- :term:`file objects + ` and list objects are both suitable. If *csvfile* is a file object, + it should be opened with ``newline=''``. [1]_ An optional + *dialect* parameter can be given which is used to define a set of parameters + specific to a particular CSV dialect. It may be an instance of a subclass of + the :class:`Dialect` class or one of the strings returned by the + :func:`list_dialects` function. The other optional *fmtparams* keyword arguments + can be given to override individual formatting parameters in the current + dialect. For full details about the dialect and formatting parameters, see + section :ref:`csv-fmt-params`. + + Each row read from the csv file is returned as a list of strings. No + automatic data type conversion is performed unless the ``QUOTE_NONNUMERIC`` format + option is specified (in which case unquoted fields are transformed into floats). + + A short usage example:: + + >>> import csv + >>> with open('eggs.csv', newline='') as csvfile: + ... spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') + ... for row in spamreader: + ... print(', '.join(row)) + Spam, Spam, Spam, Spam, Spam, Baked Beans + Spam, Lovely Spam, Wonderful Spam + + +.. function:: writer(csvfile, dialect='excel', **fmtparams) + + Return a writer object responsible for converting the user's data into delimited + strings on the given file-like object. *csvfile* can be any object with a + :func:`write` method. If *csvfile* is a file object, it should be opened with + ``newline=''`` [1]_. An optional *dialect* + parameter can be given which is used to define a set of parameters specific to a + particular CSV dialect. It may be an instance of a subclass of the + :class:`Dialect` class or one of the strings returned by the + :func:`list_dialects` function. The other optional *fmtparams* keyword arguments + can be given to override individual formatting parameters in the current + dialect. For full details about the dialect and formatting parameters, see + section :ref:`csv-fmt-params`. To make it + as easy as possible to interface with modules which implement the DB API, the + value :const:`None` is written as the empty string. While this isn't a + reversible transformation, it makes it easier to dump SQL NULL data values to + CSV files without preprocessing the data returned from a ``cursor.fetch*`` call. + All other non-string data are stringified with :func:`str` before being written. + + A short usage example:: + + import csv + with open('eggs.csv', 'w', newline='') as csvfile: + spamwriter = csv.writer(csvfile, delimiter=' ', + quotechar='|', quoting=csv.QUOTE_MINIMAL) + spamwriter.writerow(['Spam'] * 5 + ['Baked Beans']) + spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam']) + + +.. function:: register_dialect(name[, dialect[, **fmtparams]]) + + Associate *dialect* with *name*. *name* must be a string. The + dialect can be specified either by passing a sub-class of :class:`Dialect`, or + by *fmtparams* keyword arguments, or both, with keyword arguments overriding + parameters of the dialect. For full details about the dialect and formatting + parameters, see section :ref:`csv-fmt-params`. + + +.. function:: unregister_dialect(name) + + Delete the dialect associated with *name* from the dialect registry. An + :exc:`Error` is raised if *name* is not a registered dialect name. + + +.. function:: get_dialect(name) + + Return the dialect associated with *name*. An :exc:`Error` is raised if + *name* is not a registered dialect name. This function returns an immutable + :class:`Dialect`. + +.. function:: list_dialects() + + Return the names of all registered dialects. + + +.. function:: field_size_limit([new_limit]) + + Returns the current maximum field size allowed by the parser. If *new_limit* is + given, this becomes the new limit. + + +The :mod:`csv` module defines the following classes: + +.. class:: DictReader(f, fieldnames=None, restkey=None, restval=None, \ + dialect='excel', *args, **kwds) + + Create an object that operates like a regular reader but maps the + information in each row to a :class:`dict` whose keys are given by the + optional *fieldnames* parameter. + + The *fieldnames* parameter is a :term:`sequence`. If *fieldnames* is + omitted, the values in the first row of file *f* will be used as the + fieldnames. Regardless of how the fieldnames are determined, the + dictionary preserves their original ordering. + + If a row has more fields than fieldnames, the remaining data is put in a + list and stored with the fieldname specified by *restkey* (which defaults + to ``None``). If a non-blank row has fewer fields than fieldnames, the + missing values are filled-in with the value of *restval* (which defaults + to ``None``). + + All other optional or keyword arguments are passed to the underlying + :class:`reader` instance. + + .. versionchanged:: 3.8 + Returned rows are now of type :class:`dict`. + + A short usage example:: + + >>> import csv + >>> with open('names.csv', newline='') as csvfile: + ... reader = csv.DictReader(csvfile) + ... for row in reader: + ... print(row['first_name'], row['last_name']) + ... + Eric Idle + John Cleese + + >>> print(row) + {'first_name': 'John', 'last_name': 'Cleese'} + + +.. class:: DictWriter(f, fieldnames, restval='', extrasaction='raise', \ + dialect='excel', *args, **kwds) + + Create an object which operates like a regular writer but maps dictionaries + onto output rows. The *fieldnames* parameter is a :mod:`sequence + ` of keys that identify the order in which values in the + dictionary passed to the :meth:`writerow` method are written to file + *f*. The optional *restval* parameter specifies the value to be + written if the dictionary is missing a key in *fieldnames*. If the + dictionary passed to the :meth:`writerow` method contains a key not found in + *fieldnames*, the optional *extrasaction* parameter indicates what action to + take. + If it is set to ``'raise'``, the default value, a :exc:`ValueError` + is raised. + If it is set to ``'ignore'``, extra values in the dictionary are ignored. + Any other optional or keyword arguments are passed to the underlying + :class:`writer` instance. + + Note that unlike the :class:`DictReader` class, the *fieldnames* parameter + of the :class:`DictWriter` class is not optional. + + A short usage example:: + + import csv + + with open('names.csv', 'w', newline='') as csvfile: + fieldnames = ['first_name', 'last_name'] + writer = csv.DictWriter(csvfile, fieldnames=fieldnames) + + writer.writeheader() + writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'}) + writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'}) + writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'}) + + +.. class:: Dialect + + The :class:`Dialect` class is a container class relied on primarily for its + attributes, which are used to define the parameters for a specific + :class:`reader` or :class:`writer` instance. + + +.. class:: excel() + + The :class:`excel` class defines the usual properties of an Excel-generated CSV + file. It is registered with the dialect name ``'excel'``. + + +.. class:: excel_tab() + + The :class:`excel_tab` class defines the usual properties of an Excel-generated + TAB-delimited file. It is registered with the dialect name ``'excel-tab'``. + + +.. class:: unix_dialect() + + The :class:`unix_dialect` class defines the usual properties of a CSV file + generated on UNIX systems, i.e. using ``'\n'`` as line terminator and quoting + all fields. It is registered with the dialect name ``'unix'``. + + .. versionadded:: 3.2 + + +.. class:: Sniffer() + + The :class:`Sniffer` class is used to deduce the format of a CSV file. + + The :class:`Sniffer` class provides two methods: + + .. method:: sniff(sample, delimiters=None) + + Analyze the given *sample* and return a :class:`Dialect` subclass + reflecting the parameters found. If the optional *delimiters* parameter + is given, it is interpreted as a string containing possible valid + delimiter characters. + + + .. method:: has_header(sample) + + Analyze the sample text (presumed to be in CSV format) and return + :const:`True` if the first row appears to be a series of column headers. + +An example for :class:`Sniffer` use:: + + with open('example.csv', newline='') as csvfile: + dialect = csv.Sniffer().sniff(csvfile.read(1024)) + csvfile.seek(0) + reader = csv.reader(csvfile, dialect) + # ... process CSV file contents here ... + + +The :mod:`csv` module defines the following constants: + +.. data:: QUOTE_ALL + + Instructs :class:`writer` objects to quote all fields. + + +.. data:: QUOTE_MINIMAL + + Instructs :class:`writer` objects to only quote those fields which contain + special characters such as *delimiter*, *quotechar* or any of the characters in + *lineterminator*. + + +.. data:: QUOTE_NONNUMERIC + + Instructs :class:`writer` objects to quote all non-numeric fields. + + Instructs the reader to convert all non-quoted fields to type *float*. + + +.. data:: QUOTE_NONE + + Instructs :class:`writer` objects to never quote fields. When the current + *delimiter* occurs in output data it is preceded by the current *escapechar* + character. If *escapechar* is not set, the writer will raise :exc:`Error` if + any characters that require escaping are encountered. + + Instructs :class:`reader` to perform no special processing of quote characters. + +The :mod:`csv` module defines the following exception: + + +.. exception:: Error + + Raised by any of the functions when an error is detected. + +.. _csv-fmt-params: + +Dialects and Formatting Parameters +---------------------------------- + +To make it easier to specify the format of input and output records, specific +formatting parameters are grouped together into dialects. A dialect is a +subclass of the :class:`Dialect` class having a set of specific methods and a +single :meth:`validate` method. When creating :class:`reader` or +:class:`writer` objects, the programmer can specify a string or a subclass of +the :class:`Dialect` class as the dialect parameter. In addition to, or instead +of, the *dialect* parameter, the programmer can also specify individual +formatting parameters, which have the same names as the attributes defined below +for the :class:`Dialect` class. + +Dialects support the following attributes: + + +.. attribute:: Dialect.delimiter + + A one-character string used to separate fields. It defaults to ``','``. + + +.. attribute:: Dialect.doublequote + + Controls how instances of *quotechar* appearing inside a field should + themselves be quoted. When :const:`True`, the character is doubled. When + :const:`False`, the *escapechar* is used as a prefix to the *quotechar*. It + defaults to :const:`True`. + + On output, if *doublequote* is :const:`False` and no *escapechar* is set, + :exc:`Error` is raised if a *quotechar* is found in a field. + + +.. attribute:: Dialect.escapechar + + A one-character string used by the writer to escape the *delimiter* if *quoting* + is set to :const:`QUOTE_NONE` and the *quotechar* if *doublequote* is + :const:`False`. On reading, the *escapechar* removes any special meaning from + the following character. It defaults to :const:`None`, which disables escaping. + + +.. attribute:: Dialect.lineterminator + + The string used to terminate lines produced by the :class:`writer`. It defaults + to ``'\r\n'``. + + .. note:: + + The :class:`reader` is hard-coded to recognise either ``'\r'`` or ``'\n'`` as + end-of-line, and ignores *lineterminator*. This behavior may change in the + future. + + +.. attribute:: Dialect.quotechar + + A one-character string used to quote fields containing special characters, such + as the *delimiter* or *quotechar*, or which contain new-line characters. It + defaults to ``'"'``. + + +.. attribute:: Dialect.quoting + + Controls when quotes should be generated by the writer and recognised by the + reader. It can take on any of the :const:`QUOTE_\*` constants (see section + :ref:`csv-contents`) and defaults to :const:`QUOTE_MINIMAL`. + + +.. attribute:: Dialect.skipinitialspace + + When :const:`True`, whitespace immediately following the *delimiter* is ignored. + The default is :const:`False`. + + +.. attribute:: Dialect.strict + + When ``True``, raise exception :exc:`Error` on bad CSV input. + The default is ``False``. + +Reader Objects +-------------- + +Reader objects (:class:`DictReader` instances and objects returned by the +:func:`reader` function) have the following public methods: + +.. method:: csvreader.__next__() + + Return the next row of the reader's iterable object as a list (if the object + was returned from :func:`reader`) or a dict (if it is a :class:`DictReader` + instance), parsed according to the current dialect. Usually you should call + this as ``next(reader)``. + + +Reader objects have the following public attributes: + +.. attribute:: csvreader.dialect + + A read-only description of the dialect in use by the parser. + + +.. attribute:: csvreader.line_num + + The number of lines read from the source iterator. This is not the same as the + number of records returned, as records can span multiple lines. + + +DictReader objects have the following public attribute: + +.. attribute:: csvreader.fieldnames + + If not passed as a parameter when creating the object, this attribute is + initialized upon first access or when the first record is read from the + file. + + + +Writer Objects +-------------- + +:class:`Writer` objects (:class:`DictWriter` instances and objects returned by +the :func:`writer` function) have the following public methods. A *row* must be +an iterable of strings or numbers for :class:`Writer` objects and a dictionary +mapping fieldnames to strings or numbers (by passing them through :func:`str` +first) for :class:`DictWriter` objects. Note that complex numbers are written +out surrounded by parens. This may cause some problems for other programs which +read CSV files (assuming they support complex numbers at all). + + +.. method:: csvwriter.writerow(row) + + Write the *row* parameter to the writer's file object, formatted according to + the current dialect. Return the return value of the call to the *write* method + of the underlying file object. + + .. versionchanged:: 3.5 + Added support of arbitrary iterables. + +.. method:: csvwriter.writerows(rows) + + Write all elements in *rows* (an iterable of *row* objects as described + above) to the writer's file object, formatted according to the current + dialect. + +Writer objects have the following public attribute: + + +.. attribute:: csvwriter.dialect + + A read-only description of the dialect in use by the writer. + + +DictWriter objects have the following public method: + + +.. method:: DictWriter.writeheader() + + Write a row with the field names (as specified in the constructor) to + the writer's file object, formatted according to the current dialect. Return + the return value of the :meth:`csvwriter.writerow` call used internally. + + .. versionadded:: 3.2 + .. versionchanged:: 3.8 + :meth:`writeheader` now also returns the value returned by + the :meth:`csvwriter.writerow` method it uses internally. + + +.. _csv-examples: + +Examples +-------- + +The simplest example of reading a CSV file:: + + import csv + with open('some.csv', newline='') as f: + reader = csv.reader(f) + for row in reader: + print(row) + +Reading a file with an alternate format:: + + import csv + with open('passwd', newline='') as f: + reader = csv.reader(f, delimiter=':', quoting=csv.QUOTE_NONE) + for row in reader: + print(row) + +The corresponding simplest possible writing example is:: + + import csv + with open('some.csv', 'w', newline='') as f: + writer = csv.writer(f) + writer.writerows(someiterable) + +Since :func:`open` is used to open a CSV file for reading, the file +will by default be decoded into unicode using the system default +encoding (see :func:`locale.getpreferredencoding`). To decode a file +using a different encoding, use the ``encoding`` argument of open:: + + import csv + with open('some.csv', newline='', encoding='utf-8') as f: + reader = csv.reader(f) + for row in reader: + print(row) + +The same applies to writing in something other than the system default +encoding: specify the encoding argument when opening the output file. + +Registering a new dialect:: + + import csv + csv.register_dialect('unixpwd', delimiter=':', quoting=csv.QUOTE_NONE) + with open('passwd', newline='') as f: + reader = csv.reader(f, 'unixpwd') + +A slightly more advanced use of the reader --- catching and reporting errors:: + + import csv, sys + filename = 'some.csv' + with open(filename, newline='') as f: + reader = csv.reader(f) + try: + for row in reader: + print(row) + except csv.Error as e: + sys.exit('file {}, line {}: {}'.format(filename, reader.line_num, e)) + +And while the module doesn't directly support parsing strings, it can easily be +done:: + + import csv + for row in csv.reader(['one,two,three']): + print(row) + + +.. rubric:: Footnotes + +.. [1] If ``newline=''`` is not specified, newlines embedded inside quoted fields + will not be interpreted correctly, and on platforms that use ``\r\n`` linendings + on write an extra ``\r`` will be added. It should always be safe to specify + ``newline=''``, since the csv module does its own + (:term:`universal `) newline handling. diff --git a/cpython_2/environment/repo/Doc/library/ctypes.rst b/cpython_2/environment/repo/Doc/library/ctypes.rst new file mode 100644 index 0000000000000000000000000000000000000000..2d6c6d0a1c3c574c2648a2eb76631f633af2e7e7 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/ctypes.rst @@ -0,0 +1,2548 @@ +:mod:`ctypes` --- A foreign function library for Python +======================================================= + +.. module:: ctypes + :synopsis: A foreign function library for Python. + +.. moduleauthor:: Thomas Heller + +-------------- + +:mod:`ctypes` is a foreign function library for Python. It provides C compatible +data types, and allows calling functions in DLLs or shared libraries. It can be +used to wrap these libraries in pure Python. + + +.. _ctypes-ctypes-tutorial: + +ctypes tutorial +--------------- + +Note: The code samples in this tutorial use :mod:`doctest` to make sure that +they actually work. Since some code samples behave differently under Linux, +Windows, or Mac OS X, they contain doctest directives in comments. + +Note: Some code samples reference the ctypes :class:`c_int` type. On platforms +where ``sizeof(long) == sizeof(int)`` it is an alias to :class:`c_long`. +So, you should not be confused if :class:`c_long` is printed if you would expect +:class:`c_int` --- they are actually the same type. + +.. _ctypes-loading-dynamic-link-libraries: + +Loading dynamic link libraries +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +:mod:`ctypes` exports the *cdll*, and on Windows *windll* and *oledll* +objects, for loading dynamic link libraries. + +You load libraries by accessing them as attributes of these objects. *cdll* +loads libraries which export functions using the standard ``cdecl`` calling +convention, while *windll* libraries call functions using the ``stdcall`` +calling convention. *oledll* also uses the ``stdcall`` calling convention, and +assumes the functions return a Windows :c:type:`HRESULT` error code. The error +code is used to automatically raise an :class:`OSError` exception when the +function call fails. + +.. versionchanged:: 3.3 + Windows errors used to raise :exc:`WindowsError`, which is now an alias + of :exc:`OSError`. + + +Here are some examples for Windows. Note that ``msvcrt`` is the MS standard C +library containing most standard C functions, and uses the cdecl calling +convention:: + + >>> from ctypes import * + >>> print(windll.kernel32) # doctest: +WINDOWS + + >>> print(cdll.msvcrt) # doctest: +WINDOWS + + >>> libc = cdll.msvcrt # doctest: +WINDOWS + >>> + +Windows appends the usual ``.dll`` file suffix automatically. + +.. note:: + Accessing the standard C library through ``cdll.msvcrt`` will use an + outdated version of the library that may be incompatible with the one + being used by Python. Where possible, use native Python functionality, + or else import and use the ``msvcrt`` module. + +On Linux, it is required to specify the filename *including* the extension to +load a library, so attribute access can not be used to load libraries. Either the +:meth:`LoadLibrary` method of the dll loaders should be used, or you should load +the library by creating an instance of CDLL by calling the constructor:: + + >>> cdll.LoadLibrary("libc.so.6") # doctest: +LINUX + + >>> libc = CDLL("libc.so.6") # doctest: +LINUX + >>> libc # doctest: +LINUX + + >>> + +.. XXX Add section for Mac OS X. + + +.. _ctypes-accessing-functions-from-loaded-dlls: + +Accessing functions from loaded dlls +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Functions are accessed as attributes of dll objects:: + + >>> from ctypes import * + >>> libc.printf + <_FuncPtr object at 0x...> + >>> print(windll.kernel32.GetModuleHandleA) # doctest: +WINDOWS + <_FuncPtr object at 0x...> + >>> print(windll.kernel32.MyOwnFunction) # doctest: +WINDOWS + Traceback (most recent call last): + File "", line 1, in + File "ctypes.py", line 239, in __getattr__ + func = _StdcallFuncPtr(name, self) + AttributeError: function 'MyOwnFunction' not found + >>> + +Note that win32 system dlls like ``kernel32`` and ``user32`` often export ANSI +as well as UNICODE versions of a function. The UNICODE version is exported with +an ``W`` appended to the name, while the ANSI version is exported with an ``A`` +appended to the name. The win32 ``GetModuleHandle`` function, which returns a +*module handle* for a given module name, has the following C prototype, and a +macro is used to expose one of them as ``GetModuleHandle`` depending on whether +UNICODE is defined or not:: + + /* ANSI version */ + HMODULE GetModuleHandleA(LPCSTR lpModuleName); + /* UNICODE version */ + HMODULE GetModuleHandleW(LPCWSTR lpModuleName); + +*windll* does not try to select one of them by magic, you must access the +version you need by specifying ``GetModuleHandleA`` or ``GetModuleHandleW`` +explicitly, and then call it with bytes or string objects respectively. + +Sometimes, dlls export functions with names which aren't valid Python +identifiers, like ``"??2@YAPAXI@Z"``. In this case you have to use +:func:`getattr` to retrieve the function:: + + >>> getattr(cdll.msvcrt, "??2@YAPAXI@Z") # doctest: +WINDOWS + <_FuncPtr object at 0x...> + >>> + +On Windows, some dlls export functions not by name but by ordinal. These +functions can be accessed by indexing the dll object with the ordinal number:: + + >>> cdll.kernel32[1] # doctest: +WINDOWS + <_FuncPtr object at 0x...> + >>> cdll.kernel32[0] # doctest: +WINDOWS + Traceback (most recent call last): + File "", line 1, in + File "ctypes.py", line 310, in __getitem__ + func = _StdcallFuncPtr(name, self) + AttributeError: function ordinal 0 not found + >>> + + +.. _ctypes-calling-functions: + +Calling functions +^^^^^^^^^^^^^^^^^ + +You can call these functions like any other Python callable. This example uses +the ``time()`` function, which returns system time in seconds since the Unix +epoch, and the ``GetModuleHandleA()`` function, which returns a win32 module +handle. + +This example calls both functions with a ``NULL`` pointer (``None`` should be used +as the ``NULL`` pointer):: + + >>> print(libc.time(None)) # doctest: +SKIP + 1150640792 + >>> print(hex(windll.kernel32.GetModuleHandleA(None))) # doctest: +WINDOWS + 0x1d000000 + >>> + +:exc:`ValueError` is raised when you call an ``stdcall`` function with the +``cdecl`` calling convention, or vice versa:: + + >>> cdll.kernel32.GetModuleHandleA(None) # doctest: +WINDOWS + Traceback (most recent call last): + File "", line 1, in + ValueError: Procedure probably called with not enough arguments (4 bytes missing) + >>> + + >>> windll.msvcrt.printf(b"spam") # doctest: +WINDOWS + Traceback (most recent call last): + File "", line 1, in + ValueError: Procedure probably called with too many arguments (4 bytes in excess) + >>> + +To find out the correct calling convention you have to look into the C header +file or the documentation for the function you want to call. + +On Windows, :mod:`ctypes` uses win32 structured exception handling to prevent +crashes from general protection faults when functions are called with invalid +argument values:: + + >>> windll.kernel32.GetModuleHandleA(32) # doctest: +WINDOWS + Traceback (most recent call last): + File "", line 1, in + OSError: exception: access violation reading 0x00000020 + >>> + +There are, however, enough ways to crash Python with :mod:`ctypes`, so you +should be careful anyway. The :mod:`faulthandler` module can be helpful in +debugging crashes (e.g. from segmentation faults produced by erroneous C library +calls). + +``None``, integers, bytes objects and (unicode) strings are the only native +Python objects that can directly be used as parameters in these function calls. +``None`` is passed as a C ``NULL`` pointer, bytes objects and strings are passed +as pointer to the memory block that contains their data (:c:type:`char *` or +:c:type:`wchar_t *`). Python integers are passed as the platforms default C +:c:type:`int` type, their value is masked to fit into the C type. + +Before we move on calling functions with other parameter types, we have to learn +more about :mod:`ctypes` data types. + + +.. _ctypes-fundamental-data-types: + +Fundamental data types +^^^^^^^^^^^^^^^^^^^^^^ + +:mod:`ctypes` defines a number of primitive C compatible data types: + ++----------------------+------------------------------------------+----------------------------+ +| ctypes type | C type | Python type | ++======================+==========================================+============================+ +| :class:`c_bool` | :c:type:`_Bool` | bool (1) | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_char` | :c:type:`char` | 1-character bytes object | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_wchar` | :c:type:`wchar_t` | 1-character string | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_byte` | :c:type:`char` | int | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_ubyte` | :c:type:`unsigned char` | int | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_short` | :c:type:`short` | int | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_ushort` | :c:type:`unsigned short` | int | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_int` | :c:type:`int` | int | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_uint` | :c:type:`unsigned int` | int | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_long` | :c:type:`long` | int | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_ulong` | :c:type:`unsigned long` | int | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_longlong` | :c:type:`__int64` or :c:type:`long long` | int | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_ulonglong` | :c:type:`unsigned __int64` or | int | +| | :c:type:`unsigned long long` | | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_size_t` | :c:type:`size_t` | int | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_ssize_t` | :c:type:`ssize_t` or | int | +| | :c:type:`Py_ssize_t` | | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_float` | :c:type:`float` | float | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_double` | :c:type:`double` | float | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_longdouble`| :c:type:`long double` | float | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_char_p` | :c:type:`char *` (NUL terminated) | bytes object or ``None`` | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_wchar_p` | :c:type:`wchar_t *` (NUL terminated) | string or ``None`` | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_void_p` | :c:type:`void *` | int or ``None`` | ++----------------------+------------------------------------------+----------------------------+ + +(1) + The constructor accepts any object with a truth value. + +All these types can be created by calling them with an optional initializer of +the correct type and value:: + + >>> c_int() + c_long(0) + >>> c_wchar_p("Hello, World") + c_wchar_p(140018365411392) + >>> c_ushort(-3) + c_ushort(65533) + >>> + +Since these types are mutable, their value can also be changed afterwards:: + + >>> i = c_int(42) + >>> print(i) + c_long(42) + >>> print(i.value) + 42 + >>> i.value = -99 + >>> print(i.value) + -99 + >>> + +Assigning a new value to instances of the pointer types :class:`c_char_p`, +:class:`c_wchar_p`, and :class:`c_void_p` changes the *memory location* they +point to, *not the contents* of the memory block (of course not, because Python +bytes objects are immutable):: + + >>> s = "Hello, World" + >>> c_s = c_wchar_p(s) + >>> print(c_s) + c_wchar_p(139966785747344) + >>> print(c_s.value) + Hello World + >>> c_s.value = "Hi, there" + >>> print(c_s) # the memory location has changed + c_wchar_p(139966783348904) + >>> print(c_s.value) + Hi, there + >>> print(s) # first object is unchanged + Hello, World + >>> + +You should be careful, however, not to pass them to functions expecting pointers +to mutable memory. If you need mutable memory blocks, ctypes has a +:func:`create_string_buffer` function which creates these in various ways. The +current memory block contents can be accessed (or changed) with the ``raw`` +property; if you want to access it as NUL terminated string, use the ``value`` +property:: + + >>> from ctypes import * + >>> p = create_string_buffer(3) # create a 3 byte buffer, initialized to NUL bytes + >>> print(sizeof(p), repr(p.raw)) + 3 b'\x00\x00\x00' + >>> p = create_string_buffer(b"Hello") # create a buffer containing a NUL terminated string + >>> print(sizeof(p), repr(p.raw)) + 6 b'Hello\x00' + >>> print(repr(p.value)) + b'Hello' + >>> p = create_string_buffer(b"Hello", 10) # create a 10 byte buffer + >>> print(sizeof(p), repr(p.raw)) + 10 b'Hello\x00\x00\x00\x00\x00' + >>> p.value = b"Hi" + >>> print(sizeof(p), repr(p.raw)) + 10 b'Hi\x00lo\x00\x00\x00\x00\x00' + >>> + +The :func:`create_string_buffer` function replaces the :func:`c_buffer` function +(which is still available as an alias), as well as the :func:`c_string` function +from earlier ctypes releases. To create a mutable memory block containing +unicode characters of the C type :c:type:`wchar_t` use the +:func:`create_unicode_buffer` function. + + +.. _ctypes-calling-functions-continued: + +Calling functions, continued +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Note that printf prints to the real standard output channel, *not* to +:data:`sys.stdout`, so these examples will only work at the console prompt, not +from within *IDLE* or *PythonWin*:: + + >>> printf = libc.printf + >>> printf(b"Hello, %s\n", b"World!") + Hello, World! + 14 + >>> printf(b"Hello, %S\n", "World!") + Hello, World! + 14 + >>> printf(b"%d bottles of beer\n", 42) + 42 bottles of beer + 19 + >>> printf(b"%f bottles of beer\n", 42.5) + Traceback (most recent call last): + File "", line 1, in + ArgumentError: argument 2: exceptions.TypeError: Don't know how to convert parameter 2 + >>> + +As has been mentioned before, all Python types except integers, strings, and +bytes objects have to be wrapped in their corresponding :mod:`ctypes` type, so +that they can be converted to the required C data type:: + + >>> printf(b"An int %d, a double %f\n", 1234, c_double(3.14)) + An int 1234, a double 3.140000 + 31 + >>> + + +.. _ctypes-calling-functions-with-own-custom-data-types: + +Calling functions with your own custom data types +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +You can also customize :mod:`ctypes` argument conversion to allow instances of +your own classes be used as function arguments. :mod:`ctypes` looks for an +:attr:`_as_parameter_` attribute and uses this as the function argument. Of +course, it must be one of integer, string, or bytes:: + + >>> class Bottles: + ... def __init__(self, number): + ... self._as_parameter_ = number + ... + >>> bottles = Bottles(42) + >>> printf(b"%d bottles of beer\n", bottles) + 42 bottles of beer + 19 + >>> + +If you don't want to store the instance's data in the :attr:`_as_parameter_` +instance variable, you could define a :class:`property` which makes the +attribute available on request. + + +.. _ctypes-specifying-required-argument-types: + +Specifying the required argument types (function prototypes) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +It is possible to specify the required argument types of functions exported from +DLLs by setting the :attr:`argtypes` attribute. + +:attr:`argtypes` must be a sequence of C data types (the ``printf`` function is +probably not a good example here, because it takes a variable number and +different types of parameters depending on the format string, on the other hand +this is quite handy to experiment with this feature):: + + >>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double] + >>> printf(b"String '%s', Int %d, Double %f\n", b"Hi", 10, 2.2) + String 'Hi', Int 10, Double 2.200000 + 37 + >>> + +Specifying a format protects against incompatible argument types (just as a +prototype for a C function), and tries to convert the arguments to valid types:: + + >>> printf(b"%d %d %d", 1, 2, 3) + Traceback (most recent call last): + File "", line 1, in + ArgumentError: argument 2: exceptions.TypeError: wrong type + >>> printf(b"%s %d %f\n", b"X", 2, 3) + X 2 3.000000 + 13 + >>> + +If you have defined your own classes which you pass to function calls, you have +to implement a :meth:`from_param` class method for them to be able to use them +in the :attr:`argtypes` sequence. The :meth:`from_param` class method receives +the Python object passed to the function call, it should do a typecheck or +whatever is needed to make sure this object is acceptable, and then return the +object itself, its :attr:`_as_parameter_` attribute, or whatever you want to +pass as the C function argument in this case. Again, the result should be an +integer, string, bytes, a :mod:`ctypes` instance, or an object with an +:attr:`_as_parameter_` attribute. + + +.. _ctypes-return-types: + +Return types +^^^^^^^^^^^^ + +By default functions are assumed to return the C :c:type:`int` type. Other +return types can be specified by setting the :attr:`restype` attribute of the +function object. + +Here is a more advanced example, it uses the ``strchr`` function, which expects +a string pointer and a char, and returns a pointer to a string:: + + >>> strchr = libc.strchr + >>> strchr(b"abcdef", ord("d")) # doctest: +SKIP + 8059983 + >>> strchr.restype = c_char_p # c_char_p is a pointer to a string + >>> strchr(b"abcdef", ord("d")) + b'def' + >>> print(strchr(b"abcdef", ord("x"))) + None + >>> + +If you want to avoid the ``ord("x")`` calls above, you can set the +:attr:`argtypes` attribute, and the second argument will be converted from a +single character Python bytes object into a C char:: + + >>> strchr.restype = c_char_p + >>> strchr.argtypes = [c_char_p, c_char] + >>> strchr(b"abcdef", b"d") + 'def' + >>> strchr(b"abcdef", b"def") + Traceback (most recent call last): + File "", line 1, in + ArgumentError: argument 2: exceptions.TypeError: one character string expected + >>> print(strchr(b"abcdef", b"x")) + None + >>> strchr(b"abcdef", b"d") + 'def' + >>> + +You can also use a callable Python object (a function or a class for example) as +the :attr:`restype` attribute, if the foreign function returns an integer. The +callable will be called with the *integer* the C function returns, and the +result of this call will be used as the result of your function call. This is +useful to check for error return values and automatically raise an exception:: + + >>> GetModuleHandle = windll.kernel32.GetModuleHandleA # doctest: +WINDOWS + >>> def ValidHandle(value): + ... if value == 0: + ... raise WinError() + ... return value + ... + >>> + >>> GetModuleHandle.restype = ValidHandle # doctest: +WINDOWS + >>> GetModuleHandle(None) # doctest: +WINDOWS + 486539264 + >>> GetModuleHandle("something silly") # doctest: +WINDOWS + Traceback (most recent call last): + File "", line 1, in + File "", line 3, in ValidHandle + OSError: [Errno 126] The specified module could not be found. + >>> + +``WinError`` is a function which will call Windows ``FormatMessage()`` api to +get the string representation of an error code, and *returns* an exception. +``WinError`` takes an optional error code parameter, if no one is used, it calls +:func:`GetLastError` to retrieve it. + +Please note that a much more powerful error checking mechanism is available +through the :attr:`errcheck` attribute; see the reference manual for details. + + +.. _ctypes-passing-pointers: + +Passing pointers (or: passing parameters by reference) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Sometimes a C api function expects a *pointer* to a data type as parameter, +probably to write into the corresponding location, or if the data is too large +to be passed by value. This is also known as *passing parameters by reference*. + +:mod:`ctypes` exports the :func:`byref` function which is used to pass parameters +by reference. The same effect can be achieved with the :func:`pointer` function, +although :func:`pointer` does a lot more work since it constructs a real pointer +object, so it is faster to use :func:`byref` if you don't need the pointer +object in Python itself:: + + >>> i = c_int() + >>> f = c_float() + >>> s = create_string_buffer(b'\000' * 32) + >>> print(i.value, f.value, repr(s.value)) + 0 0.0 b'' + >>> libc.sscanf(b"1 3.14 Hello", b"%d %f %s", + ... byref(i), byref(f), s) + 3 + >>> print(i.value, f.value, repr(s.value)) + 1 3.1400001049 b'Hello' + >>> + + +.. _ctypes-structures-unions: + +Structures and unions +^^^^^^^^^^^^^^^^^^^^^ + +Structures and unions must derive from the :class:`Structure` and :class:`Union` +base classes which are defined in the :mod:`ctypes` module. Each subclass must +define a :attr:`_fields_` attribute. :attr:`_fields_` must be a list of +*2-tuples*, containing a *field name* and a *field type*. + +The field type must be a :mod:`ctypes` type like :class:`c_int`, or any other +derived :mod:`ctypes` type: structure, union, array, pointer. + +Here is a simple example of a POINT structure, which contains two integers named +*x* and *y*, and also shows how to initialize a structure in the constructor:: + + >>> from ctypes import * + >>> class POINT(Structure): + ... _fields_ = [("x", c_int), + ... ("y", c_int)] + ... + >>> point = POINT(10, 20) + >>> print(point.x, point.y) + 10 20 + >>> point = POINT(y=5) + >>> print(point.x, point.y) + 0 5 + >>> POINT(1, 2, 3) + Traceback (most recent call last): + File "", line 1, in + TypeError: too many initializers + >>> + +You can, however, build much more complicated structures. A structure can +itself contain other structures by using a structure as a field type. + +Here is a RECT structure which contains two POINTs named *upperleft* and +*lowerright*:: + + >>> class RECT(Structure): + ... _fields_ = [("upperleft", POINT), + ... ("lowerright", POINT)] + ... + >>> rc = RECT(point) + >>> print(rc.upperleft.x, rc.upperleft.y) + 0 5 + >>> print(rc.lowerright.x, rc.lowerright.y) + 0 0 + >>> + +Nested structures can also be initialized in the constructor in several ways:: + + >>> r = RECT(POINT(1, 2), POINT(3, 4)) + >>> r = RECT((1, 2), (3, 4)) + +Field :term:`descriptor`\s can be retrieved from the *class*, they are useful +for debugging because they can provide useful information:: + + >>> print(POINT.x) + + >>> print(POINT.y) + + >>> + + +.. _ctypes-structureunion-alignment-byte-order: + +.. warning:: + + :mod:`ctypes` does not support passing unions or structures with bit-fields + to functions by value. While this may work on 32-bit x86, it's not + guaranteed by the library to work in the general case. Unions and + structures with bit-fields should always be passed to functions by pointer. + +Structure/union alignment and byte order +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +By default, Structure and Union fields are aligned in the same way the C +compiler does it. It is possible to override this behavior by specifying a +:attr:`_pack_` class attribute in the subclass definition. This must be set to a +positive integer and specifies the maximum alignment for the fields. This is +what ``#pragma pack(n)`` also does in MSVC. + +:mod:`ctypes` uses the native byte order for Structures and Unions. To build +structures with non-native byte order, you can use one of the +:class:`BigEndianStructure`, :class:`LittleEndianStructure`, +:class:`BigEndianUnion`, and :class:`LittleEndianUnion` base classes. These +classes cannot contain pointer fields. + + +.. _ctypes-bit-fields-in-structures-unions: + +Bit fields in structures and unions +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +It is possible to create structures and unions containing bit fields. Bit fields +are only possible for integer fields, the bit width is specified as the third +item in the :attr:`_fields_` tuples:: + + >>> class Int(Structure): + ... _fields_ = [("first_16", c_int, 16), + ... ("second_16", c_int, 16)] + ... + >>> print(Int.first_16) + + >>> print(Int.second_16) + + >>> + + +.. _ctypes-arrays: + +Arrays +^^^^^^ + +Arrays are sequences, containing a fixed number of instances of the same type. + +The recommended way to create array types is by multiplying a data type with a +positive integer:: + + TenPointsArrayType = POINT * 10 + +Here is an example of a somewhat artificial data type, a structure containing 4 +POINTs among other stuff:: + + >>> from ctypes import * + >>> class POINT(Structure): + ... _fields_ = ("x", c_int), ("y", c_int) + ... + >>> class MyStruct(Structure): + ... _fields_ = [("a", c_int), + ... ("b", c_float), + ... ("point_array", POINT * 4)] + >>> + >>> print(len(MyStruct().point_array)) + 4 + >>> + +Instances are created in the usual way, by calling the class:: + + arr = TenPointsArrayType() + for pt in arr: + print(pt.x, pt.y) + +The above code print a series of ``0 0`` lines, because the array contents is +initialized to zeros. + +Initializers of the correct type can also be specified:: + + >>> from ctypes import * + >>> TenIntegers = c_int * 10 + >>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + >>> print(ii) + + >>> for i in ii: print(i, end=" ") + ... + 1 2 3 4 5 6 7 8 9 10 + >>> + + +.. _ctypes-pointers: + +Pointers +^^^^^^^^ + +Pointer instances are created by calling the :func:`pointer` function on a +:mod:`ctypes` type:: + + >>> from ctypes import * + >>> i = c_int(42) + >>> pi = pointer(i) + >>> + +Pointer instances have a :attr:`~_Pointer.contents` attribute which +returns the object to which the pointer points, the ``i`` object above:: + + >>> pi.contents + c_long(42) + >>> + +Note that :mod:`ctypes` does not have OOR (original object return), it constructs a +new, equivalent object each time you retrieve an attribute:: + + >>> pi.contents is i + False + >>> pi.contents is pi.contents + False + >>> + +Assigning another :class:`c_int` instance to the pointer's contents attribute +would cause the pointer to point to the memory location where this is stored:: + + >>> i = c_int(99) + >>> pi.contents = i + >>> pi.contents + c_long(99) + >>> + +.. XXX Document dereferencing pointers, and that it is preferred over the + .contents attribute. + +Pointer instances can also be indexed with integers:: + + >>> pi[0] + 99 + >>> + +Assigning to an integer index changes the pointed to value:: + + >>> print(i) + c_long(99) + >>> pi[0] = 22 + >>> print(i) + c_long(22) + >>> + +It is also possible to use indexes different from 0, but you must know what +you're doing, just as in C: You can access or change arbitrary memory locations. +Generally you only use this feature if you receive a pointer from a C function, +and you *know* that the pointer actually points to an array instead of a single +item. + +Behind the scenes, the :func:`pointer` function does more than simply create +pointer instances, it has to create pointer *types* first. This is done with the +:func:`POINTER` function, which accepts any :mod:`ctypes` type, and returns a +new type:: + + >>> PI = POINTER(c_int) + >>> PI + + >>> PI(42) + Traceback (most recent call last): + File "", line 1, in + TypeError: expected c_long instead of int + >>> PI(c_int(42)) + + >>> + +Calling the pointer type without an argument creates a ``NULL`` pointer. +``NULL`` pointers have a ``False`` boolean value:: + + >>> null_ptr = POINTER(c_int)() + >>> print(bool(null_ptr)) + False + >>> + +:mod:`ctypes` checks for ``NULL`` when dereferencing pointers (but dereferencing +invalid non-\ ``NULL`` pointers would crash Python):: + + >>> null_ptr[0] + Traceback (most recent call last): + .... + ValueError: NULL pointer access + >>> + + >>> null_ptr[0] = 1234 + Traceback (most recent call last): + .... + ValueError: NULL pointer access + >>> + + +.. _ctypes-type-conversions: + +Type conversions +^^^^^^^^^^^^^^^^ + +Usually, ctypes does strict type checking. This means, if you have +``POINTER(c_int)`` in the :attr:`argtypes` list of a function or as the type of +a member field in a structure definition, only instances of exactly the same +type are accepted. There are some exceptions to this rule, where ctypes accepts +other objects. For example, you can pass compatible array instances instead of +pointer types. So, for ``POINTER(c_int)``, ctypes accepts an array of c_int:: + + >>> class Bar(Structure): + ... _fields_ = [("count", c_int), ("values", POINTER(c_int))] + ... + >>> bar = Bar() + >>> bar.values = (c_int * 3)(1, 2, 3) + >>> bar.count = 3 + >>> for i in range(bar.count): + ... print(bar.values[i]) + ... + 1 + 2 + 3 + >>> + +In addition, if a function argument is explicitly declared to be a pointer type +(such as ``POINTER(c_int)``) in :attr:`argtypes`, an object of the pointed +type (``c_int`` in this case) can be passed to the function. ctypes will apply +the required :func:`byref` conversion in this case automatically. + +To set a POINTER type field to ``NULL``, you can assign ``None``:: + + >>> bar.values = None + >>> + +.. XXX list other conversions... + +Sometimes you have instances of incompatible types. In C, you can cast one type +into another type. :mod:`ctypes` provides a :func:`cast` function which can be +used in the same way. The ``Bar`` structure defined above accepts +``POINTER(c_int)`` pointers or :class:`c_int` arrays for its ``values`` field, +but not instances of other types:: + + >>> bar.values = (c_byte * 4)() + Traceback (most recent call last): + File "", line 1, in + TypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long instance + >>> + +For these cases, the :func:`cast` function is handy. + +The :func:`cast` function can be used to cast a ctypes instance into a pointer +to a different ctypes data type. :func:`cast` takes two parameters, a ctypes +object that is or can be converted to a pointer of some kind, and a ctypes +pointer type. It returns an instance of the second argument, which references +the same memory block as the first argument:: + + >>> a = (c_byte * 4)() + >>> cast(a, POINTER(c_int)) + + >>> + +So, :func:`cast` can be used to assign to the ``values`` field of ``Bar`` the +structure:: + + >>> bar = Bar() + >>> bar.values = cast((c_byte * 4)(), POINTER(c_int)) + >>> print(bar.values[0]) + 0 + >>> + + +.. _ctypes-incomplete-types: + +Incomplete Types +^^^^^^^^^^^^^^^^ + +*Incomplete Types* are structures, unions or arrays whose members are not yet +specified. In C, they are specified by forward declarations, which are defined +later:: + + struct cell; /* forward declaration */ + + struct cell { + char *name; + struct cell *next; + }; + +The straightforward translation into ctypes code would be this, but it does not +work:: + + >>> class cell(Structure): + ... _fields_ = [("name", c_char_p), + ... ("next", POINTER(cell))] + ... + Traceback (most recent call last): + File "", line 1, in + File "", line 2, in cell + NameError: name 'cell' is not defined + >>> + +because the new ``class cell`` is not available in the class statement itself. +In :mod:`ctypes`, we can define the ``cell`` class and set the :attr:`_fields_` +attribute later, after the class statement:: + + >>> from ctypes import * + >>> class cell(Structure): + ... pass + ... + >>> cell._fields_ = [("name", c_char_p), + ... ("next", POINTER(cell))] + >>> + +Let's try it. We create two instances of ``cell``, and let them point to each +other, and finally follow the pointer chain a few times:: + + >>> c1 = cell() + >>> c1.name = "foo" + >>> c2 = cell() + >>> c2.name = "bar" + >>> c1.next = pointer(c2) + >>> c2.next = pointer(c1) + >>> p = c1 + >>> for i in range(8): + ... print(p.name, end=" ") + ... p = p.next[0] + ... + foo bar foo bar foo bar foo bar + >>> + + +.. _ctypes-callback-functions: + +Callback functions +^^^^^^^^^^^^^^^^^^ + +:mod:`ctypes` allows creating C callable function pointers from Python callables. +These are sometimes called *callback functions*. + +First, you must create a class for the callback function. The class knows the +calling convention, the return type, and the number and types of arguments this +function will receive. + +The :func:`CFUNCTYPE` factory function creates types for callback functions +using the ``cdecl`` calling convention. On Windows, the :func:`WINFUNCTYPE` +factory function creates types for callback functions using the ``stdcall`` +calling convention. + +Both of these factory functions are called with the result type as first +argument, and the callback functions expected argument types as the remaining +arguments. + +I will present an example here which uses the standard C library's +:c:func:`qsort` function, that is used to sort items with the help of a callback +function. :c:func:`qsort` will be used to sort an array of integers:: + + >>> IntArray5 = c_int * 5 + >>> ia = IntArray5(5, 1, 7, 33, 99) + >>> qsort = libc.qsort + >>> qsort.restype = None + >>> + +:func:`qsort` must be called with a pointer to the data to sort, the number of +items in the data array, the size of one item, and a pointer to the comparison +function, the callback. The callback will then be called with two pointers to +items, and it must return a negative integer if the first item is smaller than +the second, a zero if they are equal, and a positive integer otherwise. + +So our callback function receives pointers to integers, and must return an +integer. First we create the ``type`` for the callback function:: + + >>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int)) + >>> + +To get started, here is a simple callback that shows the values it gets +passed:: + + >>> def py_cmp_func(a, b): + ... print("py_cmp_func", a[0], b[0]) + ... return 0 + ... + >>> cmp_func = CMPFUNC(py_cmp_func) + >>> + +The result:: + + >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +LINUX + py_cmp_func 5 1 + py_cmp_func 33 99 + py_cmp_func 7 33 + py_cmp_func 5 7 + py_cmp_func 1 7 + >>> + +Now we can actually compare the two items and return a useful result:: + + >>> def py_cmp_func(a, b): + ... print("py_cmp_func", a[0], b[0]) + ... return a[0] - b[0] + ... + >>> + >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +LINUX + py_cmp_func 5 1 + py_cmp_func 33 99 + py_cmp_func 7 33 + py_cmp_func 1 7 + py_cmp_func 5 7 + >>> + +As we can easily check, our array is sorted now:: + + >>> for i in ia: print(i, end=" ") + ... + 1 5 7 33 99 + >>> + +The function factories can be used as decorator factories, so we may as well +write:: + + >>> @CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int)) + ... def py_cmp_func(a, b): + ... print("py_cmp_func", a[0], b[0]) + ... return a[0] - b[0] + ... + >>> qsort(ia, len(ia), sizeof(c_int), py_cmp_func) + py_cmp_func 5 1 + py_cmp_func 33 99 + py_cmp_func 7 33 + py_cmp_func 1 7 + py_cmp_func 5 7 + >>> + +.. note:: + + Make sure you keep references to :func:`CFUNCTYPE` objects as long as they + are used from C code. :mod:`ctypes` doesn't, and if you don't, they may be + garbage collected, crashing your program when a callback is made. + + Also, note that if the callback function is called in a thread created + outside of Python's control (e.g. by the foreign code that calls the + callback), ctypes creates a new dummy Python thread on every invocation. This + behavior is correct for most purposes, but it means that values stored with + :class:`threading.local` will *not* survive across different callbacks, even when + those calls are made from the same C thread. + +.. _ctypes-accessing-values-exported-from-dlls: + +Accessing values exported from dlls +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Some shared libraries not only export functions, they also export variables. An +example in the Python library itself is the :c:data:`Py_OptimizeFlag`, an integer +set to 0, 1, or 2, depending on the :option:`-O` or :option:`-OO` flag given on +startup. + +:mod:`ctypes` can access values like this with the :meth:`in_dll` class methods of +the type. *pythonapi* is a predefined symbol giving access to the Python C +api:: + + >>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag") + >>> print(opt_flag) + c_long(0) + >>> + +If the interpreter would have been started with :option:`-O`, the sample would +have printed ``c_long(1)``, or ``c_long(2)`` if :option:`-OO` would have been +specified. + +An extended example which also demonstrates the use of pointers accesses the +:c:data:`PyImport_FrozenModules` pointer exported by Python. + +Quoting the docs for that value: + + This pointer is initialized to point to an array of :c:type:`struct _frozen` + records, terminated by one whose members are all ``NULL`` or zero. When a frozen + module is imported, it is searched in this table. Third-party code could play + tricks with this to provide a dynamically created collection of frozen modules. + +So manipulating this pointer could even prove useful. To restrict the example +size, we show only how this table can be read with :mod:`ctypes`:: + + >>> from ctypes import * + >>> + >>> class struct_frozen(Structure): + ... _fields_ = [("name", c_char_p), + ... ("code", POINTER(c_ubyte)), + ... ("size", c_int)] + ... + >>> + +We have defined the :c:type:`struct _frozen` data type, so we can get the pointer +to the table:: + + >>> FrozenTable = POINTER(struct_frozen) + >>> table = FrozenTable.in_dll(pythonapi, "PyImport_FrozenModules") + >>> + +Since ``table`` is a ``pointer`` to the array of ``struct_frozen`` records, we +can iterate over it, but we just have to make sure that our loop terminates, +because pointers have no size. Sooner or later it would probably crash with an +access violation or whatever, so it's better to break out of the loop when we +hit the ``NULL`` entry:: + + >>> for item in table: + ... if item.name is None: + ... break + ... print(item.name.decode("ascii"), item.size) + ... + _frozen_importlib 31764 + _frozen_importlib_external 41499 + __hello__ 161 + __phello__ -161 + __phello__.spam 161 + >>> + +The fact that standard Python has a frozen module and a frozen package +(indicated by the negative ``size`` member) is not well known, it is only used +for testing. Try it out with ``import __hello__`` for example. + + +.. _ctypes-surprises: + +Surprises +^^^^^^^^^ + +There are some edges in :mod:`ctypes` where you might expect something other +than what actually happens. + +Consider the following example:: + + >>> from ctypes import * + >>> class POINT(Structure): + ... _fields_ = ("x", c_int), ("y", c_int) + ... + >>> class RECT(Structure): + ... _fields_ = ("a", POINT), ("b", POINT) + ... + >>> p1 = POINT(1, 2) + >>> p2 = POINT(3, 4) + >>> rc = RECT(p1, p2) + >>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y) + 1 2 3 4 + >>> # now swap the two points + >>> rc.a, rc.b = rc.b, rc.a + >>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y) + 3 4 3 4 + >>> + +Hm. We certainly expected the last statement to print ``3 4 1 2``. What +happened? Here are the steps of the ``rc.a, rc.b = rc.b, rc.a`` line above:: + + >>> temp0, temp1 = rc.b, rc.a + >>> rc.a = temp0 + >>> rc.b = temp1 + >>> + +Note that ``temp0`` and ``temp1`` are objects still using the internal buffer of +the ``rc`` object above. So executing ``rc.a = temp0`` copies the buffer +contents of ``temp0`` into ``rc`` 's buffer. This, in turn, changes the +contents of ``temp1``. So, the last assignment ``rc.b = temp1``, doesn't have +the expected effect. + +Keep in mind that retrieving sub-objects from Structure, Unions, and Arrays +doesn't *copy* the sub-object, instead it retrieves a wrapper object accessing +the root-object's underlying buffer. + +Another example that may behave differently from what one would expect is this:: + + >>> s = c_char_p() + >>> s.value = b"abc def ghi" + >>> s.value + b'abc def ghi' + >>> s.value is s.value + False + >>> + +.. note:: + + Objects instantiated from :class:`c_char_p` can only have their value set to bytes + or integers. + +Why is it printing ``False``? ctypes instances are objects containing a memory +block plus some :term:`descriptor`\s accessing the contents of the memory. +Storing a Python object in the memory block does not store the object itself, +instead the ``contents`` of the object is stored. Accessing the contents again +constructs a new Python object each time! + + +.. _ctypes-variable-sized-data-types: + +Variable-sized data types +^^^^^^^^^^^^^^^^^^^^^^^^^ + +:mod:`ctypes` provides some support for variable-sized arrays and structures. + +The :func:`resize` function can be used to resize the memory buffer of an +existing ctypes object. The function takes the object as first argument, and +the requested size in bytes as the second argument. The memory block cannot be +made smaller than the natural memory block specified by the objects type, a +:exc:`ValueError` is raised if this is tried:: + + >>> short_array = (c_short * 4)() + >>> print(sizeof(short_array)) + 8 + >>> resize(short_array, 4) + Traceback (most recent call last): + ... + ValueError: minimum size is 8 + >>> resize(short_array, 32) + >>> sizeof(short_array) + 32 + >>> sizeof(type(short_array)) + 8 + >>> + +This is nice and fine, but how would one access the additional elements +contained in this array? Since the type still only knows about 4 elements, we +get errors accessing other elements:: + + >>> short_array[:] + [0, 0, 0, 0] + >>> short_array[7] + Traceback (most recent call last): + ... + IndexError: invalid index + >>> + +Another way to use variable-sized data types with :mod:`ctypes` is to use the +dynamic nature of Python, and (re-)define the data type after the required size +is already known, on a case by case basis. + + +.. _ctypes-ctypes-reference: + +ctypes reference +---------------- + + +.. _ctypes-finding-shared-libraries: + +Finding shared libraries +^^^^^^^^^^^^^^^^^^^^^^^^ + +When programming in a compiled language, shared libraries are accessed when +compiling/linking a program, and when the program is run. + +The purpose of the :func:`find_library` function is to locate a library in a way +similar to what the compiler or runtime loader does (on platforms with several +versions of a shared library the most recent should be loaded), while the ctypes +library loaders act like when a program is run, and call the runtime loader +directly. + +The :mod:`ctypes.util` module provides a function which can help to determine +the library to load. + + +.. data:: find_library(name) + :module: ctypes.util + :noindex: + + Try to find a library and return a pathname. *name* is the library name without + any prefix like *lib*, suffix like ``.so``, ``.dylib`` or version number (this + is the form used for the posix linker option :option:`!-l`). If no library can + be found, returns ``None``. + +The exact functionality is system dependent. + +On Linux, :func:`find_library` tries to run external programs +(``/sbin/ldconfig``, ``gcc``, ``objdump`` and ``ld``) to find the library file. +It returns the filename of the library file. + +.. versionchanged:: 3.6 + On Linux, the value of the environment variable ``LD_LIBRARY_PATH`` is used + when searching for libraries, if a library cannot be found by any other means. + +Here are some examples:: + + >>> from ctypes.util import find_library + >>> find_library("m") + 'libm.so.6' + >>> find_library("c") + 'libc.so.6' + >>> find_library("bz2") + 'libbz2.so.1.0' + >>> + +On OS X, :func:`find_library` tries several predefined naming schemes and paths +to locate the library, and returns a full pathname if successful:: + + >>> from ctypes.util import find_library + >>> find_library("c") + '/usr/lib/libc.dylib' + >>> find_library("m") + '/usr/lib/libm.dylib' + >>> find_library("bz2") + '/usr/lib/libbz2.dylib' + >>> find_library("AGL") + '/System/Library/Frameworks/AGL.framework/AGL' + >>> + +On Windows, :func:`find_library` searches along the system search path, and +returns the full pathname, but since there is no predefined naming scheme a call +like ``find_library("c")`` will fail and return ``None``. + +If wrapping a shared library with :mod:`ctypes`, it *may* be better to determine +the shared library name at development time, and hardcode that into the wrapper +module instead of using :func:`find_library` to locate the library at runtime. + + +.. _ctypes-loading-shared-libraries: + +Loading shared libraries +^^^^^^^^^^^^^^^^^^^^^^^^ + +There are several ways to load shared libraries into the Python process. One +way is to instantiate one of the following classes: + + +.. class:: CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False, winmode=0) + + Instances of this class represent loaded shared libraries. Functions in these + libraries use the standard C calling convention, and are assumed to return + :c:type:`int`. + + +.. class:: OleDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False, winmode=0) + + Windows only: Instances of this class represent loaded shared libraries, + functions in these libraries use the ``stdcall`` calling convention, and are + assumed to return the windows specific :class:`HRESULT` code. :class:`HRESULT` + values contain information specifying whether the function call failed or + succeeded, together with additional error code. If the return value signals a + failure, an :class:`OSError` is automatically raised. + + .. versionchanged:: 3.3 + :exc:`WindowsError` used to be raised. + + +.. class:: WinDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False, winmode=0) + + Windows only: Instances of this class represent loaded shared libraries, + functions in these libraries use the ``stdcall`` calling convention, and are + assumed to return :c:type:`int` by default. + + On Windows CE only the standard calling convention is used, for convenience the + :class:`WinDLL` and :class:`OleDLL` use the standard calling convention on this + platform. + +The Python :term:`global interpreter lock` is released before calling any +function exported by these libraries, and reacquired afterwards. + + +.. class:: PyDLL(name, mode=DEFAULT_MODE, handle=None) + + Instances of this class behave like :class:`CDLL` instances, except that the + Python GIL is *not* released during the function call, and after the function + execution the Python error flag is checked. If the error flag is set, a Python + exception is raised. + + Thus, this is only useful to call Python C api functions directly. + +All these classes can be instantiated by calling them with at least one +argument, the pathname of the shared library. If you have an existing handle to +an already loaded shared library, it can be passed as the ``handle`` named +parameter, otherwise the underlying platforms ``dlopen`` or ``LoadLibrary`` +function is used to load the library into the process, and to get a handle to +it. + +The *mode* parameter can be used to specify how the library is loaded. For +details, consult the :manpage:`dlopen(3)` manpage. On Windows, *mode* is +ignored. On posix systems, RTLD_NOW is always added, and is not +configurable. + +The *use_errno* parameter, when set to true, enables a ctypes mechanism that +allows accessing the system :data:`errno` error number in a safe way. +:mod:`ctypes` maintains a thread-local copy of the systems :data:`errno` +variable; if you call foreign functions created with ``use_errno=True`` then the +:data:`errno` value before the function call is swapped with the ctypes private +copy, the same happens immediately after the function call. + +The function :func:`ctypes.get_errno` returns the value of the ctypes private +copy, and the function :func:`ctypes.set_errno` changes the ctypes private copy +to a new value and returns the former value. + +The *use_last_error* parameter, when set to true, enables the same mechanism for +the Windows error code which is managed by the :func:`GetLastError` and +:func:`SetLastError` Windows API functions; :func:`ctypes.get_last_error` and +:func:`ctypes.set_last_error` are used to request and change the ctypes private +copy of the windows error code. + +The *winmode* parameter is used on Windows to specify how the library is loaded +(since *mode* is ignored). It takes any value that is valid for the Win32 API +``LoadLibraryEx`` flags parameter. When omitted, the default is to use the flags +that result in the most secure DLL load to avoiding issues such as DLL +hijacking. Passing the full path to the DLL is the safest way to ensure the +correct library and dependencies are loaded. + +.. versionchanged:: 3.8 + Added *winmode* parameter. + + +.. data:: RTLD_GLOBAL + :noindex: + + Flag to use as *mode* parameter. On platforms where this flag is not available, + it is defined as the integer zero. + + +.. data:: RTLD_LOCAL + :noindex: + + Flag to use as *mode* parameter. On platforms where this is not available, it + is the same as *RTLD_GLOBAL*. + + +.. data:: DEFAULT_MODE + :noindex: + + The default mode which is used to load shared libraries. On OSX 10.3, this is + *RTLD_GLOBAL*, otherwise it is the same as *RTLD_LOCAL*. + +Instances of these classes have no public methods. Functions exported by the +shared library can be accessed as attributes or by index. Please note that +accessing the function through an attribute caches the result and therefore +accessing it repeatedly returns the same object each time. On the other hand, +accessing it through an index returns a new object each time:: + + >>> from ctypes import CDLL + >>> libc = CDLL("libc.so.6") # On Linux + >>> libc.time == libc.time + True + >>> libc['time'] == libc['time'] + False + +The following public attributes are available, their name starts with an +underscore to not clash with exported function names: + + +.. attribute:: PyDLL._handle + + The system handle used to access the library. + + +.. attribute:: PyDLL._name + + The name of the library passed in the constructor. + +Shared libraries can also be loaded by using one of the prefabricated objects, +which are instances of the :class:`LibraryLoader` class, either by calling the +:meth:`LoadLibrary` method, or by retrieving the library as attribute of the +loader instance. + + +.. class:: LibraryLoader(dlltype) + + Class which loads shared libraries. *dlltype* should be one of the + :class:`CDLL`, :class:`PyDLL`, :class:`WinDLL`, or :class:`OleDLL` types. + + :meth:`__getattr__` has special behavior: It allows loading a shared library by + accessing it as attribute of a library loader instance. The result is cached, + so repeated attribute accesses return the same library each time. + + .. method:: LoadLibrary(name) + + Load a shared library into the process and return it. This method always + returns a new instance of the library. + + +These prefabricated library loaders are available: + +.. data:: cdll + :noindex: + + Creates :class:`CDLL` instances. + + +.. data:: windll + :noindex: + + Windows only: Creates :class:`WinDLL` instances. + + +.. data:: oledll + :noindex: + + Windows only: Creates :class:`OleDLL` instances. + + +.. data:: pydll + :noindex: + + Creates :class:`PyDLL` instances. + + +For accessing the C Python api directly, a ready-to-use Python shared library +object is available: + +.. data:: pythonapi + :noindex: + + An instance of :class:`PyDLL` that exposes Python C API functions as + attributes. Note that all these functions are assumed to return C + :c:type:`int`, which is of course not always the truth, so you have to assign + the correct :attr:`restype` attribute to use these functions. + +.. audit-event:: ctypes.dlopen name ctypes.LibraryLoader + + Loading a library through any of these objects raises an + :ref:`auditing event ` ``ctypes.dlopen`` with string argument + ``name``, the name used to load the library. + +.. audit-event:: ctypes.dlsym library,name ctypes.LibraryLoader + + Accessing a function on a loaded library raises an auditing event + ``ctypes.dlsym`` with arguments ``library`` (the library object) and ``name`` + (the symbol's name as a string or integer). + +.. audit-event:: ctypes.dlsym/handle handle,name ctypes.LibraryLoader + + In cases when only the library handle is available rather than the object, + accessing a function raises an auditing event ``ctypes.dlsym/handle`` with + arguments ``handle`` (the raw library handle) and ``name``. + +.. _ctypes-foreign-functions: + +Foreign functions +^^^^^^^^^^^^^^^^^ + +As explained in the previous section, foreign functions can be accessed as +attributes of loaded shared libraries. The function objects created in this way +by default accept any number of arguments, accept any ctypes data instances as +arguments, and return the default result type specified by the library loader. +They are instances of a private class: + + +.. class:: _FuncPtr + + Base class for C callable foreign functions. + + Instances of foreign functions are also C compatible data types; they + represent C function pointers. + + This behavior can be customized by assigning to special attributes of the + foreign function object. + + .. attribute:: restype + + Assign a ctypes type to specify the result type of the foreign function. + Use ``None`` for :c:type:`void`, a function not returning anything. + + It is possible to assign a callable Python object that is not a ctypes + type, in this case the function is assumed to return a C :c:type:`int`, and + the callable will be called with this integer, allowing further + processing or error checking. Using this is deprecated, for more flexible + post processing or error checking use a ctypes data type as + :attr:`restype` and assign a callable to the :attr:`errcheck` attribute. + + .. attribute:: argtypes + + Assign a tuple of ctypes types to specify the argument types that the + function accepts. Functions using the ``stdcall`` calling convention can + only be called with the same number of arguments as the length of this + tuple; functions using the C calling convention accept additional, + unspecified arguments as well. + + When a foreign function is called, each actual argument is passed to the + :meth:`from_param` class method of the items in the :attr:`argtypes` + tuple, this method allows adapting the actual argument to an object that + the foreign function accepts. For example, a :class:`c_char_p` item in + the :attr:`argtypes` tuple will convert a string passed as argument into + a bytes object using ctypes conversion rules. + + New: It is now possible to put items in argtypes which are not ctypes + types, but each item must have a :meth:`from_param` method which returns a + value usable as argument (integer, string, ctypes instance). This allows + defining adapters that can adapt custom objects as function parameters. + + .. attribute:: errcheck + + Assign a Python function or another callable to this attribute. The + callable will be called with three or more arguments: + + .. function:: callable(result, func, arguments) + :noindex: + :module: + + *result* is what the foreign function returns, as specified by the + :attr:`restype` attribute. + + *func* is the foreign function object itself, this allows reusing the + same callable object to check or post process the results of several + functions. + + *arguments* is a tuple containing the parameters originally passed to + the function call, this allows specializing the behavior on the + arguments used. + + The object that this function returns will be returned from the + foreign function call, but it can also check the result value + and raise an exception if the foreign function call failed. + + +.. exception:: ArgumentError + + This exception is raised when a foreign function call cannot convert one of the + passed arguments. + + +.. audit-event:: ctypes.seh_exception code foreign-functions + + On Windows, when a foreign function call raises a system exception (for + example, due to an access violation), it will be captured and replaced with + a suitable Python exception. Further, an auditing event + ``ctypes.seh_exception`` with argument ``code`` will be raised, allowing an + audit hook to replace the exception with its own. + +.. audit-event:: ctypes.call_function func_pointer,arguments ctype-foreign-functions + + Some ways to invoke foreign function calls may raise an auditing event + ``ctypes.call_function`` with arguments ``function pointer`` and ``arguments``. + +.. _ctypes-function-prototypes: + +Function prototypes +^^^^^^^^^^^^^^^^^^^ + +Foreign functions can also be created by instantiating function prototypes. +Function prototypes are similar to function prototypes in C; they describe a +function (return type, argument types, calling convention) without defining an +implementation. The factory functions must be called with the desired result +type and the argument types of the function, and can be used as decorator +factories, and as such, be applied to functions through the ``@wrapper`` syntax. +See :ref:`ctypes-callback-functions` for examples. + + +.. function:: CFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False) + + The returned function prototype creates functions that use the standard C + calling convention. The function will release the GIL during the call. If + *use_errno* is set to true, the ctypes private copy of the system + :data:`errno` variable is exchanged with the real :data:`errno` value before + and after the call; *use_last_error* does the same for the Windows error + code. + + +.. function:: WINFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False) + + Windows only: The returned function prototype creates functions that use the + ``stdcall`` calling convention, except on Windows CE where + :func:`WINFUNCTYPE` is the same as :func:`CFUNCTYPE`. The function will + release the GIL during the call. *use_errno* and *use_last_error* have the + same meaning as above. + + +.. function:: PYFUNCTYPE(restype, *argtypes) + + The returned function prototype creates functions that use the Python calling + convention. The function will *not* release the GIL during the call. + +Function prototypes created by these factory functions can be instantiated in +different ways, depending on the type and number of the parameters in the call: + + + .. function:: prototype(address) + :noindex: + :module: + + Returns a foreign function at the specified address which must be an integer. + + + .. function:: prototype(callable) + :noindex: + :module: + + Create a C callable function (a callback function) from a Python *callable*. + + + .. function:: prototype(func_spec[, paramflags]) + :noindex: + :module: + + Returns a foreign function exported by a shared library. *func_spec* must + be a 2-tuple ``(name_or_ordinal, library)``. The first item is the name of + the exported function as string, or the ordinal of the exported function + as small integer. The second item is the shared library instance. + + + .. function:: prototype(vtbl_index, name[, paramflags[, iid]]) + :noindex: + :module: + + Returns a foreign function that will call a COM method. *vtbl_index* is + the index into the virtual function table, a small non-negative + integer. *name* is name of the COM method. *iid* is an optional pointer to + the interface identifier which is used in extended error reporting. + + COM methods use a special calling convention: They require a pointer to + the COM interface as first argument, in addition to those parameters that + are specified in the :attr:`argtypes` tuple. + + The optional *paramflags* parameter creates foreign function wrappers with much + more functionality than the features described above. + + *paramflags* must be a tuple of the same length as :attr:`argtypes`. + + Each item in this tuple contains further information about a parameter, it must + be a tuple containing one, two, or three items. + + The first item is an integer containing a combination of direction + flags for the parameter: + + 1 + Specifies an input parameter to the function. + + 2 + Output parameter. The foreign function fills in a value. + + 4 + Input parameter which defaults to the integer zero. + + The optional second item is the parameter name as string. If this is specified, + the foreign function can be called with named parameters. + + The optional third item is the default value for this parameter. + +This example demonstrates how to wrap the Windows ``MessageBoxW`` function so +that it supports default parameters and named arguments. The C declaration from +the windows header file is this:: + + WINUSERAPI int WINAPI + MessageBoxW( + HWND hWnd, + LPCWSTR lpText, + LPCWSTR lpCaption, + UINT uType); + +Here is the wrapping with :mod:`ctypes`:: + + >>> from ctypes import c_int, WINFUNCTYPE, windll + >>> from ctypes.wintypes import HWND, LPCWSTR, UINT + >>> prototype = WINFUNCTYPE(c_int, HWND, LPCWSTR, LPCWSTR, UINT) + >>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", "Hello from ctypes"), (1, "flags", 0) + >>> MessageBox = prototype(("MessageBoxW", windll.user32), paramflags) + +The ``MessageBox`` foreign function can now be called in these ways:: + + >>> MessageBox() + >>> MessageBox(text="Spam, spam, spam") + >>> MessageBox(flags=2, text="foo bar") + +A second example demonstrates output parameters. The win32 ``GetWindowRect`` +function retrieves the dimensions of a specified window by copying them into +``RECT`` structure that the caller has to supply. Here is the C declaration:: + + WINUSERAPI BOOL WINAPI + GetWindowRect( + HWND hWnd, + LPRECT lpRect); + +Here is the wrapping with :mod:`ctypes`:: + + >>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError + >>> from ctypes.wintypes import BOOL, HWND, RECT + >>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT)) + >>> paramflags = (1, "hwnd"), (2, "lprect") + >>> GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags) + >>> + +Functions with output parameters will automatically return the output parameter +value if there is a single one, or a tuple containing the output parameter +values when there are more than one, so the GetWindowRect function now returns a +RECT instance, when called. + +Output parameters can be combined with the :attr:`errcheck` protocol to do +further output processing and error checking. The win32 ``GetWindowRect`` api +function returns a ``BOOL`` to signal success or failure, so this function could +do the error checking, and raises an exception when the api call failed:: + + >>> def errcheck(result, func, args): + ... if not result: + ... raise WinError() + ... return args + ... + >>> GetWindowRect.errcheck = errcheck + >>> + +If the :attr:`errcheck` function returns the argument tuple it receives +unchanged, :mod:`ctypes` continues the normal processing it does on the output +parameters. If you want to return a tuple of window coordinates instead of a +``RECT`` instance, you can retrieve the fields in the function and return them +instead, the normal processing will no longer take place:: + + >>> def errcheck(result, func, args): + ... if not result: + ... raise WinError() + ... rc = args[1] + ... return rc.left, rc.top, rc.bottom, rc.right + ... + >>> GetWindowRect.errcheck = errcheck + >>> + + +.. _ctypes-utility-functions: + +Utility functions +^^^^^^^^^^^^^^^^^ + +.. function:: addressof(obj) + + Returns the address of the memory buffer as integer. *obj* must be an + instance of a ctypes type. + + .. audit-event:: ctypes.addressof obj ctypes.addressof + + +.. function:: alignment(obj_or_type) + + Returns the alignment requirements of a ctypes type. *obj_or_type* must be a + ctypes type or instance. + + +.. function:: byref(obj[, offset]) + + Returns a light-weight pointer to *obj*, which must be an instance of a + ctypes type. *offset* defaults to zero, and must be an integer that will be + added to the internal pointer value. + + ``byref(obj, offset)`` corresponds to this C code:: + + (((char *)&obj) + offset) + + The returned object can only be used as a foreign function call parameter. + It behaves similar to ``pointer(obj)``, but the construction is a lot faster. + + +.. function:: cast(obj, type) + + This function is similar to the cast operator in C. It returns a new instance + of *type* which points to the same memory block as *obj*. *type* must be a + pointer type, and *obj* must be an object that can be interpreted as a + pointer. + + +.. function:: create_string_buffer(init_or_size, size=None) + + This function creates a mutable character buffer. The returned object is a + ctypes array of :class:`c_char`. + + *init_or_size* must be an integer which specifies the size of the array, or a + bytes object which will be used to initialize the array items. + + If a bytes object is specified as first argument, the buffer is made one item + larger than its length so that the last element in the array is a NUL + termination character. An integer can be passed as second argument which allows + specifying the size of the array if the length of the bytes should not be used. + + .. audit-event:: ctypes.create_string_buffer init,size ctypes.create_string_buffer + + +.. function:: create_unicode_buffer(init_or_size, size=None) + + This function creates a mutable unicode character buffer. The returned object is + a ctypes array of :class:`c_wchar`. + + *init_or_size* must be an integer which specifies the size of the array, or a + string which will be used to initialize the array items. + + If a string is specified as first argument, the buffer is made one item + larger than the length of the string so that the last element in the array is a + NUL termination character. An integer can be passed as second argument which + allows specifying the size of the array if the length of the string should not + be used. + + .. audit-event:: ctypes.create_unicode_buffer init,size ctypes.create_unicode_buffer + + +.. function:: DllCanUnloadNow() + + Windows only: This function is a hook which allows implementing in-process + COM servers with ctypes. It is called from the DllCanUnloadNow function that + the _ctypes extension dll exports. + + +.. function:: DllGetClassObject() + + Windows only: This function is a hook which allows implementing in-process + COM servers with ctypes. It is called from the DllGetClassObject function + that the ``_ctypes`` extension dll exports. + + +.. function:: find_library(name) + :module: ctypes.util + + Try to find a library and return a pathname. *name* is the library name + without any prefix like ``lib``, suffix like ``.so``, ``.dylib`` or version + number (this is the form used for the posix linker option :option:`!-l`). If + no library can be found, returns ``None``. + + The exact functionality is system dependent. + + +.. function:: find_msvcrt() + :module: ctypes.util + + Windows only: return the filename of the VC runtime library used by Python, + and by the extension modules. If the name of the library cannot be + determined, ``None`` is returned. + + If you need to free memory, for example, allocated by an extension module + with a call to the ``free(void *)``, it is important that you use the + function in the same library that allocated the memory. + + +.. function:: FormatError([code]) + + Windows only: Returns a textual description of the error code *code*. If no + error code is specified, the last error code is used by calling the Windows + api function GetLastError. + + +.. function:: GetLastError() + + Windows only: Returns the last error code set by Windows in the calling thread. + This function calls the Windows `GetLastError()` function directly, + it does not return the ctypes-private copy of the error code. + +.. function:: get_errno() + + Returns the current value of the ctypes-private copy of the system + :data:`errno` variable in the calling thread. + + .. audit-event:: ctypes.get_errno "" ctypes.get_errno + +.. function:: get_last_error() + + Windows only: returns the current value of the ctypes-private copy of the system + :data:`LastError` variable in the calling thread. + + .. audit-event:: ctypes.get_last_error "" ctypes.get_last_error + +.. function:: memmove(dst, src, count) + + Same as the standard C memmove library function: copies *count* bytes from + *src* to *dst*. *dst* and *src* must be integers or ctypes instances that can + be converted to pointers. + + +.. function:: memset(dst, c, count) + + Same as the standard C memset library function: fills the memory block at + address *dst* with *count* bytes of value *c*. *dst* must be an integer + specifying an address, or a ctypes instance. + + +.. function:: POINTER(type) + + This factory function creates and returns a new ctypes pointer type. Pointer + types are cached and reused internally, so calling this function repeatedly is + cheap. *type* must be a ctypes type. + + +.. function:: pointer(obj) + + This function creates a new pointer instance, pointing to *obj*. The returned + object is of the type ``POINTER(type(obj))``. + + Note: If you just want to pass a pointer to an object to a foreign function + call, you should use ``byref(obj)`` which is much faster. + + +.. function:: resize(obj, size) + + This function resizes the internal memory buffer of *obj*, which must be an + instance of a ctypes type. It is not possible to make the buffer smaller + than the native size of the objects type, as given by ``sizeof(type(obj))``, + but it is possible to enlarge the buffer. + + +.. function:: set_errno(value) + + Set the current value of the ctypes-private copy of the system :data:`errno` + variable in the calling thread to *value* and return the previous value. + + .. audit-event:: ctypes.set_errno errno ctypes.set_errno + + +.. function:: set_last_error(value) + + Windows only: set the current value of the ctypes-private copy of the system + :data:`LastError` variable in the calling thread to *value* and return the + previous value. + + .. audit-event:: ctypes.set_last_error error ctypes.set_last_error + + +.. function:: sizeof(obj_or_type) + + Returns the size in bytes of a ctypes type or instance memory buffer. + Does the same as the C ``sizeof`` operator. + + +.. function:: string_at(address, size=-1) + + This function returns the C string starting at memory address *address* as a bytes + object. If size is specified, it is used as size, otherwise the string is assumed + to be zero-terminated. + + .. audit-event:: ctypes.string_at address,size ctypes.string_at + + +.. function:: WinError(code=None, descr=None) + + Windows only: this function is probably the worst-named thing in ctypes. It + creates an instance of OSError. If *code* is not specified, + ``GetLastError`` is called to determine the error code. If *descr* is not + specified, :func:`FormatError` is called to get a textual description of the + error. + + .. versionchanged:: 3.3 + An instance of :exc:`WindowsError` used to be created. + + +.. function:: wstring_at(address, size=-1) + + This function returns the wide character string starting at memory address + *address* as a string. If *size* is specified, it is used as the number of + characters of the string, otherwise the string is assumed to be + zero-terminated. + + .. audit-event:: ctypes.wstring_at address,size ctypes.wstring_at + + +.. _ctypes-data-types: + +Data types +^^^^^^^^^^ + + +.. class:: _CData + + This non-public class is the common base class of all ctypes data types. + Among other things, all ctypes type instances contain a memory block that + hold C compatible data; the address of the memory block is returned by the + :func:`addressof` helper function. Another instance variable is exposed as + :attr:`_objects`; this contains other Python objects that need to be kept + alive in case the memory block contains pointers. + + Common methods of ctypes data types, these are all class methods (to be + exact, they are methods of the :term:`metaclass`): + + .. method:: _CData.from_buffer(source[, offset]) + + This method returns a ctypes instance that shares the buffer of the + *source* object. The *source* object must support the writeable buffer + interface. The optional *offset* parameter specifies an offset into the + source buffer in bytes; the default is zero. If the source buffer is not + large enough a :exc:`ValueError` is raised. + + .. audit-event:: ctypes.cdata/buffer pointer,size,offset ctypes._CData.from_buffer + + .. method:: _CData.from_buffer_copy(source[, offset]) + + This method creates a ctypes instance, copying the buffer from the + *source* object buffer which must be readable. The optional *offset* + parameter specifies an offset into the source buffer in bytes; the default + is zero. If the source buffer is not large enough a :exc:`ValueError` is + raised. + + .. audit-event:: ctypes.cdata/buffer pointer,size,offset ctypes._CData.from_buffer_copy + + .. method:: from_address(address) + + This method returns a ctypes type instance using the memory specified by + *address* which must be an integer. + + .. audit-event:: ctypes.cdata address ctypes._CData.from_address + + This method, and others that indirectly call this method, raises an + :ref:`auditing event ` ``ctypes.cdata`` with argument + ``address``. + + .. method:: from_param(obj) + + This method adapts *obj* to a ctypes type. It is called with the actual + object used in a foreign function call when the type is present in the + foreign function's :attr:`argtypes` tuple; it must return an object that + can be used as a function call parameter. + + All ctypes data types have a default implementation of this classmethod + that normally returns *obj* if that is an instance of the type. Some + types accept other objects as well. + + .. method:: in_dll(library, name) + + This method returns a ctypes type instance exported by a shared + library. *name* is the name of the symbol that exports the data, *library* + is the loaded shared library. + + Common instance variables of ctypes data types: + + .. attribute:: _b_base_ + + Sometimes ctypes data instances do not own the memory block they contain, + instead they share part of the memory block of a base object. The + :attr:`_b_base_` read-only member is the root ctypes object that owns the + memory block. + + .. attribute:: _b_needsfree_ + + This read-only variable is true when the ctypes data instance has + allocated the memory block itself, false otherwise. + + .. attribute:: _objects + + This member is either ``None`` or a dictionary containing Python objects + that need to be kept alive so that the memory block contents is kept + valid. This object is only exposed for debugging; never modify the + contents of this dictionary. + + +.. _ctypes-fundamental-data-types-2: + +Fundamental data types +^^^^^^^^^^^^^^^^^^^^^^ + +.. class:: _SimpleCData + + This non-public class is the base class of all fundamental ctypes data + types. It is mentioned here because it contains the common attributes of the + fundamental ctypes data types. :class:`_SimpleCData` is a subclass of + :class:`_CData`, so it inherits their methods and attributes. ctypes data + types that are not and do not contain pointers can now be pickled. + + Instances have a single attribute: + + .. attribute:: value + + This attribute contains the actual value of the instance. For integer and + pointer types, it is an integer, for character types, it is a single + character bytes object or string, for character pointer types it is a + Python bytes object or string. + + When the ``value`` attribute is retrieved from a ctypes instance, usually + a new object is returned each time. :mod:`ctypes` does *not* implement + original object return, always a new object is constructed. The same is + true for all other ctypes object instances. + + +Fundamental data types, when returned as foreign function call results, or, for +example, by retrieving structure field members or array items, are transparently +converted to native Python types. In other words, if a foreign function has a +:attr:`restype` of :class:`c_char_p`, you will always receive a Python bytes +object, *not* a :class:`c_char_p` instance. + +.. XXX above is false, it actually returns a Unicode string + +Subclasses of fundamental data types do *not* inherit this behavior. So, if a +foreign functions :attr:`restype` is a subclass of :class:`c_void_p`, you will +receive an instance of this subclass from the function call. Of course, you can +get the value of the pointer by accessing the ``value`` attribute. + +These are the fundamental ctypes data types: + +.. class:: c_byte + + Represents the C :c:type:`signed char` datatype, and interprets the value as + small integer. The constructor accepts an optional integer initializer; no + overflow checking is done. + + +.. class:: c_char + + Represents the C :c:type:`char` datatype, and interprets the value as a single + character. The constructor accepts an optional string initializer, the + length of the string must be exactly one character. + + +.. class:: c_char_p + + Represents the C :c:type:`char *` datatype when it points to a zero-terminated + string. For a general character pointer that may also point to binary data, + ``POINTER(c_char)`` must be used. The constructor accepts an integer + address, or a bytes object. + + +.. class:: c_double + + Represents the C :c:type:`double` datatype. The constructor accepts an + optional float initializer. + + +.. class:: c_longdouble + + Represents the C :c:type:`long double` datatype. The constructor accepts an + optional float initializer. On platforms where ``sizeof(long double) == + sizeof(double)`` it is an alias to :class:`c_double`. + +.. class:: c_float + + Represents the C :c:type:`float` datatype. The constructor accepts an + optional float initializer. + + +.. class:: c_int + + Represents the C :c:type:`signed int` datatype. The constructor accepts an + optional integer initializer; no overflow checking is done. On platforms + where ``sizeof(int) == sizeof(long)`` it is an alias to :class:`c_long`. + + +.. class:: c_int8 + + Represents the C 8-bit :c:type:`signed int` datatype. Usually an alias for + :class:`c_byte`. + + +.. class:: c_int16 + + Represents the C 16-bit :c:type:`signed int` datatype. Usually an alias for + :class:`c_short`. + + +.. class:: c_int32 + + Represents the C 32-bit :c:type:`signed int` datatype. Usually an alias for + :class:`c_int`. + + +.. class:: c_int64 + + Represents the C 64-bit :c:type:`signed int` datatype. Usually an alias for + :class:`c_longlong`. + + +.. class:: c_long + + Represents the C :c:type:`signed long` datatype. The constructor accepts an + optional integer initializer; no overflow checking is done. + + +.. class:: c_longlong + + Represents the C :c:type:`signed long long` datatype. The constructor accepts + an optional integer initializer; no overflow checking is done. + + +.. class:: c_short + + Represents the C :c:type:`signed short` datatype. The constructor accepts an + optional integer initializer; no overflow checking is done. + + +.. class:: c_size_t + + Represents the C :c:type:`size_t` datatype. + + +.. class:: c_ssize_t + + Represents the C :c:type:`ssize_t` datatype. + + .. versionadded:: 3.2 + + +.. class:: c_ubyte + + Represents the C :c:type:`unsigned char` datatype, it interprets the value as + small integer. The constructor accepts an optional integer initializer; no + overflow checking is done. + + +.. class:: c_uint + + Represents the C :c:type:`unsigned int` datatype. The constructor accepts an + optional integer initializer; no overflow checking is done. On platforms + where ``sizeof(int) == sizeof(long)`` it is an alias for :class:`c_ulong`. + + +.. class:: c_uint8 + + Represents the C 8-bit :c:type:`unsigned int` datatype. Usually an alias for + :class:`c_ubyte`. + + +.. class:: c_uint16 + + Represents the C 16-bit :c:type:`unsigned int` datatype. Usually an alias for + :class:`c_ushort`. + + +.. class:: c_uint32 + + Represents the C 32-bit :c:type:`unsigned int` datatype. Usually an alias for + :class:`c_uint`. + + +.. class:: c_uint64 + + Represents the C 64-bit :c:type:`unsigned int` datatype. Usually an alias for + :class:`c_ulonglong`. + + +.. class:: c_ulong + + Represents the C :c:type:`unsigned long` datatype. The constructor accepts an + optional integer initializer; no overflow checking is done. + + +.. class:: c_ulonglong + + Represents the C :c:type:`unsigned long long` datatype. The constructor + accepts an optional integer initializer; no overflow checking is done. + + +.. class:: c_ushort + + Represents the C :c:type:`unsigned short` datatype. The constructor accepts + an optional integer initializer; no overflow checking is done. + + +.. class:: c_void_p + + Represents the C :c:type:`void *` type. The value is represented as integer. + The constructor accepts an optional integer initializer. + + +.. class:: c_wchar + + Represents the C :c:type:`wchar_t` datatype, and interprets the value as a + single character unicode string. The constructor accepts an optional string + initializer, the length of the string must be exactly one character. + + +.. class:: c_wchar_p + + Represents the C :c:type:`wchar_t *` datatype, which must be a pointer to a + zero-terminated wide character string. The constructor accepts an integer + address, or a string. + + +.. class:: c_bool + + Represent the C :c:type:`bool` datatype (more accurately, :c:type:`_Bool` from + C99). Its value can be ``True`` or ``False``, and the constructor accepts any object + that has a truth value. + + +.. class:: HRESULT + + Windows only: Represents a :c:type:`HRESULT` value, which contains success or + error information for a function or method call. + + +.. class:: py_object + + Represents the C :c:type:`PyObject *` datatype. Calling this without an + argument creates a ``NULL`` :c:type:`PyObject *` pointer. + +The :mod:`ctypes.wintypes` module provides quite some other Windows specific +data types, for example :c:type:`HWND`, :c:type:`WPARAM`, or :c:type:`DWORD`. Some +useful structures like :c:type:`MSG` or :c:type:`RECT` are also defined. + + +.. _ctypes-structured-data-types: + +Structured data types +^^^^^^^^^^^^^^^^^^^^^ + + +.. class:: Union(*args, **kw) + + Abstract base class for unions in native byte order. + + +.. class:: BigEndianStructure(*args, **kw) + + Abstract base class for structures in *big endian* byte order. + + +.. class:: LittleEndianStructure(*args, **kw) + + Abstract base class for structures in *little endian* byte order. + +Structures with non-native byte order cannot contain pointer type fields, or any +other data types containing pointer type fields. + + +.. class:: Structure(*args, **kw) + + Abstract base class for structures in *native* byte order. + + Concrete structure and union types must be created by subclassing one of these + types, and at least define a :attr:`_fields_` class variable. :mod:`ctypes` will + create :term:`descriptor`\s which allow reading and writing the fields by direct + attribute accesses. These are the + + + .. attribute:: _fields_ + + A sequence defining the structure fields. The items must be 2-tuples or + 3-tuples. The first item is the name of the field, the second item + specifies the type of the field; it can be any ctypes data type. + + For integer type fields like :class:`c_int`, a third optional item can be + given. It must be a small positive integer defining the bit width of the + field. + + Field names must be unique within one structure or union. This is not + checked, only one field can be accessed when names are repeated. + + It is possible to define the :attr:`_fields_` class variable *after* the + class statement that defines the Structure subclass, this allows creating + data types that directly or indirectly reference themselves:: + + class List(Structure): + pass + List._fields_ = [("pnext", POINTER(List)), + ... + ] + + The :attr:`_fields_` class variable must, however, be defined before the + type is first used (an instance is created, :func:`sizeof` is called on it, + and so on). Later assignments to the :attr:`_fields_` class variable will + raise an AttributeError. + + It is possible to define sub-subclasses of structure types, they inherit + the fields of the base class plus the :attr:`_fields_` defined in the + sub-subclass, if any. + + + .. attribute:: _pack_ + + An optional small integer that allows overriding the alignment of + structure fields in the instance. :attr:`_pack_` must already be defined + when :attr:`_fields_` is assigned, otherwise it will have no effect. + + + .. attribute:: _anonymous_ + + An optional sequence that lists the names of unnamed (anonymous) fields. + :attr:`_anonymous_` must be already defined when :attr:`_fields_` is + assigned, otherwise it will have no effect. + + The fields listed in this variable must be structure or union type fields. + :mod:`ctypes` will create descriptors in the structure type that allows + accessing the nested fields directly, without the need to create the + structure or union field. + + Here is an example type (Windows):: + + class _U(Union): + _fields_ = [("lptdesc", POINTER(TYPEDESC)), + ("lpadesc", POINTER(ARRAYDESC)), + ("hreftype", HREFTYPE)] + + class TYPEDESC(Structure): + _anonymous_ = ("u",) + _fields_ = [("u", _U), + ("vt", VARTYPE)] + + + The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field + specifies which one of the union fields is valid. Since the ``u`` field + is defined as anonymous field, it is now possible to access the members + directly off the TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc`` + are equivalent, but the former is faster since it does not need to create + a temporary union instance:: + + td = TYPEDESC() + td.vt = VT_PTR + td.lptdesc = POINTER(some_type) + td.u.lptdesc = POINTER(some_type) + + It is possible to define sub-subclasses of structures, they inherit the + fields of the base class. If the subclass definition has a separate + :attr:`_fields_` variable, the fields specified in this are appended to the + fields of the base class. + + Structure and union constructors accept both positional and keyword + arguments. Positional arguments are used to initialize member fields in the + same order as they are appear in :attr:`_fields_`. Keyword arguments in the + constructor are interpreted as attribute assignments, so they will initialize + :attr:`_fields_` with the same name, or create new attributes for names not + present in :attr:`_fields_`. + + +.. _ctypes-arrays-pointers: + +Arrays and pointers +^^^^^^^^^^^^^^^^^^^ + +.. class:: Array(\*args) + + Abstract base class for arrays. + + The recommended way to create concrete array types is by multiplying any + :mod:`ctypes` data type with a positive integer. Alternatively, you can subclass + this type and define :attr:`_length_` and :attr:`_type_` class variables. + Array elements can be read and written using standard + subscript and slice accesses; for slice reads, the resulting object is + *not* itself an :class:`Array`. + + + .. attribute:: _length_ + + A positive integer specifying the number of elements in the array. + Out-of-range subscripts result in an :exc:`IndexError`. Will be + returned by :func:`len`. + + + .. attribute:: _type_ + + Specifies the type of each element in the array. + + + Array subclass constructors accept positional arguments, used to + initialize the elements in order. + + +.. class:: _Pointer + + Private, abstract base class for pointers. + + Concrete pointer types are created by calling :func:`POINTER` with the + type that will be pointed to; this is done automatically by + :func:`pointer`. + + If a pointer points to an array, its elements can be read and + written using standard subscript and slice accesses. Pointer objects + have no size, so :func:`len` will raise :exc:`TypeError`. Negative + subscripts will read from the memory *before* the pointer (as in C), and + out-of-range subscripts will probably crash with an access violation (if + you're lucky). + + + .. attribute:: _type_ + + Specifies the type pointed to. + + .. attribute:: contents + + Returns the object to which to pointer points. Assigning to this + attribute changes the pointer to point to the assigned object. + diff --git a/cpython_2/environment/repo/Doc/library/curses.ascii.rst b/cpython_2/environment/repo/Doc/library/curses.ascii.rst new file mode 100644 index 0000000000000000000000000000000000000000..a69dbb2ac06572e279d86a7854459a914ba36fe3 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/curses.ascii.rst @@ -0,0 +1,229 @@ +:mod:`curses.ascii` --- Utilities for ASCII characters +====================================================== + +.. module:: curses.ascii + :synopsis: Constants and set-membership functions for ASCII characters. + +.. moduleauthor:: Eric S. Raymond +.. sectionauthor:: Eric S. Raymond + +-------------- + +The :mod:`curses.ascii` module supplies name constants for ASCII characters and +functions to test membership in various ASCII character classes. The constants +supplied are names for control characters as follows: + ++--------------+----------------------------------------------+ +| Name | Meaning | ++==============+==============================================+ +| :const:`NUL` | | ++--------------+----------------------------------------------+ +| :const:`SOH` | Start of heading, console interrupt | ++--------------+----------------------------------------------+ +| :const:`STX` | Start of text | ++--------------+----------------------------------------------+ +| :const:`ETX` | End of text | ++--------------+----------------------------------------------+ +| :const:`EOT` | End of transmission | ++--------------+----------------------------------------------+ +| :const:`ENQ` | Enquiry, goes with :const:`ACK` flow control | ++--------------+----------------------------------------------+ +| :const:`ACK` | Acknowledgement | ++--------------+----------------------------------------------+ +| :const:`BEL` | Bell | ++--------------+----------------------------------------------+ +| :const:`BS` | Backspace | ++--------------+----------------------------------------------+ +| :const:`TAB` | Tab | ++--------------+----------------------------------------------+ +| :const:`HT` | Alias for :const:`TAB`: "Horizontal tab" | ++--------------+----------------------------------------------+ +| :const:`LF` | Line feed | ++--------------+----------------------------------------------+ +| :const:`NL` | Alias for :const:`LF`: "New line" | ++--------------+----------------------------------------------+ +| :const:`VT` | Vertical tab | ++--------------+----------------------------------------------+ +| :const:`FF` | Form feed | ++--------------+----------------------------------------------+ +| :const:`CR` | Carriage return | ++--------------+----------------------------------------------+ +| :const:`SO` | Shift-out, begin alternate character set | ++--------------+----------------------------------------------+ +| :const:`SI` | Shift-in, resume default character set | ++--------------+----------------------------------------------+ +| :const:`DLE` | Data-link escape | ++--------------+----------------------------------------------+ +| :const:`DC1` | XON, for flow control | ++--------------+----------------------------------------------+ +| :const:`DC2` | Device control 2, block-mode flow control | ++--------------+----------------------------------------------+ +| :const:`DC3` | XOFF, for flow control | ++--------------+----------------------------------------------+ +| :const:`DC4` | Device control 4 | ++--------------+----------------------------------------------+ +| :const:`NAK` | Negative acknowledgement | ++--------------+----------------------------------------------+ +| :const:`SYN` | Synchronous idle | ++--------------+----------------------------------------------+ +| :const:`ETB` | End transmission block | ++--------------+----------------------------------------------+ +| :const:`CAN` | Cancel | ++--------------+----------------------------------------------+ +| :const:`EM` | End of medium | ++--------------+----------------------------------------------+ +| :const:`SUB` | Substitute | ++--------------+----------------------------------------------+ +| :const:`ESC` | Escape | ++--------------+----------------------------------------------+ +| :const:`FS` | File separator | ++--------------+----------------------------------------------+ +| :const:`GS` | Group separator | ++--------------+----------------------------------------------+ +| :const:`RS` | Record separator, block-mode terminator | ++--------------+----------------------------------------------+ +| :const:`US` | Unit separator | ++--------------+----------------------------------------------+ +| :const:`SP` | Space | ++--------------+----------------------------------------------+ +| :const:`DEL` | Delete | ++--------------+----------------------------------------------+ + +Note that many of these have little practical significance in modern usage. The +mnemonics derive from teleprinter conventions that predate digital computers. + +The module supplies the following functions, patterned on those in the standard +C library: + + +.. function:: isalnum(c) + + Checks for an ASCII alphanumeric character; it is equivalent to ``isalpha(c) or + isdigit(c)``. + + +.. function:: isalpha(c) + + Checks for an ASCII alphabetic character; it is equivalent to ``isupper(c) or + islower(c)``. + + +.. function:: isascii(c) + + Checks for a character value that fits in the 7-bit ASCII set. + + +.. function:: isblank(c) + + Checks for an ASCII whitespace character; space or horizontal tab. + + +.. function:: iscntrl(c) + + Checks for an ASCII control character (in the range 0x00 to 0x1f or 0x7f). + + +.. function:: isdigit(c) + + Checks for an ASCII decimal digit, ``'0'`` through ``'9'``. This is equivalent + to ``c in string.digits``. + + +.. function:: isgraph(c) + + Checks for ASCII any printable character except space. + + +.. function:: islower(c) + + Checks for an ASCII lower-case character. + + +.. function:: isprint(c) + + Checks for any ASCII printable character including space. + + +.. function:: ispunct(c) + + Checks for any printable ASCII character which is not a space or an alphanumeric + character. + + +.. function:: isspace(c) + + Checks for ASCII white-space characters; space, line feed, carriage return, form + feed, horizontal tab, vertical tab. + + +.. function:: isupper(c) + + Checks for an ASCII uppercase letter. + + +.. function:: isxdigit(c) + + Checks for an ASCII hexadecimal digit. This is equivalent to ``c in + string.hexdigits``. + + +.. function:: isctrl(c) + + Checks for an ASCII control character (ordinal values 0 to 31). + + +.. function:: ismeta(c) + + Checks for a non-ASCII character (ordinal values 0x80 and above). + +These functions accept either integers or single-character strings; when the argument is a +string, it is first converted using the built-in function :func:`ord`. + +Note that all these functions check ordinal bit values derived from the +character of the string you pass in; they do not actually know anything about +the host machine's character encoding. + +The following two functions take either a single-character string or integer +byte value; they return a value of the same type. + + +.. function:: ascii(c) + + Return the ASCII value corresponding to the low 7 bits of *c*. + + +.. function:: ctrl(c) + + Return the control character corresponding to the given character (the character + bit value is bitwise-anded with 0x1f). + + +.. function:: alt(c) + + Return the 8-bit character corresponding to the given ASCII character (the + character bit value is bitwise-ored with 0x80). + +The following function takes either a single-character string or integer value; +it returns a string. + + +.. index:: + single: ^ (caret); in curses module + single: ! (exclamation); in curses module + +.. function:: unctrl(c) + + Return a string representation of the ASCII character *c*. If *c* is printable, + this string is the character itself. If the character is a control character + (0x00--0x1f) the string consists of a caret (``'^'``) followed by the + corresponding uppercase letter. If the character is an ASCII delete (0x7f) the + string is ``'^?'``. If the character has its meta bit (0x80) set, the meta bit + is stripped, the preceding rules applied, and ``'!'`` prepended to the result. + + +.. data:: controlnames + + A 33-element string array that contains the ASCII mnemonics for the thirty-two + ASCII control characters from 0 (NUL) to 0x1f (US), in order, plus the mnemonic + ``SP`` for the space character. + diff --git a/cpython_2/environment/repo/Doc/library/curses.panel.rst b/cpython_2/environment/repo/Doc/library/curses.panel.rst new file mode 100644 index 0000000000000000000000000000000000000000..d770c03c8375f468a5e026f14598c428eb3a40cc --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/curses.panel.rst @@ -0,0 +1,120 @@ +:mod:`curses.panel` --- A panel stack extension for curses +========================================================== + +.. module:: curses.panel + :synopsis: A panel stack extension that adds depth to curses windows. + +.. sectionauthor:: A.M. Kuchling + +-------------- + +Panels are windows with the added feature of depth, so they can be stacked on +top of each other, and only the visible portions of each window will be +displayed. Panels can be added, moved up or down in the stack, and removed. + + +.. _cursespanel-functions: + +Functions +--------- + +The module :mod:`curses.panel` defines the following functions: + + +.. function:: bottom_panel() + + Returns the bottom panel in the panel stack. + + +.. function:: new_panel(win) + + Returns a panel object, associating it with the given window *win*. Be aware + that you need to keep the returned panel object referenced explicitly. If you + don't, the panel object is garbage collected and removed from the panel stack. + + +.. function:: top_panel() + + Returns the top panel in the panel stack. + + +.. function:: update_panels() + + Updates the virtual screen after changes in the panel stack. This does not call + :func:`curses.doupdate`, so you'll have to do this yourself. + + +.. _curses-panel-objects: + +Panel Objects +------------- + +Panel objects, as returned by :func:`new_panel` above, are windows with a +stacking order. There's always a window associated with a panel which determines +the content, while the panel methods are responsible for the window's depth in +the panel stack. + +Panel objects have the following methods: + + +.. method:: Panel.above() + + Returns the panel above the current panel. + + +.. method:: Panel.below() + + Returns the panel below the current panel. + + +.. method:: Panel.bottom() + + Push the panel to the bottom of the stack. + + +.. method:: Panel.hidden() + + Returns ``True`` if the panel is hidden (not visible), ``False`` otherwise. + + +.. method:: Panel.hide() + + Hide the panel. This does not delete the object, it just makes the window on + screen invisible. + + +.. method:: Panel.move(y, x) + + Move the panel to the screen coordinates ``(y, x)``. + + +.. method:: Panel.replace(win) + + Change the window associated with the panel to the window *win*. + + +.. method:: Panel.set_userptr(obj) + + Set the panel's user pointer to *obj*. This is used to associate an arbitrary + piece of data with the panel, and can be any Python object. + + +.. method:: Panel.show() + + Display the panel (which might have been hidden). + + +.. method:: Panel.top() + + Push panel to the top of the stack. + + +.. method:: Panel.userptr() + + Returns the user pointer for the panel. This might be any Python object. + + +.. method:: Panel.window() + + Returns the window object associated with the panel. + diff --git a/cpython_2/environment/repo/Doc/library/curses.rst b/cpython_2/environment/repo/Doc/library/curses.rst new file mode 100644 index 0000000000000000000000000000000000000000..1201e8972de63c8c76f00279ad20fa87f9cdc29c --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/curses.rst @@ -0,0 +1,1881 @@ +:mod:`curses` --- Terminal handling for character-cell displays +=============================================================== + +.. module:: curses + :synopsis: An interface to the curses library, providing portable + terminal handling. + :platform: Unix + +.. sectionauthor:: Moshe Zadka +.. sectionauthor:: Eric Raymond + +-------------- + +The :mod:`curses` module provides an interface to the curses library, the +de-facto standard for portable advanced terminal handling. + +While curses is most widely used in the Unix environment, versions are available +for Windows, DOS, and possibly other systems as well. This extension module is +designed to match the API of ncurses, an open-source curses library hosted on +Linux and the BSD variants of Unix. + +.. note:: + + Whenever the documentation mentions a *character* it can be specified + as an integer, a one-character Unicode string or a one-byte byte string. + + Whenever the documentation mentions a *character string* it can be specified + as a Unicode string or a byte string. + +.. note:: + + Since version 5.4, the ncurses library decides how to interpret non-ASCII data + using the ``nl_langinfo`` function. That means that you have to call + :func:`locale.setlocale` in the application and encode Unicode strings + using one of the system's available encodings. This example uses the + system's default encoding:: + + import locale + locale.setlocale(locale.LC_ALL, '') + code = locale.getpreferredencoding() + + Then use *code* as the encoding for :meth:`str.encode` calls. + +.. seealso:: + + Module :mod:`curses.ascii` + Utilities for working with ASCII characters, regardless of your locale settings. + + Module :mod:`curses.panel` + A panel stack extension that adds depth to curses windows. + + Module :mod:`curses.textpad` + Editable text widget for curses supporting :program:`Emacs`\ -like bindings. + + :ref:`curses-howto` + Tutorial material on using curses with Python, by Andrew Kuchling and Eric + Raymond. + + The :source:`Tools/demo/` directory in the Python source distribution contains + some example programs using the curses bindings provided by this module. + + +.. _curses-functions: + +Functions +--------- + +The module :mod:`curses` defines the following exception: + + +.. exception:: error + + Exception raised when a curses library function returns an error. + +.. note:: + + Whenever *x* or *y* arguments to a function or a method are optional, they + default to the current cursor location. Whenever *attr* is optional, it defaults + to :const:`A_NORMAL`. + +The module :mod:`curses` defines the following functions: + + +.. function:: baudrate() + + Return the output speed of the terminal in bits per second. On software + terminal emulators it will have a fixed high value. Included for historical + reasons; in former times, it was used to write output loops for time delays and + occasionally to change interfaces depending on the line speed. + + +.. function:: beep() + + Emit a short attention sound. + + +.. function:: can_change_color() + + Return ``True`` or ``False``, depending on whether the programmer can change the colors + displayed by the terminal. + + +.. function:: cbreak() + + Enter cbreak mode. In cbreak mode (sometimes called "rare" mode) normal tty + line buffering is turned off and characters are available to be read one by one. + However, unlike raw mode, special characters (interrupt, quit, suspend, and flow + control) retain their effects on the tty driver and calling program. Calling + first :func:`raw` then :func:`cbreak` leaves the terminal in cbreak mode. + + +.. function:: color_content(color_number) + + Return the intensity of the red, green, and blue (RGB) components in the color + *color_number*, which must be between ``0`` and :const:`COLORS`. Return a 3-tuple, + containing the R,G,B values for the given color, which will be between + ``0`` (no component) and ``1000`` (maximum amount of component). + + +.. function:: color_pair(color_number) + + Return the attribute value for displaying text in the specified color. This + attribute value can be combined with :const:`A_STANDOUT`, :const:`A_REVERSE`, + and the other :const:`A_\*` attributes. :func:`pair_number` is the counterpart + to this function. + + +.. function:: curs_set(visibility) + + Set the cursor state. *visibility* can be set to ``0``, ``1``, or ``2``, for invisible, + normal, or very visible. If the terminal supports the visibility requested, return the + previous cursor state; otherwise raise an exception. On many + terminals, the "visible" mode is an underline cursor and the "very visible" mode + is a block cursor. + + +.. function:: def_prog_mode() + + Save the current terminal mode as the "program" mode, the mode when the running + program is using curses. (Its counterpart is the "shell" mode, for when the + program is not in curses.) Subsequent calls to :func:`reset_prog_mode` will + restore this mode. + + +.. function:: def_shell_mode() + + Save the current terminal mode as the "shell" mode, the mode when the running + program is not using curses. (Its counterpart is the "program" mode, when the + program is using curses capabilities.) Subsequent calls to + :func:`reset_shell_mode` will restore this mode. + + +.. function:: delay_output(ms) + + Insert an *ms* millisecond pause in output. + + +.. function:: doupdate() + + Update the physical screen. The curses library keeps two data structures, one + representing the current physical screen contents and a virtual screen + representing the desired next state. The :func:`doupdate` ground updates the + physical screen to match the virtual screen. + + The virtual screen may be updated by a :meth:`~window.noutrefresh` call after write + operations such as :meth:`~window.addstr` have been performed on a window. The normal + :meth:`~window.refresh` call is simply :meth:`!noutrefresh` followed by :func:`!doupdate`; + if you have to update multiple windows, you can speed performance and perhaps + reduce screen flicker by issuing :meth:`!noutrefresh` calls on all windows, + followed by a single :func:`!doupdate`. + + +.. function:: echo() + + Enter echo mode. In echo mode, each character input is echoed to the screen as + it is entered. + + +.. function:: endwin() + + De-initialize the library, and return terminal to normal status. + + +.. function:: erasechar() + + Return the user's current erase character as a one-byte bytes object. Under Unix operating systems this + is a property of the controlling tty of the curses program, and is not set by + the curses library itself. + + +.. function:: filter() + + The :func:`.filter` routine, if used, must be called before :func:`initscr` is + called. The effect is that, during those calls, :envvar:`LINES` is set to ``1``; the + capabilities ``clear``, ``cup``, ``cud``, ``cud1``, ``cuu1``, ``cuu``, ``vpa`` are disabled; and the ``home`` + string is set to the value of ``cr``. The effect is that the cursor is confined to + the current line, and so are screen updates. This may be used for enabling + character-at-a-time line editing without touching the rest of the screen. + + +.. function:: flash() + + Flash the screen. That is, change it to reverse-video and then change it back + in a short interval. Some people prefer such as 'visible bell' to the audible + attention signal produced by :func:`beep`. + + +.. function:: flushinp() + + Flush all input buffers. This throws away any typeahead that has been typed + by the user and has not yet been processed by the program. + + +.. function:: getmouse() + + After :meth:`~window.getch` returns :const:`KEY_MOUSE` to signal a mouse event, this + method should be call to retrieve the queued mouse event, represented as a + 5-tuple ``(id, x, y, z, bstate)``. *id* is an ID value used to distinguish + multiple devices, and *x*, *y*, *z* are the event's coordinates. (*z* is + currently unused.) *bstate* is an integer value whose bits will be set to + indicate the type of event, and will be the bitwise OR of one or more of the + following constants, where *n* is the button number from 1 to 4: + :const:`BUTTONn_PRESSED`, :const:`BUTTONn_RELEASED`, :const:`BUTTONn_CLICKED`, + :const:`BUTTONn_DOUBLE_CLICKED`, :const:`BUTTONn_TRIPLE_CLICKED`, + :const:`BUTTON_SHIFT`, :const:`BUTTON_CTRL`, :const:`BUTTON_ALT`. + + +.. function:: getsyx() + + Return the current coordinates of the virtual screen cursor as a tuple + ``(y, x)``. If :meth:`leaveok ` is currently ``True``, then return ``(-1, -1)``. + + +.. function:: getwin(file) + + Read window related data stored in the file by an earlier :func:`putwin` call. + The routine then creates and initializes a new window using that data, returning + the new window object. + + +.. function:: has_colors() + + Return ``True`` if the terminal can display colors; otherwise, return ``False``. + + +.. function:: has_ic() + + Return ``True`` if the terminal has insert- and delete-character capabilities. + This function is included for historical reasons only, as all modern software + terminal emulators have such capabilities. + + +.. function:: has_il() + + Return ``True`` if the terminal has insert- and delete-line capabilities, or can + simulate them using scrolling regions. This function is included for + historical reasons only, as all modern software terminal emulators have such + capabilities. + + +.. function:: has_key(ch) + + Take a key value *ch*, and return ``True`` if the current terminal type recognizes + a key with that value. + + +.. function:: halfdelay(tenths) + + Used for half-delay mode, which is similar to cbreak mode in that characters + typed by the user are immediately available to the program. However, after + blocking for *tenths* tenths of seconds, raise an exception if nothing has + been typed. The value of *tenths* must be a number between ``1`` and ``255``. Use + :func:`nocbreak` to leave half-delay mode. + + +.. function:: init_color(color_number, r, g, b) + + Change the definition of a color, taking the number of the color to be changed + followed by three RGB values (for the amounts of red, green, and blue + components). The value of *color_number* must be between ``0`` and + :const:`COLORS`. Each of *r*, *g*, *b*, must be a value between ``0`` and + ``1000``. When :func:`init_color` is used, all occurrences of that color on the + screen immediately change to the new definition. This function is a no-op on + most terminals; it is active only if :func:`can_change_color` returns ``True``. + + +.. function:: init_pair(pair_number, fg, bg) + + Change the definition of a color-pair. It takes three arguments: the number of + the color-pair to be changed, the foreground color number, and the background + color number. The value of *pair_number* must be between ``1`` and + ``COLOR_PAIRS - 1`` (the ``0`` color pair is wired to white on black and cannot + be changed). The value of *fg* and *bg* arguments must be between ``0`` and + :const:`COLORS`. If the color-pair was previously initialized, the screen is + refreshed and all occurrences of that color-pair are changed to the new + definition. + + +.. function:: initscr() + + Initialize the library. Return a :ref:`window ` object + which represents the whole screen. + + .. note:: + + If there is an error opening the terminal, the underlying curses library may + cause the interpreter to exit. + + +.. function:: is_term_resized(nlines, ncols) + + Return ``True`` if :func:`resize_term` would modify the window structure, + ``False`` otherwise. + + +.. function:: isendwin() + + Return ``True`` if :func:`endwin` has been called (that is, the curses library has + been deinitialized). + + +.. function:: keyname(k) + + Return the name of the key numbered *k* as a bytes object. The name of a key generating printable + ASCII character is the key's character. The name of a control-key combination + is a two-byte bytes object consisting of a caret (``b'^'``) followed by the corresponding + printable ASCII character. The name of an alt-key combination (128--255) is a + bytes object consisting of the prefix ``b'M-'`` followed by the name of the corresponding + ASCII character. + + +.. function:: killchar() + + Return the user's current line kill character as a one-byte bytes object. Under Unix operating systems + this is a property of the controlling tty of the curses program, and is not set + by the curses library itself. + + +.. function:: longname() + + Return a bytes object containing the terminfo long name field describing the current + terminal. The maximum length of a verbose description is 128 characters. It is + defined only after the call to :func:`initscr`. + + +.. function:: meta(flag) + + If *flag* is ``True``, allow 8-bit characters to be input. If + *flag* is ``False``, allow only 7-bit chars. + + +.. function:: mouseinterval(interval) + + Set the maximum time in milliseconds that can elapse between press and release + events in order for them to be recognized as a click, and return the previous + interval value. The default value is 200 msec, or one fifth of a second. + + +.. function:: mousemask(mousemask) + + Set the mouse events to be reported, and return a tuple ``(availmask, + oldmask)``. *availmask* indicates which of the specified mouse events can be + reported; on complete failure it returns ``0``. *oldmask* is the previous value of + the given window's mouse event mask. If this function is never called, no mouse + events are ever reported. + + +.. function:: napms(ms) + + Sleep for *ms* milliseconds. + + +.. function:: newpad(nlines, ncols) + + Create and return a pointer to a new pad data structure with the given number + of lines and columns. Return a pad as a window object. + + A pad is like a window, except that it is not restricted by the screen size, and + is not necessarily associated with a particular part of the screen. Pads can be + used when a large window is needed, and only a part of the window will be on the + screen at one time. Automatic refreshes of pads (such as from scrolling or + echoing of input) do not occur. The :meth:`~window.refresh` and :meth:`~window.noutrefresh` + methods of a pad require 6 arguments to specify the part of the pad to be + displayed and the location on the screen to be used for the display. The + arguments are *pminrow*, *pmincol*, *sminrow*, *smincol*, *smaxrow*, *smaxcol*; the *p* + arguments refer to the upper left corner of the pad region to be displayed and + the *s* arguments define a clipping box on the screen within which the pad region + is to be displayed. + + +.. function:: newwin(nlines, ncols) + newwin(nlines, ncols, begin_y, begin_x) + + Return a new :ref:`window `, whose left-upper corner + is at ``(begin_y, begin_x)``, and whose height/width is *nlines*/*ncols*. + + By default, the window will extend from the specified position to the lower + right corner of the screen. + + +.. function:: nl() + + Enter newline mode. This mode translates the return key into newline on input, + and translates newline into return and line-feed on output. Newline mode is + initially on. + + +.. function:: nocbreak() + + Leave cbreak mode. Return to normal "cooked" mode with line buffering. + + +.. function:: noecho() + + Leave echo mode. Echoing of input characters is turned off. + + +.. function:: nonl() + + Leave newline mode. Disable translation of return into newline on input, and + disable low-level translation of newline into newline/return on output (but this + does not change the behavior of ``addch('\n')``, which always does the + equivalent of return and line feed on the virtual screen). With translation + off, curses can sometimes speed up vertical motion a little; also, it will be + able to detect the return key on input. + + +.. function:: noqiflush() + + When the :func:`!noqiflush` routine is used, normal flush of input and output queues + associated with the ``INTR``, ``QUIT`` and ``SUSP`` characters will not be done. You may + want to call :func:`!noqiflush` in a signal handler if you want output to + continue as though the interrupt had not occurred, after the handler exits. + + +.. function:: noraw() + + Leave raw mode. Return to normal "cooked" mode with line buffering. + + +.. function:: pair_content(pair_number) + + Return a tuple ``(fg, bg)`` containing the colors for the requested color pair. + The value of *pair_number* must be between ``1`` and ``COLOR_PAIRS - 1``. + + +.. function:: pair_number(attr) + + Return the number of the color-pair set by the attribute value *attr*. + :func:`color_pair` is the counterpart to this function. + + +.. function:: putp(str) + + Equivalent to ``tputs(str, 1, putchar)``; emit the value of a specified + terminfo capability for the current terminal. Note that the output of :func:`putp` + always goes to standard output. + + +.. function:: qiflush([flag]) + + If *flag* is ``False``, the effect is the same as calling :func:`noqiflush`. If + *flag* is ``True``, or no argument is provided, the queues will be flushed when + these control characters are read. + + +.. function:: raw() + + Enter raw mode. In raw mode, normal line buffering and processing of + interrupt, quit, suspend, and flow control keys are turned off; characters are + presented to curses input functions one by one. + + +.. function:: reset_prog_mode() + + Restore the terminal to "program" mode, as previously saved by + :func:`def_prog_mode`. + + +.. function:: reset_shell_mode() + + Restore the terminal to "shell" mode, as previously saved by + :func:`def_shell_mode`. + + +.. function:: resetty() + + Restore the state of the terminal modes to what it was at the last call to + :func:`savetty`. + + +.. function:: resize_term(nlines, ncols) + + Backend function used by :func:`resizeterm`, performing most of the work; + when resizing the windows, :func:`resize_term` blank-fills the areas that are + extended. The calling application should fill in these areas with + appropriate data. The :func:`!resize_term` function attempts to resize all + windows. However, due to the calling convention of pads, it is not possible + to resize these without additional interaction with the application. + + +.. function:: resizeterm(nlines, ncols) + + Resize the standard and current windows to the specified dimensions, and + adjusts other bookkeeping data used by the curses library that record the + window dimensions (in particular the SIGWINCH handler). + + +.. function:: savetty() + + Save the current state of the terminal modes in a buffer, usable by + :func:`resetty`. + +.. function:: get_escdelay() + + Retrieves the value set by :func:`set_escdelay`. + + .. versionadded:: 3.9 + +.. function:: set_escdelay(ms) + + Sets the number of milliseconds to wait after reading an escape character, + to distinguish between an individual escape character entered on the + keyboard from escape sequences sent by cursor and function keys. + + .. versionadded:: 3.9 + +.. function:: get_tabsize() + + Retrieves the value set by :func:`set_tabsize`. + + .. versionadded:: 3.9 + +.. function:: set_tabsize(size) + + Sets the number of columns used by the curses library when converting a tab + character to spaces as it adds the tab to a window. + + .. versionadded:: 3.9 + +.. function:: setsyx(y, x) + + Set the virtual screen cursor to *y*, *x*. If *y* and *x* are both ``-1``, then + :meth:`leaveok ` is set ``True``. + + +.. function:: setupterm(term=None, fd=-1) + + Initialize the terminal. *term* is a string giving + the terminal name, or ``None``; if omitted or ``None``, the value of the + :envvar:`TERM` environment variable will be used. *fd* is the + file descriptor to which any initialization sequences will be sent; if not + supplied or ``-1``, the file descriptor for ``sys.stdout`` will be used. + + +.. function:: start_color() + + Must be called if the programmer wants to use colors, and before any other color + manipulation routine is called. It is good practice to call this routine right + after :func:`initscr`. + + :func:`start_color` initializes eight basic colors (black, red, green, yellow, + blue, magenta, cyan, and white), and two global variables in the :mod:`curses` + module, :const:`COLORS` and :const:`COLOR_PAIRS`, containing the maximum number + of colors and color-pairs the terminal can support. It also restores the colors + on the terminal to the values they had when the terminal was just turned on. + + +.. function:: termattrs() + + Return a logical OR of all video attributes supported by the terminal. This + information is useful when a curses program needs complete control over the + appearance of the screen. + + +.. function:: termname() + + Return the value of the environment variable :envvar:`TERM`, as a bytes object, + truncated to 14 characters. + + +.. function:: tigetflag(capname) + + Return the value of the Boolean capability corresponding to the terminfo + capability name *capname* as an integer. Return the value ``-1`` if *capname* is not a + Boolean capability, or ``0`` if it is canceled or absent from the terminal + description. + + +.. function:: tigetnum(capname) + + Return the value of the numeric capability corresponding to the terminfo + capability name *capname* as an integer. Return the value ``-2`` if *capname* is not a + numeric capability, or ``-1`` if it is canceled or absent from the terminal + description. + + +.. function:: tigetstr(capname) + + Return the value of the string capability corresponding to the terminfo + capability name *capname* as a bytes object. Return ``None`` if *capname* + is not a terminfo "string capability", or is canceled or absent from the + terminal description. + + +.. function:: tparm(str[, ...]) + + Instantiate the bytes object *str* with the supplied parameters, where *str* should + be a parameterized string obtained from the terminfo database. E.g. + ``tparm(tigetstr("cup"), 5, 3)`` could result in ``b'\033[6;4H'``, the exact + result depending on terminal type. + + +.. function:: typeahead(fd) + + Specify that the file descriptor *fd* be used for typeahead checking. If *fd* + is ``-1``, then no typeahead checking is done. + + The curses library does "line-breakout optimization" by looking for typeahead + periodically while updating the screen. If input is found, and it is coming + from a tty, the current update is postponed until refresh or doupdate is called + again, allowing faster response to commands typed in advance. This function + allows specifying a different file descriptor for typeahead checking. + + +.. function:: unctrl(ch) + + Return a bytes object which is a printable representation of the character *ch*. + Control characters are represented as a caret followed by the character, for + example as ``b'^C'``. Printing characters are left as they are. + + +.. function:: ungetch(ch) + + Push *ch* so the next :meth:`~window.getch` will return it. + + .. note:: + + Only one *ch* can be pushed before :meth:`!getch` is called. + + +.. function:: update_lines_cols() + + Update :envvar:`LINES` and :envvar:`COLS`. Useful for detecting manual screen resize. + + .. versionadded:: 3.5 + + +.. function:: unget_wch(ch) + + Push *ch* so the next :meth:`~window.get_wch` will return it. + + .. note:: + + Only one *ch* can be pushed before :meth:`!get_wch` is called. + + .. versionadded:: 3.3 + + +.. function:: ungetmouse(id, x, y, z, bstate) + + Push a :const:`KEY_MOUSE` event onto the input queue, associating the given + state data with it. + + +.. function:: use_env(flag) + + If used, this function should be called before :func:`initscr` or newterm are + called. When *flag* is ``False``, the values of lines and columns specified in the + terminfo database will be used, even if environment variables :envvar:`LINES` + and :envvar:`COLUMNS` (used by default) are set, or if curses is running in a + window (in which case default behavior would be to use the window size if + :envvar:`LINES` and :envvar:`COLUMNS` are not set). + + +.. function:: use_default_colors() + + Allow use of default values for colors on terminals supporting this feature. Use + this to support transparency in your application. The default color is assigned + to the color number ``-1``. After calling this function, ``init_pair(x, + curses.COLOR_RED, -1)`` initializes, for instance, color pair *x* to a red + foreground color on the default background. + + +.. function:: wrapper(func, /, *args, **kwargs) + + Initialize curses and call another callable object, *func*, which should be the + rest of your curses-using application. If the application raises an exception, + this function will restore the terminal to a sane state before re-raising the + exception and generating a traceback. The callable object *func* is then passed + the main window 'stdscr' as its first argument, followed by any other arguments + passed to :func:`!wrapper`. Before calling *func*, :func:`!wrapper` turns on + cbreak mode, turns off echo, enables the terminal keypad, and initializes colors + if the terminal has color support. On exit (whether normally or by exception) + it restores cooked mode, turns on echo, and disables the terminal keypad. + + +.. _curses-window-objects: + +Window Objects +-------------- + +Window objects, as returned by :func:`initscr` and :func:`newwin` above, have +the following methods and attributes: + + +.. method:: window.addch(ch[, attr]) + window.addch(y, x, ch[, attr]) + + Paint character *ch* at ``(y, x)`` with attributes *attr*, overwriting any + character previously painter at that location. By default, the character + position and attributes are the current settings for the window object. + + .. note:: + + Writing outside the window, subwindow, or pad raises a :exc:`curses.error`. + Attempting to write to the lower right corner of a window, subwindow, + or pad will cause an exception to be raised after the character is printed. + + +.. method:: window.addnstr(str, n[, attr]) + window.addnstr(y, x, str, n[, attr]) + + Paint at most *n* characters of the character string *str* at + ``(y, x)`` with attributes + *attr*, overwriting anything previously on the display. + + +.. method:: window.addstr(str[, attr]) + window.addstr(y, x, str[, attr]) + + Paint the character string *str* at ``(y, x)`` with attributes + *attr*, overwriting anything previously on the display. + + .. note:: + + * Writing outside the window, subwindow, or pad raises :exc:`curses.error`. + Attempting to write to the lower right corner of a window, subwindow, + or pad will cause an exception to be raised after the string is printed. + + * A `bug in ncurses `_, the backend + for this Python module, can cause SegFaults when resizing windows. This + is fixed in ncurses-6.1-20190511. If you are stuck with an earlier + ncurses, you can avoid triggering this if you do not call :func:`addstr` + with a *str* that has embedded newlines. Instead, call :func:`addstr` + separately for each line. + + +.. method:: window.attroff(attr) + + Remove attribute *attr* from the "background" set applied to all writes to the + current window. + + +.. method:: window.attron(attr) + + Add attribute *attr* from the "background" set applied to all writes to the + current window. + + +.. method:: window.attrset(attr) + + Set the "background" set of attributes to *attr*. This set is initially + ``0`` (no attributes). + + +.. method:: window.bkgd(ch[, attr]) + + Set the background property of the window to the character *ch*, with + attributes *attr*. The change is then applied to every character position in + that window: + + * The attribute of every character in the window is changed to the new + background attribute. + + * Wherever the former background character appears, it is changed to the new + background character. + + +.. method:: window.bkgdset(ch[, attr]) + + Set the window's background. A window's background consists of a character and + any combination of attributes. The attribute part of the background is combined + (OR'ed) with all non-blank characters that are written into the window. Both + the character and attribute parts of the background are combined with the blank + characters. The background becomes a property of the character and moves with + the character through any scrolling and insert/delete line/character operations. + + +.. method:: window.border([ls[, rs[, ts[, bs[, tl[, tr[, bl[, br]]]]]]]]) + + Draw a border around the edges of the window. Each parameter specifies the + character to use for a specific part of the border; see the table below for more + details. + + .. note:: + + A ``0`` value for any parameter will cause the default character to be used for + that parameter. Keyword parameters can *not* be used. The defaults are listed + in this table: + + +-----------+---------------------+-----------------------+ + | Parameter | Description | Default value | + +===========+=====================+=======================+ + | *ls* | Left side | :const:`ACS_VLINE` | + +-----------+---------------------+-----------------------+ + | *rs* | Right side | :const:`ACS_VLINE` | + +-----------+---------------------+-----------------------+ + | *ts* | Top | :const:`ACS_HLINE` | + +-----------+---------------------+-----------------------+ + | *bs* | Bottom | :const:`ACS_HLINE` | + +-----------+---------------------+-----------------------+ + | *tl* | Upper-left corner | :const:`ACS_ULCORNER` | + +-----------+---------------------+-----------------------+ + | *tr* | Upper-right corner | :const:`ACS_URCORNER` | + +-----------+---------------------+-----------------------+ + | *bl* | Bottom-left corner | :const:`ACS_LLCORNER` | + +-----------+---------------------+-----------------------+ + | *br* | Bottom-right corner | :const:`ACS_LRCORNER` | + +-----------+---------------------+-----------------------+ + + +.. method:: window.box([vertch, horch]) + + Similar to :meth:`border`, but both *ls* and *rs* are *vertch* and both *ts* and + *bs* are *horch*. The default corner characters are always used by this function. + + +.. method:: window.chgat(attr) + window.chgat(num, attr) + window.chgat(y, x, attr) + window.chgat(y, x, num, attr) + + Set the attributes of *num* characters at the current cursor position, or at + position ``(y, x)`` if supplied. If *num* is not given or is ``-1``, + the attribute will be set on all the characters to the end of the line. This + function moves cursor to position ``(y, x)`` if supplied. The changed line + will be touched using the :meth:`touchline` method so that the contents will + be redisplayed by the next window refresh. + + +.. method:: window.clear() + + Like :meth:`erase`, but also cause the whole window to be repainted upon next + call to :meth:`refresh`. + + +.. method:: window.clearok(flag) + + If *flag* is ``True``, the next call to :meth:`refresh` will clear the window + completely. + + +.. method:: window.clrtobot() + + Erase from cursor to the end of the window: all lines below the cursor are + deleted, and then the equivalent of :meth:`clrtoeol` is performed. + + +.. method:: window.clrtoeol() + + Erase from cursor to the end of the line. + + +.. method:: window.cursyncup() + + Update the current cursor position of all the ancestors of the window to + reflect the current cursor position of the window. + + +.. method:: window.delch([y, x]) + + Delete any character at ``(y, x)``. + + +.. method:: window.deleteln() + + Delete the line under the cursor. All following lines are moved up by one line. + + +.. method:: window.derwin(begin_y, begin_x) + window.derwin(nlines, ncols, begin_y, begin_x) + + An abbreviation for "derive window", :meth:`derwin` is the same as calling + :meth:`subwin`, except that *begin_y* and *begin_x* are relative to the origin + of the window, rather than relative to the entire screen. Return a window + object for the derived window. + + +.. method:: window.echochar(ch[, attr]) + + Add character *ch* with attribute *attr*, and immediately call :meth:`refresh` + on the window. + + +.. method:: window.enclose(y, x) + + Test whether the given pair of screen-relative character-cell coordinates are + enclosed by the given window, returning ``True`` or ``False``. It is useful for + determining what subset of the screen windows enclose the location of a mouse + event. + + +.. attribute:: window.encoding + + Encoding used to encode method arguments (Unicode strings and characters). + The encoding attribute is inherited from the parent window when a subwindow + is created, for example with :meth:`window.subwin`. By default, the locale + encoding is used (see :func:`locale.getpreferredencoding`). + + .. versionadded:: 3.3 + + +.. method:: window.erase() + + Clear the window. + + +.. method:: window.getbegyx() + + Return a tuple ``(y, x)`` of co-ordinates of upper-left corner. + + +.. method:: window.getbkgd() + + Return the given window's current background character/attribute pair. + + +.. method:: window.getch([y, x]) + + Get a character. Note that the integer returned does *not* have to be in ASCII + range: function keys, keypad keys and so on are represented by numbers higher + than 255. In no-delay mode, return ``-1`` if there is no input, otherwise + wait until a key is pressed. + + +.. method:: window.get_wch([y, x]) + + Get a wide character. Return a character for most keys, or an integer for + function keys, keypad keys, and other special keys. + In no-delay mode, raise an exception if there is no input. + + .. versionadded:: 3.3 + + +.. method:: window.getkey([y, x]) + + Get a character, returning a string instead of an integer, as :meth:`getch` + does. Function keys, keypad keys and other special keys return a multibyte + string containing the key name. In no-delay mode, raise an exception if + there is no input. + + +.. method:: window.getmaxyx() + + Return a tuple ``(y, x)`` of the height and width of the window. + + +.. method:: window.getparyx() + + Return the beginning coordinates of this window relative to its parent window + as a tuple ``(y, x)``. Return ``(-1, -1)`` if this window has no + parent. + + +.. method:: window.getstr() + window.getstr(n) + window.getstr(y, x) + window.getstr(y, x, n) + + Read a bytes object from the user, with primitive line editing capacity. + + +.. method:: window.getyx() + + Return a tuple ``(y, x)`` of current cursor position relative to the window's + upper-left corner. + + +.. method:: window.hline(ch, n) + window.hline(y, x, ch, n) + + Display a horizontal line starting at ``(y, x)`` with length *n* consisting of + the character *ch*. + + +.. method:: window.idcok(flag) + + If *flag* is ``False``, curses no longer considers using the hardware insert/delete + character feature of the terminal; if *flag* is ``True``, use of character insertion + and deletion is enabled. When curses is first initialized, use of character + insert/delete is enabled by default. + + +.. method:: window.idlok(flag) + + If *flag* is ``True``, :mod:`curses` will try and use hardware line + editing facilities. Otherwise, line insertion/deletion are disabled. + + +.. method:: window.immedok(flag) + + If *flag* is ``True``, any change in the window image automatically causes the + window to be refreshed; you no longer have to call :meth:`refresh` yourself. + However, it may degrade performance considerably, due to repeated calls to + wrefresh. This option is disabled by default. + + +.. method:: window.inch([y, x]) + + Return the character at the given position in the window. The bottom 8 bits are + the character proper, and upper bits are the attributes. + + +.. method:: window.insch(ch[, attr]) + window.insch(y, x, ch[, attr]) + + Paint character *ch* at ``(y, x)`` with attributes *attr*, moving the line from + position *x* right by one character. + + +.. method:: window.insdelln(nlines) + + Insert *nlines* lines into the specified window above the current line. The + *nlines* bottom lines are lost. For negative *nlines*, delete *nlines* lines + starting with the one under the cursor, and move the remaining lines up. The + bottom *nlines* lines are cleared. The current cursor position remains the + same. + + +.. method:: window.insertln() + + Insert a blank line under the cursor. All following lines are moved down by one + line. + + +.. method:: window.insnstr(str, n[, attr]) + window.insnstr(y, x, str, n[, attr]) + + Insert a character string (as many characters as will fit on the line) before + the character under the cursor, up to *n* characters. If *n* is zero or + negative, the entire string is inserted. All characters to the right of the + cursor are shifted right, with the rightmost characters on the line being lost. + The cursor position does not change (after moving to *y*, *x*, if specified). + + +.. method:: window.insstr(str[, attr]) + window.insstr(y, x, str[, attr]) + + Insert a character string (as many characters as will fit on the line) before + the character under the cursor. All characters to the right of the cursor are + shifted right, with the rightmost characters on the line being lost. The cursor + position does not change (after moving to *y*, *x*, if specified). + + +.. method:: window.instr([n]) + window.instr(y, x[, n]) + + Return a bytes object of characters, extracted from the window starting at the + current cursor position, or at *y*, *x* if specified. Attributes are stripped + from the characters. If *n* is specified, :meth:`instr` returns a string + at most *n* characters long (exclusive of the trailing NUL). + + +.. method:: window.is_linetouched(line) + + Return ``True`` if the specified line was modified since the last call to + :meth:`refresh`; otherwise return ``False``. Raise a :exc:`curses.error` + exception if *line* is not valid for the given window. + + +.. method:: window.is_wintouched() + + Return ``True`` if the specified window was modified since the last call to + :meth:`refresh`; otherwise return ``False``. + + +.. method:: window.keypad(flag) + + If *flag* is ``True``, escape sequences generated by some keys (keypad, function keys) + will be interpreted by :mod:`curses`. If *flag* is ``False``, escape sequences will be + left as is in the input stream. + + +.. method:: window.leaveok(flag) + + If *flag* is ``True``, cursor is left where it is on update, instead of being at "cursor + position." This reduces cursor movement where possible. If possible the cursor + will be made invisible. + + If *flag* is ``False``, cursor will always be at "cursor position" after an update. + + +.. method:: window.move(new_y, new_x) + + Move cursor to ``(new_y, new_x)``. + + +.. method:: window.mvderwin(y, x) + + Move the window inside its parent window. The screen-relative parameters of + the window are not changed. This routine is used to display different parts of + the parent window at the same physical position on the screen. + + +.. method:: window.mvwin(new_y, new_x) + + Move the window so its upper-left corner is at ``(new_y, new_x)``. + + +.. method:: window.nodelay(flag) + + If *flag* is ``True``, :meth:`getch` will be non-blocking. + + +.. method:: window.notimeout(flag) + + If *flag* is ``True``, escape sequences will not be timed out. + + If *flag* is ``False``, after a few milliseconds, an escape sequence will not be + interpreted, and will be left in the input stream as is. + + +.. method:: window.noutrefresh() + + Mark for refresh but wait. This function updates the data structure + representing the desired state of the window, but does not force an update of + the physical screen. To accomplish that, call :func:`doupdate`. + + +.. method:: window.overlay(destwin[, sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol]) + + Overlay the window on top of *destwin*. The windows need not be the same size, + only the overlapping region is copied. This copy is non-destructive, which means + that the current background character does not overwrite the old contents of + *destwin*. + + To get fine-grained control over the copied region, the second form of + :meth:`overlay` can be used. *sminrow* and *smincol* are the upper-left + coordinates of the source window, and the other variables mark a rectangle in + the destination window. + + +.. method:: window.overwrite(destwin[, sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol]) + + Overwrite the window on top of *destwin*. The windows need not be the same size, + in which case only the overlapping region is copied. This copy is destructive, + which means that the current background character overwrites the old contents of + *destwin*. + + To get fine-grained control over the copied region, the second form of + :meth:`overwrite` can be used. *sminrow* and *smincol* are the upper-left + coordinates of the source window, the other variables mark a rectangle in the + destination window. + + +.. method:: window.putwin(file) + + Write all data associated with the window into the provided file object. This + information can be later retrieved using the :func:`getwin` function. + + +.. method:: window.redrawln(beg, num) + + Indicate that the *num* screen lines, starting at line *beg*, are corrupted and + should be completely redrawn on the next :meth:`refresh` call. + + +.. method:: window.redrawwin() + + Touch the entire window, causing it to be completely redrawn on the next + :meth:`refresh` call. + + +.. method:: window.refresh([pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol]) + + Update the display immediately (sync actual screen with previous + drawing/deleting methods). + + The 6 optional arguments can only be specified when the window is a pad created + with :func:`newpad`. The additional parameters are needed to indicate what part + of the pad and screen are involved. *pminrow* and *pmincol* specify the upper + left-hand corner of the rectangle to be displayed in the pad. *sminrow*, + *smincol*, *smaxrow*, and *smaxcol* specify the edges of the rectangle to be + displayed on the screen. The lower right-hand corner of the rectangle to be + displayed in the pad is calculated from the screen coordinates, since the + rectangles must be the same size. Both rectangles must be entirely contained + within their respective structures. Negative values of *pminrow*, *pmincol*, + *sminrow*, or *smincol* are treated as if they were zero. + + +.. method:: window.resize(nlines, ncols) + + Reallocate storage for a curses window to adjust its dimensions to the + specified values. If either dimension is larger than the current values, the + window's data is filled with blanks that have the current background + rendition (as set by :meth:`bkgdset`) merged into them. + + +.. method:: window.scroll([lines=1]) + + Scroll the screen or scrolling region upward by *lines* lines. + + +.. method:: window.scrollok(flag) + + Control what happens when the cursor of a window is moved off the edge of the + window or scrolling region, either as a result of a newline action on the bottom + line, or typing the last character of the last line. If *flag* is ``False``, the + cursor is left on the bottom line. If *flag* is ``True``, the window is scrolled up + one line. Note that in order to get the physical scrolling effect on the + terminal, it is also necessary to call :meth:`idlok`. + + +.. method:: window.setscrreg(top, bottom) + + Set the scrolling region from line *top* to line *bottom*. All scrolling actions + will take place in this region. + + +.. method:: window.standend() + + Turn off the standout attribute. On some terminals this has the side effect of + turning off all attributes. + + +.. method:: window.standout() + + Turn on attribute *A_STANDOUT*. + + +.. method:: window.subpad(begin_y, begin_x) + window.subpad(nlines, ncols, begin_y, begin_x) + + Return a sub-window, whose upper-left corner is at ``(begin_y, begin_x)``, and + whose width/height is *ncols*/*nlines*. + + +.. method:: window.subwin(begin_y, begin_x) + window.subwin(nlines, ncols, begin_y, begin_x) + + Return a sub-window, whose upper-left corner is at ``(begin_y, begin_x)``, and + whose width/height is *ncols*/*nlines*. + + By default, the sub-window will extend from the specified position to the lower + right corner of the window. + + +.. method:: window.syncdown() + + Touch each location in the window that has been touched in any of its ancestor + windows. This routine is called by :meth:`refresh`, so it should almost never + be necessary to call it manually. + + +.. method:: window.syncok(flag) + + If *flag* is ``True``, then :meth:`syncup` is called automatically + whenever there is a change in the window. + + +.. method:: window.syncup() + + Touch all locations in ancestors of the window that have been changed in the + window. + + +.. method:: window.timeout(delay) + + Set blocking or non-blocking read behavior for the window. If *delay* is + negative, blocking read is used (which will wait indefinitely for input). If + *delay* is zero, then non-blocking read is used, and :meth:`getch` will + return ``-1`` if no input is waiting. If *delay* is positive, then + :meth:`getch` will block for *delay* milliseconds, and return ``-1`` if there is + still no input at the end of that time. + + +.. method:: window.touchline(start, count[, changed]) + + Pretend *count* lines have been changed, starting with line *start*. If + *changed* is supplied, it specifies whether the affected lines are marked as + having been changed (*changed*\ ``=True``) or unchanged (*changed*\ ``=False``). + + +.. method:: window.touchwin() + + Pretend the whole window has been changed, for purposes of drawing + optimizations. + + +.. method:: window.untouchwin() + + Mark all lines in the window as unchanged since the last call to + :meth:`refresh`. + + +.. method:: window.vline(ch, n) + window.vline(y, x, ch, n) + + Display a vertical line starting at ``(y, x)`` with length *n* consisting of the + character *ch*. + + +Constants +--------- + +The :mod:`curses` module defines the following data members: + + +.. data:: ERR + + Some curses routines that return an integer, such as :meth:`~window.getch`, return + :const:`ERR` upon failure. + + +.. data:: OK + + Some curses routines that return an integer, such as :func:`napms`, return + :const:`OK` upon success. + + +.. data:: version + + A bytes object representing the current version of the module. Also available as + :const:`__version__`. + + +.. data:: ncurses_version + + A named tuple containing the three components of the ncurses library + version: *major*, *minor*, and *patch*. All values are integers. The + components can also be accessed by name, so ``curses.ncurses_version[0]`` + is equivalent to ``curses.ncurses_version.major`` and so on. + + Availability: if the ncurses library is used. + + .. versionadded:: 3.8 + + +Some constants are available to specify character cell attributes. +The exact constants available are system dependent. + ++------------------+-------------------------------+ +| Attribute | Meaning | ++==================+===============================+ +| ``A_ALTCHARSET`` | Alternate character set mode | ++------------------+-------------------------------+ +| ``A_BLINK`` | Blink mode | ++------------------+-------------------------------+ +| ``A_BOLD`` | Bold mode | ++------------------+-------------------------------+ +| ``A_DIM`` | Dim mode | ++------------------+-------------------------------+ +| ``A_INVIS`` | Invisible or blank mode | ++------------------+-------------------------------+ +| ``A_ITALIC`` | Italic mode | ++------------------+-------------------------------+ +| ``A_NORMAL`` | Normal attribute | ++------------------+-------------------------------+ +| ``A_PROTECT`` | Protected mode | ++------------------+-------------------------------+ +| ``A_REVERSE`` | Reverse background and | +| | foreground colors | ++------------------+-------------------------------+ +| ``A_STANDOUT`` | Standout mode | ++------------------+-------------------------------+ +| ``A_UNDERLINE`` | Underline mode | ++------------------+-------------------------------+ +| ``A_HORIZONTAL`` | Horizontal highlight | ++------------------+-------------------------------+ +| ``A_LEFT`` | Left highlight | ++------------------+-------------------------------+ +| ``A_LOW`` | Low highlight | ++------------------+-------------------------------+ +| ``A_RIGHT`` | Right highlight | ++------------------+-------------------------------+ +| ``A_TOP`` | Top highlight | ++------------------+-------------------------------+ +| ``A_VERTICAL`` | Vertical highlight | ++------------------+-------------------------------+ +| ``A_CHARTEXT`` | Bit-mask to extract a | +| | character | ++------------------+-------------------------------+ + +.. versionadded:: 3.7 + ``A_ITALIC`` was added. + +Several constants are available to extract corresponding attributes returned +by some methods. + ++------------------+-------------------------------+ +| Bit-mask | Meaning | ++==================+===============================+ +| ``A_ATTRIBUTES`` | Bit-mask to extract | +| | attributes | ++------------------+-------------------------------+ +| ``A_CHARTEXT`` | Bit-mask to extract a | +| | character | ++------------------+-------------------------------+ +| ``A_COLOR`` | Bit-mask to extract | +| | color-pair field information | ++------------------+-------------------------------+ + +Keys are referred to by integer constants with names starting with ``KEY_``. +The exact keycaps available are system dependent. + +.. XXX this table is far too large! should it be alphabetized? + ++-------------------+--------------------------------------------+ +| Key constant | Key | ++===================+============================================+ +| ``KEY_MIN`` | Minimum key value | ++-------------------+--------------------------------------------+ +| ``KEY_BREAK`` | Break key (unreliable) | ++-------------------+--------------------------------------------+ +| ``KEY_DOWN`` | Down-arrow | ++-------------------+--------------------------------------------+ +| ``KEY_UP`` | Up-arrow | ++-------------------+--------------------------------------------+ +| ``KEY_LEFT`` | Left-arrow | ++-------------------+--------------------------------------------+ +| ``KEY_RIGHT`` | Right-arrow | ++-------------------+--------------------------------------------+ +| ``KEY_HOME`` | Home key (upward+left arrow) | ++-------------------+--------------------------------------------+ +| ``KEY_BACKSPACE`` | Backspace (unreliable) | ++-------------------+--------------------------------------------+ +| ``KEY_F0`` | Function keys. Up to 64 function keys are | +| | supported. | ++-------------------+--------------------------------------------+ +| ``KEY_Fn`` | Value of function key *n* | ++-------------------+--------------------------------------------+ +| ``KEY_DL`` | Delete line | ++-------------------+--------------------------------------------+ +| ``KEY_IL`` | Insert line | ++-------------------+--------------------------------------------+ +| ``KEY_DC`` | Delete character | ++-------------------+--------------------------------------------+ +| ``KEY_IC`` | Insert char or enter insert mode | ++-------------------+--------------------------------------------+ +| ``KEY_EIC`` | Exit insert char mode | ++-------------------+--------------------------------------------+ +| ``KEY_CLEAR`` | Clear screen | ++-------------------+--------------------------------------------+ +| ``KEY_EOS`` | Clear to end of screen | ++-------------------+--------------------------------------------+ +| ``KEY_EOL`` | Clear to end of line | ++-------------------+--------------------------------------------+ +| ``KEY_SF`` | Scroll 1 line forward | ++-------------------+--------------------------------------------+ +| ``KEY_SR`` | Scroll 1 line backward (reverse) | ++-------------------+--------------------------------------------+ +| ``KEY_NPAGE`` | Next page | ++-------------------+--------------------------------------------+ +| ``KEY_PPAGE`` | Previous page | ++-------------------+--------------------------------------------+ +| ``KEY_STAB`` | Set tab | ++-------------------+--------------------------------------------+ +| ``KEY_CTAB`` | Clear tab | ++-------------------+--------------------------------------------+ +| ``KEY_CATAB`` | Clear all tabs | ++-------------------+--------------------------------------------+ +| ``KEY_ENTER`` | Enter or send (unreliable) | ++-------------------+--------------------------------------------+ +| ``KEY_SRESET`` | Soft (partial) reset (unreliable) | ++-------------------+--------------------------------------------+ +| ``KEY_RESET`` | Reset or hard reset (unreliable) | ++-------------------+--------------------------------------------+ +| ``KEY_PRINT`` | Print | ++-------------------+--------------------------------------------+ +| ``KEY_LL`` | Home down or bottom (lower left) | ++-------------------+--------------------------------------------+ +| ``KEY_A1`` | Upper left of keypad | ++-------------------+--------------------------------------------+ +| ``KEY_A3`` | Upper right of keypad | ++-------------------+--------------------------------------------+ +| ``KEY_B2`` | Center of keypad | ++-------------------+--------------------------------------------+ +| ``KEY_C1`` | Lower left of keypad | ++-------------------+--------------------------------------------+ +| ``KEY_C3`` | Lower right of keypad | ++-------------------+--------------------------------------------+ +| ``KEY_BTAB`` | Back tab | ++-------------------+--------------------------------------------+ +| ``KEY_BEG`` | Beg (beginning) | ++-------------------+--------------------------------------------+ +| ``KEY_CANCEL`` | Cancel | ++-------------------+--------------------------------------------+ +| ``KEY_CLOSE`` | Close | ++-------------------+--------------------------------------------+ +| ``KEY_COMMAND`` | Cmd (command) | ++-------------------+--------------------------------------------+ +| ``KEY_COPY`` | Copy | ++-------------------+--------------------------------------------+ +| ``KEY_CREATE`` | Create | ++-------------------+--------------------------------------------+ +| ``KEY_END`` | End | ++-------------------+--------------------------------------------+ +| ``KEY_EXIT`` | Exit | ++-------------------+--------------------------------------------+ +| ``KEY_FIND`` | Find | ++-------------------+--------------------------------------------+ +| ``KEY_HELP`` | Help | ++-------------------+--------------------------------------------+ +| ``KEY_MARK`` | Mark | ++-------------------+--------------------------------------------+ +| ``KEY_MESSAGE`` | Message | ++-------------------+--------------------------------------------+ +| ``KEY_MOVE`` | Move | ++-------------------+--------------------------------------------+ +| ``KEY_NEXT`` | Next | ++-------------------+--------------------------------------------+ +| ``KEY_OPEN`` | Open | ++-------------------+--------------------------------------------+ +| ``KEY_OPTIONS`` | Options | ++-------------------+--------------------------------------------+ +| ``KEY_PREVIOUS`` | Prev (previous) | ++-------------------+--------------------------------------------+ +| ``KEY_REDO`` | Redo | ++-------------------+--------------------------------------------+ +| ``KEY_REFERENCE`` | Ref (reference) | ++-------------------+--------------------------------------------+ +| ``KEY_REFRESH`` | Refresh | ++-------------------+--------------------------------------------+ +| ``KEY_REPLACE`` | Replace | ++-------------------+--------------------------------------------+ +| ``KEY_RESTART`` | Restart | ++-------------------+--------------------------------------------+ +| ``KEY_RESUME`` | Resume | ++-------------------+--------------------------------------------+ +| ``KEY_SAVE`` | Save | ++-------------------+--------------------------------------------+ +| ``KEY_SBEG`` | Shifted Beg (beginning) | ++-------------------+--------------------------------------------+ +| ``KEY_SCANCEL`` | Shifted Cancel | ++-------------------+--------------------------------------------+ +| ``KEY_SCOMMAND`` | Shifted Command | ++-------------------+--------------------------------------------+ +| ``KEY_SCOPY`` | Shifted Copy | ++-------------------+--------------------------------------------+ +| ``KEY_SCREATE`` | Shifted Create | ++-------------------+--------------------------------------------+ +| ``KEY_SDC`` | Shifted Delete char | ++-------------------+--------------------------------------------+ +| ``KEY_SDL`` | Shifted Delete line | ++-------------------+--------------------------------------------+ +| ``KEY_SELECT`` | Select | ++-------------------+--------------------------------------------+ +| ``KEY_SEND`` | Shifted End | ++-------------------+--------------------------------------------+ +| ``KEY_SEOL`` | Shifted Clear line | ++-------------------+--------------------------------------------+ +| ``KEY_SEXIT`` | Shifted Exit | ++-------------------+--------------------------------------------+ +| ``KEY_SFIND`` | Shifted Find | ++-------------------+--------------------------------------------+ +| ``KEY_SHELP`` | Shifted Help | ++-------------------+--------------------------------------------+ +| ``KEY_SHOME`` | Shifted Home | ++-------------------+--------------------------------------------+ +| ``KEY_SIC`` | Shifted Input | ++-------------------+--------------------------------------------+ +| ``KEY_SLEFT`` | Shifted Left arrow | ++-------------------+--------------------------------------------+ +| ``KEY_SMESSAGE`` | Shifted Message | ++-------------------+--------------------------------------------+ +| ``KEY_SMOVE`` | Shifted Move | ++-------------------+--------------------------------------------+ +| ``KEY_SNEXT`` | Shifted Next | ++-------------------+--------------------------------------------+ +| ``KEY_SOPTIONS`` | Shifted Options | ++-------------------+--------------------------------------------+ +| ``KEY_SPREVIOUS`` | Shifted Prev | ++-------------------+--------------------------------------------+ +| ``KEY_SPRINT`` | Shifted Print | ++-------------------+--------------------------------------------+ +| ``KEY_SREDO`` | Shifted Redo | ++-------------------+--------------------------------------------+ +| ``KEY_SREPLACE`` | Shifted Replace | ++-------------------+--------------------------------------------+ +| ``KEY_SRIGHT`` | Shifted Right arrow | ++-------------------+--------------------------------------------+ +| ``KEY_SRSUME`` | Shifted Resume | ++-------------------+--------------------------------------------+ +| ``KEY_SSAVE`` | Shifted Save | ++-------------------+--------------------------------------------+ +| ``KEY_SSUSPEND`` | Shifted Suspend | ++-------------------+--------------------------------------------+ +| ``KEY_SUNDO`` | Shifted Undo | ++-------------------+--------------------------------------------+ +| ``KEY_SUSPEND`` | Suspend | ++-------------------+--------------------------------------------+ +| ``KEY_UNDO`` | Undo | ++-------------------+--------------------------------------------+ +| ``KEY_MOUSE`` | Mouse event has occurred | ++-------------------+--------------------------------------------+ +| ``KEY_RESIZE`` | Terminal resize event | ++-------------------+--------------------------------------------+ +| ``KEY_MAX`` | Maximum key value | ++-------------------+--------------------------------------------+ + +On VT100s and their software emulations, such as X terminal emulators, there are +normally at least four function keys (:const:`KEY_F1`, :const:`KEY_F2`, +:const:`KEY_F3`, :const:`KEY_F4`) available, and the arrow keys mapped to +:const:`KEY_UP`, :const:`KEY_DOWN`, :const:`KEY_LEFT` and :const:`KEY_RIGHT` in +the obvious way. If your machine has a PC keyboard, it is safe to expect arrow +keys and twelve function keys (older PC keyboards may have only ten function +keys); also, the following keypad mappings are standard: + ++------------------+-----------+ +| Keycap | Constant | ++==================+===========+ +| :kbd:`Insert` | KEY_IC | ++------------------+-----------+ +| :kbd:`Delete` | KEY_DC | ++------------------+-----------+ +| :kbd:`Home` | KEY_HOME | ++------------------+-----------+ +| :kbd:`End` | KEY_END | ++------------------+-----------+ +| :kbd:`Page Up` | KEY_PPAGE | ++------------------+-----------+ +| :kbd:`Page Down` | KEY_NPAGE | ++------------------+-----------+ + +The following table lists characters from the alternate character set. These are +inherited from the VT100 terminal, and will generally be available on software +emulations such as X terminals. When there is no graphic available, curses +falls back on a crude printable ASCII approximation. + +.. note:: + + These are available only after :func:`initscr` has been called. + ++------------------+------------------------------------------+ +| ACS code | Meaning | ++==================+==========================================+ +| ``ACS_BBSS`` | alternate name for upper right corner | ++------------------+------------------------------------------+ +| ``ACS_BLOCK`` | solid square block | ++------------------+------------------------------------------+ +| ``ACS_BOARD`` | board of squares | ++------------------+------------------------------------------+ +| ``ACS_BSBS`` | alternate name for horizontal line | ++------------------+------------------------------------------+ +| ``ACS_BSSB`` | alternate name for upper left corner | ++------------------+------------------------------------------+ +| ``ACS_BSSS`` | alternate name for top tee | ++------------------+------------------------------------------+ +| ``ACS_BTEE`` | bottom tee | ++------------------+------------------------------------------+ +| ``ACS_BULLET`` | bullet | ++------------------+------------------------------------------+ +| ``ACS_CKBOARD`` | checker board (stipple) | ++------------------+------------------------------------------+ +| ``ACS_DARROW`` | arrow pointing down | ++------------------+------------------------------------------+ +| ``ACS_DEGREE`` | degree symbol | ++------------------+------------------------------------------+ +| ``ACS_DIAMOND`` | diamond | ++------------------+------------------------------------------+ +| ``ACS_GEQUAL`` | greater-than-or-equal-to | ++------------------+------------------------------------------+ +| ``ACS_HLINE`` | horizontal line | ++------------------+------------------------------------------+ +| ``ACS_LANTERN`` | lantern symbol | ++------------------+------------------------------------------+ +| ``ACS_LARROW`` | left arrow | ++------------------+------------------------------------------+ +| ``ACS_LEQUAL`` | less-than-or-equal-to | ++------------------+------------------------------------------+ +| ``ACS_LLCORNER`` | lower left-hand corner | ++------------------+------------------------------------------+ +| ``ACS_LRCORNER`` | lower right-hand corner | ++------------------+------------------------------------------+ +| ``ACS_LTEE`` | left tee | ++------------------+------------------------------------------+ +| ``ACS_NEQUAL`` | not-equal sign | ++------------------+------------------------------------------+ +| ``ACS_PI`` | letter pi | ++------------------+------------------------------------------+ +| ``ACS_PLMINUS`` | plus-or-minus sign | ++------------------+------------------------------------------+ +| ``ACS_PLUS`` | big plus sign | ++------------------+------------------------------------------+ +| ``ACS_RARROW`` | right arrow | ++------------------+------------------------------------------+ +| ``ACS_RTEE`` | right tee | ++------------------+------------------------------------------+ +| ``ACS_S1`` | scan line 1 | ++------------------+------------------------------------------+ +| ``ACS_S3`` | scan line 3 | ++------------------+------------------------------------------+ +| ``ACS_S7`` | scan line 7 | ++------------------+------------------------------------------+ +| ``ACS_S9`` | scan line 9 | ++------------------+------------------------------------------+ +| ``ACS_SBBS`` | alternate name for lower right corner | ++------------------+------------------------------------------+ +| ``ACS_SBSB`` | alternate name for vertical line | ++------------------+------------------------------------------+ +| ``ACS_SBSS`` | alternate name for right tee | ++------------------+------------------------------------------+ +| ``ACS_SSBB`` | alternate name for lower left corner | ++------------------+------------------------------------------+ +| ``ACS_SSBS`` | alternate name for bottom tee | ++------------------+------------------------------------------+ +| ``ACS_SSSB`` | alternate name for left tee | ++------------------+------------------------------------------+ +| ``ACS_SSSS`` | alternate name for crossover or big plus | ++------------------+------------------------------------------+ +| ``ACS_STERLING`` | pound sterling | ++------------------+------------------------------------------+ +| ``ACS_TTEE`` | top tee | ++------------------+------------------------------------------+ +| ``ACS_UARROW`` | up arrow | ++------------------+------------------------------------------+ +| ``ACS_ULCORNER`` | upper left corner | ++------------------+------------------------------------------+ +| ``ACS_URCORNER`` | upper right corner | ++------------------+------------------------------------------+ +| ``ACS_VLINE`` | vertical line | ++------------------+------------------------------------------+ + +The following table lists the predefined colors: + ++-------------------+----------------------------+ +| Constant | Color | ++===================+============================+ +| ``COLOR_BLACK`` | Black | ++-------------------+----------------------------+ +| ``COLOR_BLUE`` | Blue | ++-------------------+----------------------------+ +| ``COLOR_CYAN`` | Cyan (light greenish blue) | ++-------------------+----------------------------+ +| ``COLOR_GREEN`` | Green | ++-------------------+----------------------------+ +| ``COLOR_MAGENTA`` | Magenta (purplish red) | ++-------------------+----------------------------+ +| ``COLOR_RED`` | Red | ++-------------------+----------------------------+ +| ``COLOR_WHITE`` | White | ++-------------------+----------------------------+ +| ``COLOR_YELLOW`` | Yellow | ++-------------------+----------------------------+ + + +:mod:`curses.textpad` --- Text input widget for curses programs +=============================================================== + +.. module:: curses.textpad + :synopsis: Emacs-like input editing in a curses window. +.. moduleauthor:: Eric Raymond +.. sectionauthor:: Eric Raymond + + +The :mod:`curses.textpad` module provides a :class:`Textbox` class that handles +elementary text editing in a curses window, supporting a set of keybindings +resembling those of Emacs (thus, also of Netscape Navigator, BBedit 6.x, +FrameMaker, and many other programs). The module also provides a +rectangle-drawing function useful for framing text boxes or for other purposes. + +The module :mod:`curses.textpad` defines the following function: + + +.. function:: rectangle(win, uly, ulx, lry, lrx) + + Draw a rectangle. The first argument must be a window object; the remaining + arguments are coordinates relative to that window. The second and third + arguments are the y and x coordinates of the upper left hand corner of the + rectangle to be drawn; the fourth and fifth arguments are the y and x + coordinates of the lower right hand corner. The rectangle will be drawn using + VT100/IBM PC forms characters on terminals that make this possible (including + xterm and most other software terminal emulators). Otherwise it will be drawn + with ASCII dashes, vertical bars, and plus signs. + + +.. _curses-textpad-objects: + +Textbox objects +--------------- + +You can instantiate a :class:`Textbox` object as follows: + + +.. class:: Textbox(win) + + Return a textbox widget object. The *win* argument should be a curses + :ref:`window ` object in which the textbox is to + be contained. The edit cursor of the textbox is initially located at the + upper left hand corner of the containing window, with coordinates ``(0, 0)``. + The instance's :attr:`stripspaces` flag is initially on. + + :class:`Textbox` objects have the following methods: + + + .. method:: edit([validator]) + + This is the entry point you will normally use. It accepts editing + keystrokes until one of the termination keystrokes is entered. If + *validator* is supplied, it must be a function. It will be called for + each keystroke entered with the keystroke as a parameter; command dispatch + is done on the result. This method returns the window contents as a + string; whether blanks in the window are included is affected by the + :attr:`stripspaces` attribute. + + + .. method:: do_command(ch) + + Process a single command keystroke. Here are the supported special + keystrokes: + + +------------------+-------------------------------------------+ + | Keystroke | Action | + +==================+===========================================+ + | :kbd:`Control-A` | Go to left edge of window. | + +------------------+-------------------------------------------+ + | :kbd:`Control-B` | Cursor left, wrapping to previous line if | + | | appropriate. | + +------------------+-------------------------------------------+ + | :kbd:`Control-D` | Delete character under cursor. | + +------------------+-------------------------------------------+ + | :kbd:`Control-E` | Go to right edge (stripspaces off) or end | + | | of line (stripspaces on). | + +------------------+-------------------------------------------+ + | :kbd:`Control-F` | Cursor right, wrapping to next line when | + | | appropriate. | + +------------------+-------------------------------------------+ + | :kbd:`Control-G` | Terminate, returning the window contents. | + +------------------+-------------------------------------------+ + | :kbd:`Control-H` | Delete character backward. | + +------------------+-------------------------------------------+ + | :kbd:`Control-J` | Terminate if the window is 1 line, | + | | otherwise insert newline. | + +------------------+-------------------------------------------+ + | :kbd:`Control-K` | If line is blank, delete it, otherwise | + | | clear to end of line. | + +------------------+-------------------------------------------+ + | :kbd:`Control-L` | Refresh screen. | + +------------------+-------------------------------------------+ + | :kbd:`Control-N` | Cursor down; move down one line. | + +------------------+-------------------------------------------+ + | :kbd:`Control-O` | Insert a blank line at cursor location. | + +------------------+-------------------------------------------+ + | :kbd:`Control-P` | Cursor up; move up one line. | + +------------------+-------------------------------------------+ + + Move operations do nothing if the cursor is at an edge where the movement + is not possible. The following synonyms are supported where possible: + + +------------------------+------------------+ + | Constant | Keystroke | + +========================+==================+ + | :const:`KEY_LEFT` | :kbd:`Control-B` | + +------------------------+------------------+ + | :const:`KEY_RIGHT` | :kbd:`Control-F` | + +------------------------+------------------+ + | :const:`KEY_UP` | :kbd:`Control-P` | + +------------------------+------------------+ + | :const:`KEY_DOWN` | :kbd:`Control-N` | + +------------------------+------------------+ + | :const:`KEY_BACKSPACE` | :kbd:`Control-h` | + +------------------------+------------------+ + + All other keystrokes are treated as a command to insert the given + character and move right (with line wrapping). + + + .. method:: gather() + + Return the window contents as a string; whether blanks in the + window are included is affected by the :attr:`stripspaces` member. + + + .. attribute:: stripspaces + + This attribute is a flag which controls the interpretation of blanks in + the window. When it is on, trailing blanks on each line are ignored; any + cursor motion that would land the cursor on a trailing blank goes to the + end of that line instead, and trailing blanks are stripped when the window + contents are gathered. diff --git a/cpython_2/environment/repo/Doc/library/custominterp.rst b/cpython_2/environment/repo/Doc/library/custominterp.rst new file mode 100644 index 0000000000000000000000000000000000000000..5eeced20a9a594734ad8d1ccf2de4eefcee2007d --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/custominterp.rst @@ -0,0 +1,19 @@ +.. _custominterp: + +************************** +Custom Python Interpreters +************************** + +The modules described in this chapter allow writing interfaces similar to +Python's interactive interpreter. If you want a Python interpreter that +supports some special feature in addition to the Python language, you should +look at the :mod:`code` module. (The :mod:`codeop` module is lower-level, used +to support compiling a possibly-incomplete chunk of Python code.) + +The full list of modules described in this chapter is: + + +.. toctree:: + + code.rst + codeop.rst diff --git a/cpython_2/environment/repo/Doc/library/dataclasses.rst b/cpython_2/environment/repo/Doc/library/dataclasses.rst new file mode 100644 index 0000000000000000000000000000000000000000..fe63d20671dd744fc3ac87b54b1d98754acceb9f --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/dataclasses.rst @@ -0,0 +1,595 @@ +:mod:`dataclasses` --- Data Classes +=================================== + +.. module:: dataclasses + :synopsis: Generate special methods on user-defined classes. + +.. moduleauthor:: Eric V. Smith +.. sectionauthor:: Eric V. Smith + +**Source code:** :source:`Lib/dataclasses.py` + +-------------- + +This module provides a decorator and functions for automatically +adding generated :term:`special method`\s such as :meth:`__init__` and +:meth:`__repr__` to user-defined classes. It was originally described +in :pep:`557`. + +The member variables to use in these generated methods are defined +using :pep:`526` type annotations. For example this code:: + + from dataclasses import dataclass + + @dataclass + class InventoryItem: + '''Class for keeping track of an item in inventory.''' + name: str + unit_price: float + quantity_on_hand: int = 0 + + def total_cost(self) -> float: + return self.unit_price * self.quantity_on_hand + +Will add, among other things, a :meth:`__init__` that looks like:: + + def __init__(self, name: str, unit_price: float, quantity_on_hand: int=0): + self.name = name + self.unit_price = unit_price + self.quantity_on_hand = quantity_on_hand + +Note that this method is automatically added to the class: it is not +directly specified in the ``InventoryItem`` definition shown above. + +.. versionadded:: 3.7 + +Module-level decorators, classes, and functions +----------------------------------------------- + +.. decorator:: dataclass(*, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False) + + This function is a :term:`decorator` that is used to add generated + :term:`special method`\s to classes, as described below. + + The :func:`dataclass` decorator examines the class to find + ``field``\s. A ``field`` is defined as class variable that has a + :term:`type annotation `. With two + exceptions described below, nothing in :func:`dataclass` + examines the type specified in the variable annotation. + + The order of the fields in all of the generated methods is the + order in which they appear in the class definition. + + The :func:`dataclass` decorator will add various "dunder" methods to + the class, described below. If any of the added methods already + exist on the class, the behavior depends on the parameter, as documented + below. The decorator returns the same class that is called on; no new + class is created. + + If :func:`dataclass` is used just as a simple decorator with no parameters, + it acts as if it has the default values documented in this + signature. That is, these three uses of :func:`dataclass` are + equivalent:: + + @dataclass + class C: + ... + + @dataclass() + class C: + ... + + @dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False) + class C: + ... + + The parameters to :func:`dataclass` are: + + - ``init``: If true (the default), a :meth:`__init__` method will be + generated. + + If the class already defines :meth:`__init__`, this parameter is + ignored. + + - ``repr``: If true (the default), a :meth:`__repr__` method will be + generated. The generated repr string will have the class name and + the name and repr of each field, in the order they are defined in + the class. Fields that are marked as being excluded from the repr + are not included. For example: + ``InventoryItem(name='widget', unit_price=3.0, quantity_on_hand=10)``. + + If the class already defines :meth:`__repr__`, this parameter is + ignored. + + - ``eq``: If true (the default), an :meth:`__eq__` method will be + generated. This method compares the class as if it were a tuple + of its fields, in order. Both instances in the comparison must + be of the identical type. + + If the class already defines :meth:`__eq__`, this parameter is + ignored. + + - ``order``: If true (the default is ``False``), :meth:`__lt__`, + :meth:`__le__`, :meth:`__gt__`, and :meth:`__ge__` methods will be + generated. These compare the class as if it were a tuple of its + fields, in order. Both instances in the comparison must be of the + identical type. If ``order`` is true and ``eq`` is false, a + :exc:`ValueError` is raised. + + If the class already defines any of :meth:`__lt__`, + :meth:`__le__`, :meth:`__gt__`, or :meth:`__ge__`, then + :exc:`TypeError` is raised. + + - ``unsafe_hash``: If ``False`` (the default), a :meth:`__hash__` method + is generated according to how ``eq`` and ``frozen`` are set. + + :meth:`__hash__` is used by built-in :meth:`hash()`, and when objects are + added to hashed collections such as dictionaries and sets. Having a + :meth:`__hash__` implies that instances of the class are immutable. + Mutability is a complicated property that depends on the programmer's + intent, the existence and behavior of :meth:`__eq__`, and the values of + the ``eq`` and ``frozen`` flags in the :func:`dataclass` decorator. + + By default, :func:`dataclass` will not implicitly add a :meth:`__hash__` + method unless it is safe to do so. Neither will it add or change an + existing explicitly defined :meth:`__hash__` method. Setting the class + attribute ``__hash__ = None`` has a specific meaning to Python, as + described in the :meth:`__hash__` documentation. + + If :meth:`__hash__` is not explicit defined, or if it is set to ``None``, + then :func:`dataclass` *may* add an implicit :meth:`__hash__` method. + Although not recommended, you can force :func:`dataclass` to create a + :meth:`__hash__` method with ``unsafe_hash=True``. This might be the case + if your class is logically immutable but can nonetheless be mutated. + This is a specialized use case and should be considered carefully. + + Here are the rules governing implicit creation of a :meth:`__hash__` + method. Note that you cannot both have an explicit :meth:`__hash__` + method in your dataclass and set ``unsafe_hash=True``; this will result + in a :exc:`TypeError`. + + If ``eq`` and ``frozen`` are both true, by default :func:`dataclass` will + generate a :meth:`__hash__` method for you. If ``eq`` is true and + ``frozen`` is false, :meth:`__hash__` will be set to ``None``, marking it + unhashable (which it is, since it is mutable). If ``eq`` is false, + :meth:`__hash__` will be left untouched meaning the :meth:`__hash__` + method of the superclass will be used (if the superclass is + :class:`object`, this means it will fall back to id-based hashing). + + - ``frozen``: If true (the default is ``False``), assigning to fields will + generate an exception. This emulates read-only frozen instances. If + :meth:`__setattr__` or :meth:`__delattr__` is defined in the class, then + :exc:`TypeError` is raised. See the discussion below. + + ``field``\s may optionally specify a default value, using normal + Python syntax:: + + @dataclass + class C: + a: int # 'a' has no default value + b: int = 0 # assign a default value for 'b' + + In this example, both ``a`` and ``b`` will be included in the added + :meth:`__init__` method, which will be defined as:: + + def __init__(self, a: int, b: int = 0): + + :exc:`TypeError` will be raised if a field without a default value + follows a field with a default value. This is true either when this + occurs in a single class, or as a result of class inheritance. + +.. function:: field(*, default=MISSING, default_factory=MISSING, repr=True, hash=None, init=True, compare=True, metadata=None) + + For common and simple use cases, no other functionality is + required. There are, however, some dataclass features that + require additional per-field information. To satisfy this need for + additional information, you can replace the default field value + with a call to the provided :func:`field` function. For example:: + + @dataclass + class C: + mylist: List[int] = field(default_factory=list) + + c = C() + c.mylist += [1, 2, 3] + + As shown above, the ``MISSING`` value is a sentinel object used to + detect if the ``default`` and ``default_factory`` parameters are + provided. This sentinel is used because ``None`` is a valid value + for ``default``. No code should directly use the ``MISSING`` + value. + + The parameters to :func:`field` are: + + - ``default``: If provided, this will be the default value for this + field. This is needed because the :meth:`field` call itself + replaces the normal position of the default value. + + - ``default_factory``: If provided, it must be a zero-argument + callable that will be called when a default value is needed for + this field. Among other purposes, this can be used to specify + fields with mutable default values, as discussed below. It is an + error to specify both ``default`` and ``default_factory``. + + - ``init``: If true (the default), this field is included as a + parameter to the generated :meth:`__init__` method. + + - ``repr``: If true (the default), this field is included in the + string returned by the generated :meth:`__repr__` method. + + - ``compare``: If true (the default), this field is included in the + generated equality and comparison methods (:meth:`__eq__`, + :meth:`__gt__`, et al.). + + - ``hash``: This can be a bool or ``None``. If true, this field is + included in the generated :meth:`__hash__` method. If ``None`` (the + default), use the value of ``compare``: this would normally be + the expected behavior. A field should be considered in the hash + if it's used for comparisons. Setting this value to anything + other than ``None`` is discouraged. + + One possible reason to set ``hash=False`` but ``compare=True`` + would be if a field is expensive to compute a hash value for, + that field is needed for equality testing, and there are other + fields that contribute to the type's hash value. Even if a field + is excluded from the hash, it will still be used for comparisons. + + - ``metadata``: This can be a mapping or None. None is treated as + an empty dict. This value is wrapped in + :func:`~types.MappingProxyType` to make it read-only, and exposed + on the :class:`Field` object. It is not used at all by Data + Classes, and is provided as a third-party extension mechanism. + Multiple third-parties can each have their own key, to use as a + namespace in the metadata. + + If the default value of a field is specified by a call to + :func:`field()`, then the class attribute for this field will be + replaced by the specified ``default`` value. If no ``default`` is + provided, then the class attribute will be deleted. The intent is + that after the :func:`dataclass` decorator runs, the class + attributes will all contain the default values for the fields, just + as if the default value itself were specified. For example, + after:: + + @dataclass + class C: + x: int + y: int = field(repr=False) + z: int = field(repr=False, default=10) + t: int = 20 + + The class attribute ``C.z`` will be ``10``, the class attribute + ``C.t`` will be ``20``, and the class attributes ``C.x`` and + ``C.y`` will not be set. + +.. class:: Field + + :class:`Field` objects describe each defined field. These objects + are created internally, and are returned by the :func:`fields` + module-level method (see below). Users should never instantiate a + :class:`Field` object directly. Its documented attributes are: + + - ``name``: The name of the field. + + - ``type``: The type of the field. + + - ``default``, ``default_factory``, ``init``, ``repr``, ``hash``, + ``compare``, and ``metadata`` have the identical meaning and + values as they do in the :func:`field` declaration. + + Other attributes may exist, but they are private and must not be + inspected or relied on. + +.. function:: fields(class_or_instance) + + Returns a tuple of :class:`Field` objects that define the fields for this + dataclass. Accepts either a dataclass, or an instance of a dataclass. + Raises :exc:`TypeError` if not passed a dataclass or instance of one. + Does not return pseudo-fields which are ``ClassVar`` or ``InitVar``. + +.. function:: asdict(instance, *, dict_factory=dict) + + Converts the dataclass ``instance`` to a dict (by using the + factory function ``dict_factory``). Each dataclass is converted + to a dict of its fields, as ``name: value`` pairs. dataclasses, dicts, + lists, and tuples are recursed into. For example:: + + @dataclass + class Point: + x: int + y: int + + @dataclass + class C: + mylist: List[Point] + + p = Point(10, 20) + assert asdict(p) == {'x': 10, 'y': 20} + + c = C([Point(0, 0), Point(10, 4)]) + assert asdict(c) == {'mylist': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]} + + Raises :exc:`TypeError` if ``instance`` is not a dataclass instance. + +.. function:: astuple(instance, *, tuple_factory=tuple) + + Converts the dataclass ``instance`` to a tuple (by using the + factory function ``tuple_factory``). Each dataclass is converted + to a tuple of its field values. dataclasses, dicts, lists, and + tuples are recursed into. + + Continuing from the previous example:: + + assert astuple(p) == (10, 20) + assert astuple(c) == ([(0, 0), (10, 4)],) + + Raises :exc:`TypeError` if ``instance`` is not a dataclass instance. + +.. function:: make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False) + + Creates a new dataclass with name ``cls_name``, fields as defined + in ``fields``, base classes as given in ``bases``, and initialized + with a namespace as given in ``namespace``. ``fields`` is an + iterable whose elements are each either ``name``, ``(name, type)``, + or ``(name, type, Field)``. If just ``name`` is supplied, + ``typing.Any`` is used for ``type``. The values of ``init``, + ``repr``, ``eq``, ``order``, ``unsafe_hash``, and ``frozen`` have + the same meaning as they do in :func:`dataclass`. + + This function is not strictly required, because any Python + mechanism for creating a new class with ``__annotations__`` can + then apply the :func:`dataclass` function to convert that class to + a dataclass. This function is provided as a convenience. For + example:: + + C = make_dataclass('C', + [('x', int), + 'y', + ('z', int, field(default=5))], + namespace={'add_one': lambda self: self.x + 1}) + + Is equivalent to:: + + @dataclass + class C: + x: int + y: 'typing.Any' + z: int = 5 + + def add_one(self): + return self.x + 1 + +.. function:: replace(instance, /, **changes) + + Creates a new object of the same type of ``instance``, replacing + fields with values from ``changes``. If ``instance`` is not a Data + Class, raises :exc:`TypeError`. If values in ``changes`` do not + specify fields, raises :exc:`TypeError`. + + The newly returned object is created by calling the :meth:`__init__` + method of the dataclass. This ensures that + :meth:`__post_init__`, if present, is also called. + + Init-only variables without default values, if any exist, must be + specified on the call to :func:`replace` so that they can be passed to + :meth:`__init__` and :meth:`__post_init__`. + + It is an error for ``changes`` to contain any fields that are + defined as having ``init=False``. A :exc:`ValueError` will be raised + in this case. + + Be forewarned about how ``init=False`` fields work during a call to + :func:`replace`. They are not copied from the source object, but + rather are initialized in :meth:`__post_init__`, if they're + initialized at all. It is expected that ``init=False`` fields will + be rarely and judiciously used. If they are used, it might be wise + to have alternate class constructors, or perhaps a custom + ``replace()`` (or similarly named) method which handles instance + copying. + +.. function:: is_dataclass(class_or_instance) + + Return ``True`` if its parameter is a dataclass or an instance of one, + otherwise return ``False``. + + If you need to know if a class is an instance of a dataclass (and + not a dataclass itself), then add a further check for ``not + isinstance(obj, type)``:: + + def is_dataclass_instance(obj): + return is_dataclass(obj) and not isinstance(obj, type) + +Post-init processing +-------------------- + +The generated :meth:`__init__` code will call a method named +:meth:`__post_init__`, if :meth:`__post_init__` is defined on the +class. It will normally be called as ``self.__post_init__()``. +However, if any ``InitVar`` fields are defined, they will also be +passed to :meth:`__post_init__` in the order they were defined in the +class. If no :meth:`__init__` method is generated, then +:meth:`__post_init__` will not automatically be called. + +Among other uses, this allows for initializing field values that +depend on one or more other fields. For example:: + + @dataclass + class C: + a: float + b: float + c: float = field(init=False) + + def __post_init__(self): + self.c = self.a + self.b + +See the section below on init-only variables for ways to pass +parameters to :meth:`__post_init__`. Also see the warning about how +:func:`replace` handles ``init=False`` fields. + +Class variables +--------------- + +One of two places where :func:`dataclass` actually inspects the type +of a field is to determine if a field is a class variable as defined +in :pep:`526`. It does this by checking if the type of the field is +``typing.ClassVar``. If a field is a ``ClassVar``, it is excluded +from consideration as a field and is ignored by the dataclass +mechanisms. Such ``ClassVar`` pseudo-fields are not returned by the +module-level :func:`fields` function. + +Init-only variables +------------------- + +The other place where :func:`dataclass` inspects a type annotation is to +determine if a field is an init-only variable. It does this by seeing +if the type of a field is of type ``dataclasses.InitVar``. If a field +is an ``InitVar``, it is considered a pseudo-field called an init-only +field. As it is not a true field, it is not returned by the +module-level :func:`fields` function. Init-only fields are added as +parameters to the generated :meth:`__init__` method, and are passed to +the optional :meth:`__post_init__` method. They are not otherwise used +by dataclasses. + +For example, suppose a field will be initialized from a database, if a +value is not provided when creating the class:: + + @dataclass + class C: + i: int + j: int = None + database: InitVar[DatabaseType] = None + + def __post_init__(self, database): + if self.j is None and database is not None: + self.j = database.lookup('j') + + c = C(10, database=my_database) + +In this case, :func:`fields` will return :class:`Field` objects for ``i`` and +``j``, but not for ``database``. + +Frozen instances +---------------- + +It is not possible to create truly immutable Python objects. However, +by passing ``frozen=True`` to the :meth:`dataclass` decorator you can +emulate immutability. In that case, dataclasses will add +:meth:`__setattr__` and :meth:`__delattr__` methods to the class. These +methods will raise a :exc:`FrozenInstanceError` when invoked. + +There is a tiny performance penalty when using ``frozen=True``: +:meth:`__init__` cannot use simple assignment to initialize fields, and +must use :meth:`object.__setattr__`. + +Inheritance +----------- + +When the dataclass is being created by the :meth:`dataclass` decorator, +it looks through all of the class's base classes in reverse MRO (that +is, starting at :class:`object`) and, for each dataclass that it finds, +adds the fields from that base class to an ordered mapping of fields. +After all of the base class fields are added, it adds its own fields +to the ordered mapping. All of the generated methods will use this +combined, calculated ordered mapping of fields. Because the fields +are in insertion order, derived classes override base classes. An +example:: + + @dataclass + class Base: + x: Any = 15.0 + y: int = 0 + + @dataclass + class C(Base): + z: int = 10 + x: int = 15 + +The final list of fields is, in order, ``x``, ``y``, ``z``. The final +type of ``x`` is ``int``, as specified in class ``C``. + +The generated :meth:`__init__` method for ``C`` will look like:: + + def __init__(self, x: int = 15, y: int = 0, z: int = 10): + +Default factory functions +------------------------- + + If a :func:`field` specifies a ``default_factory``, it is called with + zero arguments when a default value for the field is needed. For + example, to create a new instance of a list, use:: + + mylist: list = field(default_factory=list) + + If a field is excluded from :meth:`__init__` (using ``init=False``) + and the field also specifies ``default_factory``, then the default + factory function will always be called from the generated + :meth:`__init__` function. This happens because there is no other + way to give the field an initial value. + +Mutable default values +---------------------- + + Python stores default member variable values in class attributes. + Consider this example, not using dataclasses:: + + class C: + x = [] + def add(self, element): + self.x.append(element) + + o1 = C() + o2 = C() + o1.add(1) + o2.add(2) + assert o1.x == [1, 2] + assert o1.x is o2.x + + Note that the two instances of class ``C`` share the same class + variable ``x``, as expected. + + Using dataclasses, *if* this code was valid:: + + @dataclass + class D: + x: List = [] + def add(self, element): + self.x += element + + it would generate code similar to:: + + class D: + x = [] + def __init__(self, x=x): + self.x = x + def add(self, element): + self.x += element + + assert D().x is D().x + + This has the same issue as the original example using class ``C``. + That is, two instances of class ``D`` that do not specify a value for + ``x`` when creating a class instance will share the same copy of + ``x``. Because dataclasses just use normal Python class creation + they also share this behavior. There is no general way for Data + Classes to detect this condition. Instead, dataclasses will raise a + :exc:`TypeError` if it detects a default parameter of type ``list``, + ``dict``, or ``set``. This is a partial solution, but it does protect + against many common errors. + + Using default factory functions is a way to create new instances of + mutable types as default values for fields:: + + @dataclass + class D: + x: list = field(default_factory=list) + + assert D().x is not D().x + +Exceptions +---------- + +.. exception:: FrozenInstanceError + + Raised when an implicitly defined :meth:`__setattr__` or + :meth:`__delattr__` is called on a dataclass which was defined with + ``frozen=True``. diff --git a/cpython_2/environment/repo/Doc/library/datatypes.rst b/cpython_2/environment/repo/Doc/library/datatypes.rst new file mode 100644 index 0000000000000000000000000000000000000000..94010c0e391b0b0ed67c746e242f5c32e5622994 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/datatypes.rst @@ -0,0 +1,34 @@ +.. _datatypes: + +********** +Data Types +********** + +The modules described in this chapter provide a variety of specialized data +types such as dates and times, fixed-type arrays, heap queues, double-ended +queues, and enumerations. + +Python also provides some built-in data types, in particular, +:class:`dict`, :class:`list`, :class:`set` and :class:`frozenset`, and +:class:`tuple`. The :class:`str` class is used to hold +Unicode strings, and the :class:`bytes` and :class:`bytearray` classes are used +to hold binary data. + +The following modules are documented in this chapter: + + +.. toctree:: + + datetime.rst + calendar.rst + collections.rst + collections.abc.rst + heapq.rst + bisect.rst + array.rst + weakref.rst + types.rst + copy.rst + pprint.rst + reprlib.rst + enum.rst diff --git a/cpython_2/environment/repo/Doc/library/datetime.rst b/cpython_2/environment/repo/Doc/library/datetime.rst new file mode 100644 index 0000000000000000000000000000000000000000..22ecbb551d89736ab10b960d5aa28154d89182ce --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/datetime.rst @@ -0,0 +1,2582 @@ +:mod:`datetime` --- Basic date and time types +============================================= + +.. module:: datetime + :synopsis: Basic date and time types. + +.. moduleauthor:: Tim Peters +.. sectionauthor:: Tim Peters +.. sectionauthor:: A.M. Kuchling + +**Source code:** :source:`Lib/datetime.py` + +-------------- + +.. XXX what order should the types be discussed in? + +The :mod:`datetime` module supplies classes for manipulating dates and times. + +While date and time arithmetic is supported, the focus of the implementation is +on efficient attribute extraction for output formatting and manipulation. + +.. seealso:: + + Module :mod:`calendar` + General calendar related functions. + + Module :mod:`time` + Time access and conversions. + + Package `dateutil `_ + Third-party library with expanded time zone and parsing support. + +.. _datetime-naive-aware: + +Aware and Naive Objects +----------------------- + +Date and time objects may be categorized as "aware" or "naive." + +With sufficient knowledge of applicable algorithmic and political time +adjustments, such as time zone and daylight saving time information, +an **aware** object can locate itself relative to other aware objects. +An aware object represents a specific moment in time that is not open to +interpretation. [#]_ + +A **naive** object does not contain enough information to unambiguously locate +itself relative to other date/time objects. Whether a naive object represents +Coordinated Universal Time (UTC), local time, or time in some other timezone is +purely up to the program, just like it is up to the program whether a +particular number represents metres, miles, or mass. Naive objects are easy to +understand and to work with, at the cost of ignoring some aspects of reality. + +For applications requiring aware objects, :class:`.datetime` and :class:`.time` +objects have an optional time zone information attribute, :attr:`!tzinfo`, that +can be set to an instance of a subclass of the abstract :class:`tzinfo` class. +These :class:`tzinfo` objects capture information about the offset from UTC +time, the time zone name, and whether daylight saving time is in effect. + +Only one concrete :class:`tzinfo` class, the :class:`timezone` class, is +supplied by the :mod:`datetime` module. The :class:`timezone` class can +represent simple timezones with fixed offsets from UTC, such as UTC itself or +North American EST and EDT timezones. Supporting timezones at deeper levels of +detail is up to the application. The rules for time adjustment across the +world are more political than rational, change frequently, and there is no +standard suitable for every application aside from UTC. + +Constants +--------- + +The :mod:`datetime` module exports the following constants: + +.. data:: MINYEAR + + The smallest year number allowed in a :class:`date` or :class:`.datetime` object. + :const:`MINYEAR` is ``1``. + + +.. data:: MAXYEAR + + The largest year number allowed in a :class:`date` or :class:`.datetime` object. + :const:`MAXYEAR` is ``9999``. + +Available Types +--------------- + +.. class:: date + :noindex: + + An idealized naive date, assuming the current Gregorian calendar always was, and + always will be, in effect. Attributes: :attr:`year`, :attr:`month`, and + :attr:`day`. + + +.. class:: time + :noindex: + + An idealized time, independent of any particular day, assuming that every day + has exactly 24\*60\*60 seconds. (There is no notion of "leap seconds" here.) + Attributes: :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`, + and :attr:`.tzinfo`. + + +.. class:: datetime + :noindex: + + A combination of a date and a time. Attributes: :attr:`year`, :attr:`month`, + :attr:`day`, :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`, + and :attr:`.tzinfo`. + + +.. class:: timedelta + :noindex: + + A duration expressing the difference between two :class:`date`, :class:`.time`, + or :class:`.datetime` instances to microsecond resolution. + + +.. class:: tzinfo + :noindex: + + An abstract base class for time zone information objects. These are used by the + :class:`.datetime` and :class:`.time` classes to provide a customizable notion of + time adjustment (for example, to account for time zone and/or daylight saving + time). + +.. class:: timezone + :noindex: + + A class that implements the :class:`tzinfo` abstract base class as a + fixed offset from the UTC. + + .. versionadded:: 3.2 + +Objects of these types are immutable. + +Subclass relationships:: + + object + timedelta + tzinfo + timezone + time + date + datetime + +Common Properties +^^^^^^^^^^^^^^^^^ + +The :class:`date`, :class:`.datetime`, :class:`.time`, and :class:`timezone` types +share these common features: + +- Objects of these types are immutable. +- Objects of these types are hashable, meaning that they can be used as + dictionary keys. +- Objects of these types support efficient pickling via the :mod:`pickle` module. + +Determining if an Object is Aware or Naive +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Objects of the :class:`date` type are always naive. + +An object of type :class:`.time` or :class:`.datetime` may be aware or naive. + +A :class:`.datetime` object *d* is aware if both of the following hold: + +1. ``d.tzinfo`` is not ``None`` +2. ``d.tzinfo.utcoffset(d)`` does not return ``None`` + +Otherwise, *d* is naive. + +A :class:`.time` object *t* is aware if both of the following hold: + +1. ``t.tzinfo`` is not ``None`` +2. ``t.tzinfo.utcoffset(None)`` does not return ``None``. + +Otherwise, *t* is naive. + +The distinction between aware and naive doesn't apply to :class:`timedelta` +objects. + +.. _datetime-timedelta: + +:class:`timedelta` Objects +-------------------------- + +A :class:`timedelta` object represents a duration, the difference between two +dates or times. + +.. class:: timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) + + All arguments are optional and default to ``0``. Arguments may be integers + or floats, and may be positive or negative. + + Only *days*, *seconds* and *microseconds* are stored internally. + Arguments are converted to those units: + + * A millisecond is converted to 1000 microseconds. + * A minute is converted to 60 seconds. + * An hour is converted to 3600 seconds. + * A week is converted to 7 days. + + and days, seconds and microseconds are then normalized so that the + representation is unique, with + + * ``0 <= microseconds < 1000000`` + * ``0 <= seconds < 3600*24`` (the number of seconds in one day) + * ``-999999999 <= days <= 999999999`` + + The following example illustrates how any arguments besides + *days*, *seconds* and *microseconds* are "merged" and normalized into those + three resulting attributes:: + + >>> from datetime import timedelta + >>> delta = timedelta( + ... days=50, + ... seconds=27, + ... microseconds=10, + ... milliseconds=29000, + ... minutes=5, + ... hours=8, + ... weeks=2 + ... ) + >>> # Only days, seconds, and microseconds remain + >>> delta + datetime.timedelta(days=64, seconds=29156, microseconds=10) + + If any argument is a float and there are fractional microseconds, + the fractional microseconds left over from all arguments are + combined and their sum is rounded to the nearest microsecond using + round-half-to-even tiebreaker. If no argument is a float, the + conversion and normalization processes are exact (no information is + lost). + + If the normalized value of days lies outside the indicated range, + :exc:`OverflowError` is raised. + + Note that normalization of negative values may be surprising at first. For + example:: + + >>> from datetime import timedelta + >>> d = timedelta(microseconds=-1) + >>> (d.days, d.seconds, d.microseconds) + (-1, 86399, 999999) + + +Class attributes: + +.. attribute:: timedelta.min + + The most negative :class:`timedelta` object, ``timedelta(-999999999)``. + + +.. attribute:: timedelta.max + + The most positive :class:`timedelta` object, ``timedelta(days=999999999, + hours=23, minutes=59, seconds=59, microseconds=999999)``. + + +.. attribute:: timedelta.resolution + + The smallest possible difference between non-equal :class:`timedelta` objects, + ``timedelta(microseconds=1)``. + +Note that, because of normalization, ``timedelta.max`` > ``-timedelta.min``. +``-timedelta.max`` is not representable as a :class:`timedelta` object. + +Instance attributes (read-only): + ++------------------+--------------------------------------------+ +| Attribute | Value | ++==================+============================================+ +| ``days`` | Between -999999999 and 999999999 inclusive | ++------------------+--------------------------------------------+ +| ``seconds`` | Between 0 and 86399 inclusive | ++------------------+--------------------------------------------+ +| ``microseconds`` | Between 0 and 999999 inclusive | ++------------------+--------------------------------------------+ + +Supported operations: + +.. XXX this table is too wide! + ++--------------------------------+-----------------------------------------------+ +| Operation | Result | ++================================+===============================================+ +| ``t1 = t2 + t3`` | Sum of *t2* and *t3*. Afterwards *t1*-*t2* == | +| | *t3* and *t1*-*t3* == *t2* are true. (1) | ++--------------------------------+-----------------------------------------------+ +| ``t1 = t2 - t3`` | Difference of *t2* and *t3*. Afterwards *t1* | +| | == *t2* - *t3* and *t2* == *t1* + *t3* are | +| | true. (1)(6) | ++--------------------------------+-----------------------------------------------+ +| ``t1 = t2 * i or t1 = i * t2`` | Delta multiplied by an integer. | +| | Afterwards *t1* // i == *t2* is true, | +| | provided ``i != 0``. | ++--------------------------------+-----------------------------------------------+ +| | In general, *t1* \* i == *t1* \* (i-1) + *t1* | +| | is true. (1) | ++--------------------------------+-----------------------------------------------+ +| ``t1 = t2 * f or t1 = f * t2`` | Delta multiplied by a float. The result is | +| | rounded to the nearest multiple of | +| | timedelta.resolution using round-half-to-even.| ++--------------------------------+-----------------------------------------------+ +| ``f = t2 / t3`` | Division (3) of overall duration *t2* by | +| | interval unit *t3*. Returns a :class:`float` | +| | object. | ++--------------------------------+-----------------------------------------------+ +| ``t1 = t2 / f or t1 = t2 / i`` | Delta divided by a float or an int. The result| +| | is rounded to the nearest multiple of | +| | timedelta.resolution using round-half-to-even.| ++--------------------------------+-----------------------------------------------+ +| ``t1 = t2 // i`` or | The floor is computed and the remainder (if | +| ``t1 = t2 // t3`` | any) is thrown away. In the second case, an | +| | integer is returned. (3) | ++--------------------------------+-----------------------------------------------+ +| ``t1 = t2 % t3`` | The remainder is computed as a | +| | :class:`timedelta` object. (3) | ++--------------------------------+-----------------------------------------------+ +| ``q, r = divmod(t1, t2)`` | Computes the quotient and the remainder: | +| | ``q = t1 // t2`` (3) and ``r = t1 % t2``. | +| | q is an integer and r is a :class:`timedelta` | +| | object. | ++--------------------------------+-----------------------------------------------+ +| ``+t1`` | Returns a :class:`timedelta` object with the | +| | same value. (2) | ++--------------------------------+-----------------------------------------------+ +| ``-t1`` | equivalent to | +| | :class:`timedelta`\ (-*t1.days*, | +| | -*t1.seconds*, -*t1.microseconds*), | +| | and to *t1*\* -1. (1)(4) | ++--------------------------------+-----------------------------------------------+ +| ``abs(t)`` | equivalent to +\ *t* when ``t.days >= 0``, | +| | and to -*t* when ``t.days < 0``. (2) | ++--------------------------------+-----------------------------------------------+ +| ``str(t)`` | Returns a string in the form | +| | ``[D day[s], ][H]H:MM:SS[.UUUUUU]``, where D | +| | is negative for negative ``t``. (5) | ++--------------------------------+-----------------------------------------------+ +| ``repr(t)`` | Returns a string representation of the | +| | :class:`timedelta` object as a constructor | +| | call with canonical attribute values. | ++--------------------------------+-----------------------------------------------+ + + +Notes: + +(1) + This is exact but may overflow. + +(2) + This is exact and cannot overflow. + +(3) + Division by 0 raises :exc:`ZeroDivisionError`. + +(4) + -*timedelta.max* is not representable as a :class:`timedelta` object. + +(5) + String representations of :class:`timedelta` objects are normalized + similarly to their internal representation. This leads to somewhat + unusual results for negative timedeltas. For example:: + + >>> timedelta(hours=-5) + datetime.timedelta(days=-1, seconds=68400) + >>> print(_) + -1 day, 19:00:00 + +(6) + The expression ``t2 - t3`` will always be equal to the expression ``t2 + (-t3)`` except + when t3 is equal to ``timedelta.max``; in that case the former will produce a result + while the latter will overflow. + +In addition to the operations listed above, :class:`timedelta` objects support +certain additions and subtractions with :class:`date` and :class:`.datetime` +objects (see below). + +.. versionchanged:: 3.2 + Floor division and true division of a :class:`timedelta` object by another + :class:`timedelta` object are now supported, as are remainder operations and + the :func:`divmod` function. True division and multiplication of a + :class:`timedelta` object by a :class:`float` object are now supported. + + +Comparisons of :class:`timedelta` objects are supported, with some caveats. + +The comparisons ``==`` or ``!=`` *always* return a :class:`bool`, no matter +the type of the compared object:: + + >>> from datetime import timedelta + >>> delta1 = timedelta(seconds=57) + >>> delta2 = timedelta(hours=25, seconds=2) + >>> delta2 != delta1 + True + >>> delta2 == 5 + False + +For all other comparisons (such as ``<`` and ``>``), when a :class:`timedelta` +object is compared to an object of a different type, :exc:`TypeError` +is raised:: + + >>> delta2 > delta1 + True + >>> delta2 > 5 + Traceback (most recent call last): + File "", line 1, in + TypeError: '>' not supported between instances of 'datetime.timedelta' and 'int' + +In Boolean contexts, a :class:`timedelta` object is +considered to be true if and only if it isn't equal to ``timedelta(0)``. + +Instance methods: + +.. method:: timedelta.total_seconds() + + Return the total number of seconds contained in the duration. Equivalent to + ``td / timedelta(seconds=1)``. For interval units other than seconds, use the + division form directly (e.g. ``td / timedelta(microseconds=1)``). + + Note that for very large time intervals (greater than 270 years on + most platforms) this method will lose microsecond accuracy. + + .. versionadded:: 3.2 + +Examples of usage: :class:`timedelta` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +An additional example of normalization:: + + >>> # Components of another_year add up to exactly 365 days + >>> from datetime import timedelta + >>> year = timedelta(days=365) + >>> another_year = timedelta(weeks=40, days=84, hours=23, + ... minutes=50, seconds=600) + >>> year == another_year + True + >>> year.total_seconds() + 31536000.0 + +Examples of :class:`timedelta` arithmetic:: + + >>> from datetime import timedelta + >>> year = timedelta(days=365) + >>> ten_years = 10 * year + >>> ten_years + datetime.timedelta(days=3650) + >>> ten_years.days // 365 + 10 + >>> nine_years = ten_years - year + >>> nine_years + datetime.timedelta(days=3285) + >>> three_years = nine_years // 3 + >>> three_years, three_years.days // 365 + (datetime.timedelta(days=1095), 3) + +.. _datetime-date: + +:class:`date` Objects +--------------------- + +A :class:`date` object represents a date (year, month and day) in an idealized +calendar, the current Gregorian calendar indefinitely extended in both +directions. + +January 1 of year 1 is called day number 1, January 2 of year 1 is +called day number 2, and so on. [#]_ + +.. class:: date(year, month, day) + + All arguments are required. Arguments must be integers, in the following + ranges: + + * ``MINYEAR <= year <= MAXYEAR`` + * ``1 <= month <= 12`` + * ``1 <= day <= number of days in the given month and year`` + + If an argument outside those ranges is given, :exc:`ValueError` is raised. + + +Other constructors, all class methods: + +.. classmethod:: date.today() + + Return the current local date. + + This is equivalent to ``date.fromtimestamp(time.time())``. + +.. classmethod:: date.fromtimestamp(timestamp) + + Return the local date corresponding to the POSIX timestamp, such as is + returned by :func:`time.time`. + + This may raise :exc:`OverflowError`, if the timestamp is out + of the range of values supported by the platform C :c:func:`localtime` + function, and :exc:`OSError` on :c:func:`localtime` failure. + It's common for this to be restricted to years from 1970 through 2038. Note + that on non-POSIX systems that include leap seconds in their notion of a + timestamp, leap seconds are ignored by :meth:`fromtimestamp`. + + .. versionchanged:: 3.3 + Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp + is out of the range of values supported by the platform C + :c:func:`localtime` function. Raise :exc:`OSError` instead of + :exc:`ValueError` on :c:func:`localtime` failure. + + +.. classmethod:: date.fromordinal(ordinal) + + Return the date corresponding to the proleptic Gregorian ordinal, where + January 1 of year 1 has ordinal 1. + + :exc:`ValueError` is raised unless ``1 <= ordinal <= + date.max.toordinal()``. For any date *d*, + ``date.fromordinal(d.toordinal()) == d``. + + +.. classmethod:: date.fromisoformat(date_string) + + Return a :class:`date` corresponding to a *date_string* given in the format + ``YYYY-MM-DD``:: + + >>> from datetime import date + >>> date.fromisoformat('2019-12-04') + datetime.date(2019, 12, 4) + + This is the inverse of :meth:`date.isoformat`. It only supports the format + ``YYYY-MM-DD``. + + .. versionadded:: 3.7 + + +.. classmethod:: date.fromisocalendar(year, week, day) + + Return a :class:`date` corresponding to the ISO calendar date specified by + year, week and day. This is the inverse of the function :meth:`date.isocalendar`. + + .. versionadded:: 3.8 + + +Class attributes: + +.. attribute:: date.min + + The earliest representable date, ``date(MINYEAR, 1, 1)``. + + +.. attribute:: date.max + + The latest representable date, ``date(MAXYEAR, 12, 31)``. + + +.. attribute:: date.resolution + + The smallest possible difference between non-equal date objects, + ``timedelta(days=1)``. + + +Instance attributes (read-only): + +.. attribute:: date.year + + Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive. + + +.. attribute:: date.month + + Between 1 and 12 inclusive. + + +.. attribute:: date.day + + Between 1 and the number of days in the given month of the given year. + + +Supported operations: + ++-------------------------------+----------------------------------------------+ +| Operation | Result | ++===============================+==============================================+ +| ``date2 = date1 + timedelta`` | *date2* is ``timedelta.days`` days removed | +| | from *date1*. (1) | ++-------------------------------+----------------------------------------------+ +| ``date2 = date1 - timedelta`` | Computes *date2* such that ``date2 + | +| | timedelta == date1``. (2) | ++-------------------------------+----------------------------------------------+ +| ``timedelta = date1 - date2`` | \(3) | ++-------------------------------+----------------------------------------------+ +| ``date1 < date2`` | *date1* is considered less than *date2* when | +| | *date1* precedes *date2* in time. (4) | ++-------------------------------+----------------------------------------------+ + +Notes: + +(1) + *date2* is moved forward in time if ``timedelta.days > 0``, or backward if + ``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``. + ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored. + :exc:`OverflowError` is raised if ``date2.year`` would be smaller than + :const:`MINYEAR` or larger than :const:`MAXYEAR`. + +(2) + ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored. + +(3) + This is exact, and cannot overflow. timedelta.seconds and + timedelta.microseconds are 0, and date2 + timedelta == date1 after. + +(4) + In other words, ``date1 < date2`` if and only if ``date1.toordinal() < + date2.toordinal()``. Date comparison raises :exc:`TypeError` if + the other comparand isn't also a :class:`date` object. However, + ``NotImplemented`` is returned instead if the other comparand has a + :meth:`timetuple` attribute. This hook gives other kinds of date objects a + chance at implementing mixed-type comparison. If not, when a :class:`date` + object is compared to an object of a different type, :exc:`TypeError` is raised + unless the comparison is ``==`` or ``!=``. The latter cases return + :const:`False` or :const:`True`, respectively. + +In Boolean contexts, all :class:`date` objects are considered to be true. + +Instance methods: + +.. method:: date.replace(year=self.year, month=self.month, day=self.day) + + Return a date with the same value, except for those parameters given new + values by whichever keyword arguments are specified. + + Example:: + + >>> from datetime import date + >>> d = date(2002, 12, 31) + >>> d.replace(day=26) + datetime.date(2002, 12, 26) + + +.. method:: date.timetuple() + + Return a :class:`time.struct_time` such as returned by :func:`time.localtime`. + + The hours, minutes and seconds are 0, and the DST flag is -1. + + ``d.timetuple()`` is equivalent to:: + + time.struct_time((d.year, d.month, d.day, 0, 0, 0, d.weekday(), yday, -1)) + + where ``yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` + is the day number within the current year starting with ``1`` for January 1st. + + +.. method:: date.toordinal() + + Return the proleptic Gregorian ordinal of the date, where January 1 of year 1 + has ordinal 1. For any :class:`date` object *d*, + ``date.fromordinal(d.toordinal()) == d``. + + +.. method:: date.weekday() + + Return the day of the week as an integer, where Monday is 0 and Sunday is 6. + For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also + :meth:`isoweekday`. + + +.. method:: date.isoweekday() + + Return the day of the week as an integer, where Monday is 1 and Sunday is 7. + For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also + :meth:`weekday`, :meth:`isocalendar`. + + +.. method:: date.isocalendar() + + Return a 3-tuple, (ISO year, ISO week number, ISO weekday). + + The ISO calendar is a widely used variant of the Gregorian calendar. [#]_ + + The ISO year consists of 52 or 53 full weeks, and where a week starts on a + Monday and ends on a Sunday. The first week of an ISO year is the first + (Gregorian) calendar week of a year containing a Thursday. This is called week + number 1, and the ISO year of that Thursday is the same as its Gregorian year. + + For example, 2004 begins on a Thursday, so the first week of ISO year 2004 + begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004:: + + >>> from datetime import date + >>> date(2003, 12, 29).isocalendar() + (2004, 1, 1) + >>> date(2004, 1, 4).isocalendar() + (2004, 1, 7) + +.. method:: date.isoformat() + + Return a string representing the date in ISO 8601 format, ``YYYY-MM-DD``:: + + >>> from datetime import date + >>> date(2002, 12, 4).isoformat() + '2002-12-04' + + This is the inverse of :meth:`date.fromisoformat`. + +.. method:: date.__str__() + + For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``. + + +.. method:: date.ctime() + + Return a string representing the date:: + + >>> from datetime import date + >>> date(2002, 12, 4).ctime() + 'Wed Dec 4 00:00:00 2002' + + ``d.ctime()`` is equivalent to:: + + time.ctime(time.mktime(d.timetuple())) + + on platforms where the native C + :c:func:`ctime` function (which :func:`time.ctime` invokes, but which + :meth:`date.ctime` does not invoke) conforms to the C standard. + + +.. method:: date.strftime(format) + + Return a string representing the date, controlled by an explicit format string. + Format codes referring to hours, minutes or seconds will see 0 values. For a + complete list of formatting directives, see + :ref:`strftime-strptime-behavior`. + + +.. method:: date.__format__(format) + + Same as :meth:`.date.strftime`. This makes it possible to specify a format + string for a :class:`.date` object in :ref:`formatted string + literals ` and when using :meth:`str.format`. For a + complete list of formatting directives, see + :ref:`strftime-strptime-behavior`. + +Examples of Usage: :class:`date` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Example of counting days to an event:: + + >>> import time + >>> from datetime import date + >>> today = date.today() + >>> today + datetime.date(2007, 12, 5) + >>> today == date.fromtimestamp(time.time()) + True + >>> my_birthday = date(today.year, 6, 24) + >>> if my_birthday < today: + ... my_birthday = my_birthday.replace(year=today.year + 1) + >>> my_birthday + datetime.date(2008, 6, 24) + >>> time_to_birthday = abs(my_birthday - today) + >>> time_to_birthday.days + 202 + +More examples of working with :class:`date`: + +.. doctest:: + + >>> from datetime import date + >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001 + >>> d + datetime.date(2002, 3, 11) + + >>> # Methods related to formatting string output + >>> d.isoformat() + '2002-03-11' + >>> d.strftime("%d/%m/%y") + '11/03/02' + >>> d.strftime("%A %d. %B %Y") + 'Monday 11. March 2002' + >>> d.ctime() + 'Mon Mar 11 00:00:00 2002' + >>> 'The {1} is {0:%d}, the {2} is {0:%B}.'.format(d, "day", "month") + 'The day is 11, the month is March.' + + >>> # Methods for to extracting 'components' under different calendars + >>> t = d.timetuple() + >>> for i in t: # doctest: +SKIP + ... print(i) + 2002 # year + 3 # month + 11 # day + 0 + 0 + 0 + 0 # weekday (0 = Monday) + 70 # 70th day in the year + -1 + >>> ic = d.isocalendar() + >>> for i in ic: # doctest: +SKIP + ... print(i) + 2002 # ISO year + 11 # ISO week number + 1 # ISO day number ( 1 = Monday ) + + >>> # A date object is immutable; all operations produce a new object + >>> d.replace(year=2005) + datetime.date(2005, 3, 11) + + +.. _datetime-datetime: + +:class:`.datetime` Objects +-------------------------- + +A :class:`.datetime` object is a single object containing all the information +from a :class:`date` object and a :class:`.time` object. + +Like a :class:`date` object, :class:`.datetime` assumes the current Gregorian +calendar extended in both directions; like a :class:`.time` object, +:class:`.datetime` assumes there are exactly 3600\*24 seconds in every day. + +Constructor: + +.. class:: datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0) + + The *year*, *month* and *day* arguments are required. *tzinfo* may be ``None``, or an + instance of a :class:`tzinfo` subclass. The remaining arguments must be integers + in the following ranges: + + * ``MINYEAR <= year <= MAXYEAR``, + * ``1 <= month <= 12``, + * ``1 <= day <= number of days in the given month and year``, + * ``0 <= hour < 24``, + * ``0 <= minute < 60``, + * ``0 <= second < 60``, + * ``0 <= microsecond < 1000000``, + * ``fold in [0, 1]``. + + If an argument outside those ranges is given, :exc:`ValueError` is raised. + + .. versionadded:: 3.6 + Added the ``fold`` argument. + +Other constructors, all class methods: + +.. classmethod:: datetime.today() + + Return the current local datetime, with :attr:`.tzinfo` ``None``. + + Equivalent to:: + + datetime.fromtimestamp(time.time()) + + See also :meth:`now`, :meth:`fromtimestamp`. + + This method is functionally equivalent to :meth:`now`, but without a + ``tz`` parameter. + +.. classmethod:: datetime.now(tz=None) + + Return the current local date and time. + + If optional argument *tz* is ``None`` + or not specified, this is like :meth:`today`, but, if possible, supplies more + precision than can be gotten from going through a :func:`time.time` timestamp + (for example, this may be possible on platforms supplying the C + :c:func:`gettimeofday` function). + + If *tz* is not ``None``, it must be an instance of a :class:`tzinfo` subclass, + and the current date and time are converted to *tz*’s time zone. + + This function is preferred over :meth:`today` and :meth:`utcnow`. + + +.. classmethod:: datetime.utcnow() + + Return the current UTC date and time, with :attr:`.tzinfo` ``None``. + + This is like :meth:`now`, but returns the current UTC date and time, as a naive + :class:`.datetime` object. An aware current UTC datetime can be obtained by + calling ``datetime.now(timezone.utc)``. See also :meth:`now`. + + .. warning:: + + Because naive ``datetime`` objects are treated by many ``datetime`` methods + as local times, it is preferred to use aware datetimes to represent times + in UTC. As such, the recommended way to create an object representing the + current time in UTC is by calling ``datetime.now(timezone.utc)``. + + +.. classmethod:: datetime.fromtimestamp(timestamp, tz=None) + + Return the local date and time corresponding to the POSIX timestamp, such as is + returned by :func:`time.time`. If optional argument *tz* is ``None`` or not + specified, the timestamp is converted to the platform's local date and time, and + the returned :class:`.datetime` object is naive. + + If *tz* is not ``None``, it must be an instance of a :class:`tzinfo` subclass, and the + timestamp is converted to *tz*’s time zone. + + :meth:`fromtimestamp` may raise :exc:`OverflowError`, if the timestamp is out of + the range of values supported by the platform C :c:func:`localtime` or + :c:func:`gmtime` functions, and :exc:`OSError` on :c:func:`localtime` or + :c:func:`gmtime` failure. + It's common for this to be restricted to years in + 1970 through 2038. Note that on non-POSIX systems that include leap seconds in + their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`, + and then it's possible to have two timestamps differing by a second that yield + identical :class:`.datetime` objects. This method is preferred over + :meth:`utcfromtimestamp`. + + .. versionchanged:: 3.3 + Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp + is out of the range of values supported by the platform C + :c:func:`localtime` or :c:func:`gmtime` functions. Raise :exc:`OSError` + instead of :exc:`ValueError` on :c:func:`localtime` or :c:func:`gmtime` + failure. + + .. versionchanged:: 3.6 + :meth:`fromtimestamp` may return instances with :attr:`.fold` set to 1. + +.. classmethod:: datetime.utcfromtimestamp(timestamp) + + Return the UTC :class:`.datetime` corresponding to the POSIX timestamp, with + :attr:`.tzinfo` ``None``. (The resulting object is naive.) + + This may raise :exc:`OverflowError`, if the timestamp is + out of the range of values supported by the platform C :c:func:`gmtime` function, + and :exc:`OSError` on :c:func:`gmtime` failure. + It's common for this to be restricted to years in 1970 through 2038. + + To get an aware :class:`.datetime` object, call :meth:`fromtimestamp`:: + + datetime.fromtimestamp(timestamp, timezone.utc) + + On the POSIX compliant platforms, it is equivalent to the following + expression:: + + datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=timestamp) + + except the latter formula always supports the full years range: between + :const:`MINYEAR` and :const:`MAXYEAR` inclusive. + + .. warning:: + + Because naive ``datetime`` objects are treated by many ``datetime`` methods + as local times, it is preferred to use aware datetimes to represent times + in UTC. As such, the recommended way to create an object representing a + specific timestamp in UTC is by calling + ``datetime.fromtimestamp(timestamp, tz=timezone.utc)``. + + .. versionchanged:: 3.3 + Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp + is out of the range of values supported by the platform C + :c:func:`gmtime` function. Raise :exc:`OSError` instead of + :exc:`ValueError` on :c:func:`gmtime` failure. + + +.. classmethod:: datetime.fromordinal(ordinal) + + Return the :class:`.datetime` corresponding to the proleptic Gregorian ordinal, + where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 + <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and + microsecond of the result are all 0, and :attr:`.tzinfo` is ``None``. + + +.. classmethod:: datetime.combine(date, time, tzinfo=self.tzinfo) + + Return a new :class:`.datetime` object whose date components are equal to the + given :class:`date` object's, and whose time components + are equal to the given :class:`.time` object's. If the *tzinfo* + argument is provided, its value is used to set the :attr:`.tzinfo` attribute + of the result, otherwise the :attr:`~.time.tzinfo` attribute of the *time* argument + is used. + + For any :class:`.datetime` object *d*, + ``d == datetime.combine(d.date(), d.time(), d.tzinfo)``. If date is a + :class:`.datetime` object, its time components and :attr:`.tzinfo` attributes + are ignored. + + .. versionchanged:: 3.6 + Added the *tzinfo* argument. + + +.. classmethod:: datetime.fromisoformat(date_string) + + Return a :class:`.datetime` corresponding to a *date_string* in one of the + formats emitted by :meth:`date.isoformat` and :meth:`datetime.isoformat`. + + Specifically, this function supports strings in the format: + + .. code-block:: none + + YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]] + + where ``*`` can match any single character. + + .. caution:: + + This does *not* support parsing arbitrary ISO 8601 strings - it is only intended + as the inverse operation of :meth:`datetime.isoformat`. A more full-featured + ISO 8601 parser, ``dateutil.parser.isoparse`` is available in the third-party package + `dateutil `__. + + Examples:: + + >>> from datetime import datetime + >>> datetime.fromisoformat('2011-11-04') + datetime.datetime(2011, 11, 4, 0, 0) + >>> datetime.fromisoformat('2011-11-04T00:05:23') + datetime.datetime(2011, 11, 4, 0, 5, 23) + >>> datetime.fromisoformat('2011-11-04 00:05:23.283') + datetime.datetime(2011, 11, 4, 0, 5, 23, 283000) + >>> datetime.fromisoformat('2011-11-04 00:05:23.283+00:00') + datetime.datetime(2011, 11, 4, 0, 5, 23, 283000, tzinfo=datetime.timezone.utc) + >>> datetime.fromisoformat('2011-11-04T00:05:23+04:00') # doctest: +NORMALIZE_WHITESPACE + datetime.datetime(2011, 11, 4, 0, 5, 23, + tzinfo=datetime.timezone(datetime.timedelta(seconds=14400))) + + .. versionadded:: 3.7 + +.. classmethod:: datetime.fromisocalendar(year, week, day) + + Return a :class:`.datetime` corresponding to the ISO calendar date specified + by year, week and day. The non-date components of the datetime are populated + with their normal default values. This is the inverse of the function + :meth:`datetime.isocalendar`. + + .. versionadded:: 3.8 + +.. classmethod:: datetime.strptime(date_string, format) + + Return a :class:`.datetime` corresponding to *date_string*, parsed according to + *format*. + + This is equivalent to:: + + datetime(*(time.strptime(date_string, format)[0:6])) + + :exc:`ValueError` is raised if the date_string and format + can't be parsed by :func:`time.strptime` or if it returns a value which isn't a + time tuple. For a complete list of formatting directives, see + :ref:`strftime-strptime-behavior`. + + + +Class attributes: + +.. attribute:: datetime.min + + The earliest representable :class:`.datetime`, ``datetime(MINYEAR, 1, 1, + tzinfo=None)``. + + +.. attribute:: datetime.max + + The latest representable :class:`.datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59, + 59, 999999, tzinfo=None)``. + + +.. attribute:: datetime.resolution + + The smallest possible difference between non-equal :class:`.datetime` objects, + ``timedelta(microseconds=1)``. + + +Instance attributes (read-only): + +.. attribute:: datetime.year + + Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive. + + +.. attribute:: datetime.month + + Between 1 and 12 inclusive. + + +.. attribute:: datetime.day + + Between 1 and the number of days in the given month of the given year. + + +.. attribute:: datetime.hour + + In ``range(24)``. + + +.. attribute:: datetime.minute + + In ``range(60)``. + + +.. attribute:: datetime.second + + In ``range(60)``. + + +.. attribute:: datetime.microsecond + + In ``range(1000000)``. + + +.. attribute:: datetime.tzinfo + + The object passed as the *tzinfo* argument to the :class:`.datetime` constructor, + or ``None`` if none was passed. + + +.. attribute:: datetime.fold + + In ``[0, 1]``. Used to disambiguate wall times during a repeated interval. (A + repeated interval occurs when clocks are rolled back at the end of daylight saving + time or when the UTC offset for the current zone is decreased for political reasons.) + The value 0 (1) represents the earlier (later) of the two moments with the same wall + time representation. + + .. versionadded:: 3.6 + +Supported operations: + ++---------------------------------------+--------------------------------+ +| Operation | Result | ++=======================================+================================+ +| ``datetime2 = datetime1 + timedelta`` | \(1) | ++---------------------------------------+--------------------------------+ +| ``datetime2 = datetime1 - timedelta`` | \(2) | ++---------------------------------------+--------------------------------+ +| ``timedelta = datetime1 - datetime2`` | \(3) | ++---------------------------------------+--------------------------------+ +| ``datetime1 < datetime2`` | Compares :class:`.datetime` to | +| | :class:`.datetime`. (4) | ++---------------------------------------+--------------------------------+ + +(1) + datetime2 is a duration of timedelta removed from datetime1, moving forward in + time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The + result has the same :attr:`~.datetime.tzinfo` attribute as the input datetime, and + datetime2 - datetime1 == timedelta after. :exc:`OverflowError` is raised if + datetime2.year would be smaller than :const:`MINYEAR` or larger than + :const:`MAXYEAR`. Note that no time zone adjustments are done even if the + input is an aware object. + +(2) + Computes the datetime2 such that datetime2 + timedelta == datetime1. As for + addition, the result has the same :attr:`~.datetime.tzinfo` attribute as the input + datetime, and no time zone adjustments are done even if the input is aware. + +(3) + Subtraction of a :class:`.datetime` from a :class:`.datetime` is defined only if + both operands are naive, or if both are aware. If one is aware and the other is + naive, :exc:`TypeError` is raised. + + If both are naive, or both are aware and have the same :attr:`~.datetime.tzinfo` attribute, + the :attr:`~.datetime.tzinfo` attributes are ignored, and the result is a :class:`timedelta` + object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments + are done in this case. + + If both are aware and have different :attr:`~.datetime.tzinfo` attributes, ``a-b`` acts + as if *a* and *b* were first converted to naive UTC datetimes first. The + result is ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) + - b.utcoffset())`` except that the implementation never overflows. + +(4) + *datetime1* is considered less than *datetime2* when *datetime1* precedes + *datetime2* in time. + + If one comparand is naive and the other is aware, :exc:`TypeError` + is raised if an order comparison is attempted. For equality + comparisons, naive instances are never equal to aware instances. + + If both comparands are aware, and have the same :attr:`~.datetime.tzinfo` attribute, the + common :attr:`~.datetime.tzinfo` attribute is ignored and the base datetimes are + compared. If both comparands are aware and have different :attr:`~.datetime.tzinfo` + attributes, the comparands are first adjusted by subtracting their UTC + offsets (obtained from ``self.utcoffset()``). + + .. versionchanged:: 3.3 + Equality comparisons between aware and naive :class:`.datetime` + instances don't raise :exc:`TypeError`. + + .. note:: + + In order to stop comparison from falling back to the default scheme of comparing + object addresses, datetime comparison normally raises :exc:`TypeError` if the + other comparand isn't also a :class:`.datetime` object. However, + ``NotImplemented`` is returned instead if the other comparand has a + :meth:`timetuple` attribute. This hook gives other kinds of date objects a + chance at implementing mixed-type comparison. If not, when a :class:`.datetime` + object is compared to an object of a different type, :exc:`TypeError` is raised + unless the comparison is ``==`` or ``!=``. The latter cases return + :const:`False` or :const:`True`, respectively. + +Instance methods: + +.. method:: datetime.date() + + Return :class:`date` object with same year, month and day. + + +.. method:: datetime.time() + + Return :class:`.time` object with same hour, minute, second, microsecond and fold. + :attr:`.tzinfo` is ``None``. See also method :meth:`timetz`. + + .. versionchanged:: 3.6 + The fold value is copied to the returned :class:`.time` object. + + +.. method:: datetime.timetz() + + Return :class:`.time` object with same hour, minute, second, microsecond, fold, and + tzinfo attributes. See also method :meth:`time`. + + .. versionchanged:: 3.6 + The fold value is copied to the returned :class:`.time` object. + + +.. method:: datetime.replace(year=self.year, month=self.month, day=self.day, \ + hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, \ + tzinfo=self.tzinfo, * fold=0) + + Return a datetime with the same attributes, except for those attributes given + new values by whichever keyword arguments are specified. Note that + ``tzinfo=None`` can be specified to create a naive datetime from an aware + datetime with no conversion of date and time data. + + .. versionadded:: 3.6 + Added the ``fold`` argument. + + +.. method:: datetime.astimezone(tz=None) + + Return a :class:`.datetime` object with new :attr:`.tzinfo` attribute *tz*, + adjusting the date and time data so the result is the same UTC time as + *self*, but in *tz*'s local time. + + If provided, *tz* must be an instance of a :class:`tzinfo` subclass, and its + :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. If *self* + is naive, it is presumed to represent time in the system timezone. + + If called without arguments (or with ``tz=None``) the system local + timezone is assumed for the target timezone. The ``.tzinfo`` attribute of the converted + datetime instance will be set to an instance of :class:`timezone` + with the zone name and offset obtained from the OS. + + If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no + adjustment of date or time data is performed. Else the result is local + time in the timezone *tz*, representing the same UTC time as *self*: after + ``astz = dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will have + the same date and time data as ``dt - dt.utcoffset()``. + + If you merely want to attach a time zone object *tz* to a datetime *dt* without + adjustment of date and time data, use ``dt.replace(tzinfo=tz)``. If you + merely want to remove the time zone object from an aware datetime *dt* without + conversion of date and time data, use ``dt.replace(tzinfo=None)``. + + Note that the default :meth:`tzinfo.fromutc` method can be overridden in a + :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`. + Ignoring error cases, :meth:`astimezone` acts like:: + + def astimezone(self, tz): + if self.tzinfo is tz: + return self + # Convert self to UTC, and attach the new time zone object. + utc = (self - self.utcoffset()).replace(tzinfo=tz) + # Convert from UTC to tz's local time. + return tz.fromutc(utc) + + .. versionchanged:: 3.3 + *tz* now can be omitted. + + .. versionchanged:: 3.6 + The :meth:`astimezone` method can now be called on naive instances that + are presumed to represent system local time. + + +.. method:: datetime.utcoffset() + + If :attr:`.tzinfo` is ``None``, returns ``None``, else returns + ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't + return ``None`` or a :class:`timedelta` object with magnitude less than one day. + + .. versionchanged:: 3.7 + The UTC offset is not restricted to a whole number of minutes. + + +.. method:: datetime.dst() + + If :attr:`.tzinfo` is ``None``, returns ``None``, else returns + ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return + ``None`` or a :class:`timedelta` object with magnitude less than one day. + + .. versionchanged:: 3.7 + The DST offset is not restricted to a whole number of minutes. + + +.. method:: datetime.tzname() + + If :attr:`.tzinfo` is ``None``, returns ``None``, else returns + ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return + ``None`` or a string object, + + +.. method:: datetime.timetuple() + + Return a :class:`time.struct_time` such as returned by :func:`time.localtime`. + + ``d.timetuple()`` is equivalent to:: + + time.struct_time((d.year, d.month, d.day, + d.hour, d.minute, d.second, + d.weekday(), yday, dst)) + + where ``yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` + is the day number within the current year starting with ``1`` for January + 1st. The :attr:`tm_isdst` flag of the result is set according to the + :meth:`dst` method: :attr:`.tzinfo` is ``None`` or :meth:`dst` returns + ``None``, :attr:`tm_isdst` is set to ``-1``; else if :meth:`dst` returns a + non-zero value, :attr:`tm_isdst` is set to ``1``; else :attr:`tm_isdst` is + set to ``0``. + + +.. method:: datetime.utctimetuple() + + If :class:`.datetime` instance *d* is naive, this is the same as + ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what + ``d.dst()`` returns. DST is never in effect for a UTC time. + + If *d* is aware, *d* is normalized to UTC time, by subtracting + ``d.utcoffset()``, and a :class:`time.struct_time` for the + normalized time is returned. :attr:`tm_isdst` is forced to 0. Note + that an :exc:`OverflowError` may be raised if *d*.year was + ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year + boundary. + + .. warning:: + + Because naive ``datetime`` objects are treated by many ``datetime`` methods + as local times, it is preferred to use aware datetimes to represent times + in UTC; as a result, using ``utcfromtimetuple`` may give misleading + results. If you have a naive ``datetime`` representing UTC, use + ``datetime.replace(tzinfo=timezone.utc)`` to make it aware, at which point + you can use :meth:`.datetime.timetuple`. + +.. method:: datetime.toordinal() + + Return the proleptic Gregorian ordinal of the date. The same as + ``self.date().toordinal()``. + +.. method:: datetime.timestamp() + + Return POSIX timestamp corresponding to the :class:`.datetime` + instance. The return value is a :class:`float` similar to that + returned by :func:`time.time`. + + Naive :class:`.datetime` instances are assumed to represent local + time and this method relies on the platform C :c:func:`mktime` + function to perform the conversion. Since :class:`.datetime` + supports wider range of values than :c:func:`mktime` on many + platforms, this method may raise :exc:`OverflowError` for times far + in the past or far in the future. + + For aware :class:`.datetime` instances, the return value is computed + as:: + + (dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds() + + .. versionadded:: 3.3 + + .. versionchanged:: 3.6 + The :meth:`timestamp` method uses the :attr:`.fold` attribute to + disambiguate the times during a repeated interval. + + .. note:: + + There is no method to obtain the POSIX timestamp directly from a + naive :class:`.datetime` instance representing UTC time. If your + application uses this convention and your system timezone is not + set to UTC, you can obtain the POSIX timestamp by supplying + ``tzinfo=timezone.utc``:: + + timestamp = dt.replace(tzinfo=timezone.utc).timestamp() + + or by calculating the timestamp directly:: + + timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1) + +.. method:: datetime.weekday() + + Return the day of the week as an integer, where Monday is 0 and Sunday is 6. + The same as ``self.date().weekday()``. See also :meth:`isoweekday`. + + +.. method:: datetime.isoweekday() + + Return the day of the week as an integer, where Monday is 1 and Sunday is 7. + The same as ``self.date().isoweekday()``. See also :meth:`weekday`, + :meth:`isocalendar`. + + +.. method:: datetime.isocalendar() + + Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as + ``self.date().isocalendar()``. + + +.. method:: datetime.isoformat(sep='T', timespec='auto') + + Return a string representing the date and time in ISO 8601 format: + + - ``YYYY-MM-DDTHH:MM:SS.ffffff``, if :attr:`microsecond` is not 0 + - ``YYYY-MM-DDTHH:MM:SS``, if :attr:`microsecond` is 0 + + If :meth:`utcoffset` does not return ``None``, a string is + appended, giving the UTC offset: + + - ``YYYY-MM-DDTHH:MM:SS.ffffff+HH:MM[:SS[.ffffff]]``, if :attr:`microsecond` + is not 0 + - ``YYYY-MM-DDTHH:MM:SS+HH:MM[:SS[.ffffff]]``, if :attr:`microsecond` is 0 + + Examples:: + + >>> from datetime import datetime, timezone + >>> datetime(2019, 5, 18, 15, 17, 8, 132263).isoformat() + '2019-05-18T15:17:08.132263' + >>> datetime(2019, 5, 18, 15, 17, tzinfo=timezone.utc).isoformat() + '2019-05-18T15:17:00+00:00' + + The optional argument *sep* (default ``'T'``) is a one-character separator, + placed between the date and time portions of the result. For example:: + + >>> from datetime import tzinfo, timedelta, datetime + >>> class TZ(tzinfo): + ... """A time zone with an arbitrary, constant -06:39 offset.""" + ... def utcoffset(self, dt): + ... return timedelta(hours=-6, minutes=-39) + ... + >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ') + '2002-12-25 00:00:00-06:39' + >>> datetime(2009, 11, 27, microsecond=100, tzinfo=TZ()).isoformat() + '2009-11-27T00:00:00.000100-06:39' + + The optional argument *timespec* specifies the number of additional + components of the time to include (the default is ``'auto'``). + It can be one of the following: + + - ``'auto'``: Same as ``'seconds'`` if :attr:`microsecond` is 0, + same as ``'microseconds'`` otherwise. + - ``'hours'``: Include the :attr:`hour` in the two-digit ``HH`` format. + - ``'minutes'``: Include :attr:`hour` and :attr:`minute` in ``HH:MM`` format. + - ``'seconds'``: Include :attr:`hour`, :attr:`minute`, and :attr:`second` + in ``HH:MM:SS`` format. + - ``'milliseconds'``: Include full time, but truncate fractional second + part to milliseconds. ``HH:MM:SS.sss`` format. + - ``'microseconds'``: Include full time in ``HH:MM:SS.ffffff`` format. + + .. note:: + + Excluded time components are truncated, not rounded. + + :exc:`ValueError` will be raised on an invalid *timespec* argument:: + + + >>> from datetime import datetime + >>> datetime.now().isoformat(timespec='minutes') # doctest: +SKIP + '2002-12-25T00:00' + >>> dt = datetime(2015, 1, 1, 12, 30, 59, 0) + >>> dt.isoformat(timespec='microseconds') + '2015-01-01T12:30:59.000000' + + .. versionadded:: 3.6 + Added the *timespec* argument. + + +.. method:: datetime.__str__() + + For a :class:`.datetime` instance *d*, ``str(d)`` is equivalent to + ``d.isoformat(' ')``. + + +.. method:: datetime.ctime() + + Return a string representing the date and time:: + + >>> from datetime import datetime + >>> datetime(2002, 12, 4, 20, 30, 40).ctime() + 'Wed Dec 4 20:30:40 2002' + + The output string will *not* include time zone information, regardless + of whether the input is aware or naive. + + ``d.ctime()`` is equivalent to:: + + time.ctime(time.mktime(d.timetuple())) + + on platforms where the native C :c:func:`ctime` function + (which :func:`time.ctime` invokes, but which + :meth:`datetime.ctime` does not invoke) conforms to the C standard. + +.. method:: datetime.strftime(format) + + Return a string representing the date and time, controlled by an explicit format + string. For a complete list of formatting directives, see + :ref:`strftime-strptime-behavior`. + + +.. method:: datetime.__format__(format) + + Same as :meth:`.datetime.strftime`. This makes it possible to specify a format + string for a :class:`.datetime` object in :ref:`formatted string + literals ` and when using :meth:`str.format`. For a + complete list of formatting directives, see + :ref:`strftime-strptime-behavior`. + +Examples of Usage: :class:`.datetime` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Examples of working with :class:`~datetime.datetime` objects: + +.. doctest:: + + >>> from datetime import datetime, date, time, timezone + + >>> # Using datetime.combine() + >>> d = date(2005, 7, 14) + >>> t = time(12, 30) + >>> datetime.combine(d, t) + datetime.datetime(2005, 7, 14, 12, 30) + + >>> # Using datetime.now() + >>> datetime.now() # doctest: +SKIP + datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1 + >>> datetime.now(timezone.utc) # doctest: +SKIP + datetime.datetime(2007, 12, 6, 15, 29, 43, 79060, tzinfo=datetime.timezone.utc) + + >>> # Using datetime.strptime() + >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M") + >>> dt + datetime.datetime(2006, 11, 21, 16, 30) + + >>> # Using datetime.timetuple() to get tuple of all attributes + >>> tt = dt.timetuple() + >>> for it in tt: # doctest: +SKIP + ... print(it) + ... + 2006 # year + 11 # month + 21 # day + 16 # hour + 30 # minute + 0 # second + 1 # weekday (0 = Monday) + 325 # number of days since 1st January + -1 # dst - method tzinfo.dst() returned None + + >>> # Date in ISO format + >>> ic = dt.isocalendar() + >>> for it in ic: # doctest: +SKIP + ... print(it) + ... + 2006 # ISO year + 47 # ISO week + 2 # ISO weekday + + >>> # Formatting a datetime + >>> dt.strftime("%A, %d. %B %Y %I:%M%p") + 'Tuesday, 21. November 2006 04:30PM' + >>> 'The {1} is {0:%d}, the {2} is {0:%B}, the {3} is {0:%I:%M%p}.'.format(dt, "day", "month", "time") + 'The day is 21, the month is November, the time is 04:30PM.' + +The example below defines a :class:`tzinfo` subclass capturing time zone +information for Kabul, Afghanistan, which used +4 UTC until 1945 +and then +4:30 UTC thereafter:: + + from datetime import timedelta, datetime, tzinfo, timezone + + class KabulTz(tzinfo): + # Kabul used +4 until 1945, when they moved to +4:30 + UTC_MOVE_DATE = datetime(1944, 12, 31, 20, tzinfo=timezone.utc) + + def utcoffset(self, dt): + if dt.year < 1945: + return timedelta(hours=4) + elif (1945, 1, 1, 0, 0) <= dt.timetuple()[:5] < (1945, 1, 1, 0, 30): + # An ambiguous ("imaginary") half-hour range representing + # a 'fold' in time due to the shift from +4 to +4:30. + # If dt falls in the imaginary range, use fold to decide how + # to resolve. See PEP495. + return timedelta(hours=4, minutes=(30 if dt.fold else 0)) + else: + return timedelta(hours=4, minutes=30) + + def fromutc(self, dt): + # Follow same validations as in datetime.tzinfo + if not isinstance(dt, datetime): + raise TypeError("fromutc() requires a datetime argument") + if dt.tzinfo is not self: + raise ValueError("dt.tzinfo is not self") + + # A custom implementation is required for fromutc as + # the input to this function is a datetime with utc values + # but with a tzinfo set to self. + # See datetime.astimezone or fromtimestamp. + if dt.replace(tzinfo=timezone.utc) >= self.UTC_MOVE_DATE: + return dt + timedelta(hours=4, minutes=30) + else: + return dt + timedelta(hours=4) + + def dst(self, dt): + # Kabul does not observe daylight saving time. + return timedelta(0) + + def tzname(self, dt): + if dt >= self.UTC_MOVE_DATE: + return "+04:30" + return "+04" + +Usage of ``KabulTz`` from above:: + + >>> tz1 = KabulTz() + + >>> # Datetime before the change + >>> dt1 = datetime(1900, 11, 21, 16, 30, tzinfo=tz1) + >>> print(dt1.utcoffset()) + 4:00:00 + + >>> # Datetime after the change + >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=tz1) + >>> print(dt2.utcoffset()) + 4:30:00 + + >>> # Convert datetime to another time zone + >>> dt3 = dt2.astimezone(timezone.utc) + >>> dt3 + datetime.datetime(2006, 6, 14, 8, 30, tzinfo=datetime.timezone.utc) + >>> dt2 + datetime.datetime(2006, 6, 14, 13, 0, tzinfo=KabulTz()) + >>> dt2 == dt3 + True + +.. _datetime-time: + +:class:`.time` Objects +---------------------- + +A :class:`time` object represents a (local) time of day, independent of any particular +day, and subject to adjustment via a :class:`tzinfo` object. + +.. class:: time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0) + + All arguments are optional. *tzinfo* may be ``None``, or an instance of a + :class:`tzinfo` subclass. The remaining arguments must be integers in the + following ranges: + + * ``0 <= hour < 24``, + * ``0 <= minute < 60``, + * ``0 <= second < 60``, + * ``0 <= microsecond < 1000000``, + * ``fold in [0, 1]``. + + If an argument outside those ranges is given, :exc:`ValueError` is raised. All + default to ``0`` except *tzinfo*, which defaults to :const:`None`. + +Class attributes: + + +.. attribute:: time.min + + The earliest representable :class:`.time`, ``time(0, 0, 0, 0)``. + + +.. attribute:: time.max + + The latest representable :class:`.time`, ``time(23, 59, 59, 999999)``. + + +.. attribute:: time.resolution + + The smallest possible difference between non-equal :class:`.time` objects, + ``timedelta(microseconds=1)``, although note that arithmetic on + :class:`.time` objects is not supported. + + +Instance attributes (read-only): + +.. attribute:: time.hour + + In ``range(24)``. + + +.. attribute:: time.minute + + In ``range(60)``. + + +.. attribute:: time.second + + In ``range(60)``. + + +.. attribute:: time.microsecond + + In ``range(1000000)``. + + +.. attribute:: time.tzinfo + + The object passed as the tzinfo argument to the :class:`.time` constructor, or + ``None`` if none was passed. + + +.. attribute:: time.fold + + In ``[0, 1]``. Used to disambiguate wall times during a repeated interval. (A + repeated interval occurs when clocks are rolled back at the end of daylight saving + time or when the UTC offset for the current zone is decreased for political reasons.) + The value 0 (1) represents the earlier (later) of the two moments with the same wall + time representation. + + .. versionadded:: 3.6 + +:class:`.time` objects support comparison of :class:`.time` to :class:`.time`, +where *a* is considered less +than *b* when *a* precedes *b* in time. If one comparand is naive and the other +is aware, :exc:`TypeError` is raised if an order comparison is attempted. For equality +comparisons, naive instances are never equal to aware instances. + +If both comparands are aware, and have +the same :attr:`~time.tzinfo` attribute, the common :attr:`~time.tzinfo` attribute is +ignored and the base times are compared. If both comparands are aware and +have different :attr:`~time.tzinfo` attributes, the comparands are first adjusted by +subtracting their UTC offsets (obtained from ``self.utcoffset()``). In order +to stop mixed-type comparisons from falling back to the default comparison by +object address, when a :class:`.time` object is compared to an object of a +different type, :exc:`TypeError` is raised unless the comparison is ``==`` or +``!=``. The latter cases return :const:`False` or :const:`True`, respectively. + +.. versionchanged:: 3.3 + Equality comparisons between aware and naive :class:`~datetime.time` instances + don't raise :exc:`TypeError`. + +In Boolean contexts, a :class:`.time` object is always considered to be true. + +.. versionchanged:: 3.5 + Before Python 3.5, a :class:`.time` object was considered to be false if it + represented midnight in UTC. This behavior was considered obscure and + error-prone and has been removed in Python 3.5. See :issue:`13936` for full + details. + + +Other constructor: + +.. classmethod:: time.fromisoformat(time_string) + + Return a :class:`.time` corresponding to a *time_string* in one of the + formats emitted by :meth:`time.isoformat`. Specifically, this function supports + strings in the format: + + .. code-block:: none + + HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]] + + .. caution:: + + This does *not* support parsing arbitrary ISO 8601 strings. It is only + intended as the inverse operation of :meth:`time.isoformat`. + + Examples:: + + >>> from datetime import time + >>> time.fromisoformat('04:23:01') + datetime.time(4, 23, 1) + >>> time.fromisoformat('04:23:01.000384') + datetime.time(4, 23, 1, 384) + >>> time.fromisoformat('04:23:01+04:00') + datetime.time(4, 23, 1, tzinfo=datetime.timezone(datetime.timedelta(seconds=14400))) + + .. versionadded:: 3.7 + + +Instance methods: + +.. method:: time.replace(hour=self.hour, minute=self.minute, second=self.second, \ + microsecond=self.microsecond, tzinfo=self.tzinfo, * fold=0) + + Return a :class:`.time` with the same value, except for those attributes given + new values by whichever keyword arguments are specified. Note that + ``tzinfo=None`` can be specified to create a naive :class:`.time` from an + aware :class:`.time`, without conversion of the time data. + + .. versionadded:: 3.6 + Added the ``fold`` argument. + + +.. method:: time.isoformat(timespec='auto') + + Return a string representing the time in ISO 8601 format, one of: + + - ``HH:MM:SS.ffffff``, if :attr:`microsecond` is not 0 + - ``HH:MM:SS``, if :attr:`microsecond` is 0 + - ``HH:MM:SS.ffffff+HH:MM[:SS[.ffffff]]``, if :meth:`utcoffset` does not return ``None`` + - ``HH:MM:SS+HH:MM[:SS[.ffffff]]``, if :attr:`microsecond` is 0 and :meth:`utcoffset` does not return ``None`` + + The optional argument *timespec* specifies the number of additional + components of the time to include (the default is ``'auto'``). + It can be one of the following: + + - ``'auto'``: Same as ``'seconds'`` if :attr:`microsecond` is 0, + same as ``'microseconds'`` otherwise. + - ``'hours'``: Include the :attr:`hour` in the two-digit ``HH`` format. + - ``'minutes'``: Include :attr:`hour` and :attr:`minute` in ``HH:MM`` format. + - ``'seconds'``: Include :attr:`hour`, :attr:`minute`, and :attr:`second` + in ``HH:MM:SS`` format. + - ``'milliseconds'``: Include full time, but truncate fractional second + part to milliseconds. ``HH:MM:SS.sss`` format. + - ``'microseconds'``: Include full time in ``HH:MM:SS.ffffff`` format. + + .. note:: + + Excluded time components are truncated, not rounded. + + :exc:`ValueError` will be raised on an invalid *timespec* argument. + + Example:: + + >>> from datetime import time + >>> time(hour=12, minute=34, second=56, microsecond=123456).isoformat(timespec='minutes') + '12:34' + >>> dt = time(hour=12, minute=34, second=56, microsecond=0) + >>> dt.isoformat(timespec='microseconds') + '12:34:56.000000' + >>> dt.isoformat(timespec='auto') + '12:34:56' + + .. versionadded:: 3.6 + Added the *timespec* argument. + + +.. method:: time.__str__() + + For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``. + + +.. method:: time.strftime(format) + + Return a string representing the time, controlled by an explicit format + string. For a complete list of formatting directives, see + :ref:`strftime-strptime-behavior`. + + +.. method:: time.__format__(format) + + Same as :meth:`.time.strftime`. This makes it possible to specify a format string + for a :class:`.time` object in :ref:`formatted string + literals ` and when using :meth:`str.format`. For a + complete list of formatting directives, see + :ref:`strftime-strptime-behavior`. + + +.. method:: time.utcoffset() + + If :attr:`.tzinfo` is ``None``, returns ``None``, else returns + ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't + return ``None`` or a :class:`timedelta` object with magnitude less than one day. + + .. versionchanged:: 3.7 + The UTC offset is not restricted to a whole number of minutes. + + +.. method:: time.dst() + + If :attr:`.tzinfo` is ``None``, returns ``None``, else returns + ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return + ``None``, or a :class:`timedelta` object with magnitude less than one day. + + .. versionchanged:: 3.7 + The DST offset is not restricted to a whole number of minutes. + +.. method:: time.tzname() + + If :attr:`.tzinfo` is ``None``, returns ``None``, else returns + ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't + return ``None`` or a string object. + +Examples of Usage: :class:`.time` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Examples of working with a :class:`.time` object:: + + >>> from datetime import time, tzinfo, timedelta + >>> class TZ1(tzinfo): + ... def utcoffset(self, dt): + ... return timedelta(hours=1) + ... def dst(self, dt): + ... return timedelta(0) + ... def tzname(self,dt): + ... return "+01:00" + ... def __repr__(self): + ... return f"{self.__class__.__name__}()" + ... + >>> t = time(12, 10, 30, tzinfo=TZ1()) + >>> t + datetime.time(12, 10, 30, tzinfo=TZ1()) + >>> t.isoformat() + '12:10:30+01:00' + >>> t.dst() + datetime.timedelta(0) + >>> t.tzname() + '+01:00' + >>> t.strftime("%H:%M:%S %Z") + '12:10:30 +01:00' + >>> 'The {} is {:%H:%M}.'.format("time", t) + 'The time is 12:10.' + + +.. _datetime-tzinfo: + +:class:`tzinfo` Objects +----------------------- + +.. class:: tzinfo() + + This is an abstract base class, meaning that this class should not be + instantiated directly. Define a subclass of :class:`tzinfo` to capture + information about a particular time zone. + + An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the + constructors for :class:`.datetime` and :class:`.time` objects. The latter objects + view their attributes as being in local time, and the :class:`tzinfo` object + supports methods revealing offset of local time from UTC, the name of the time + zone, and DST offset, all relative to a date or time object passed to them. + + You need to derive a concrete subclass, and (at least) + supply implementations of the standard :class:`tzinfo` methods needed by the + :class:`.datetime` methods you use. The :mod:`datetime` module provides + :class:`timezone`, a simple concrete subclass of :class:`tzinfo` which can + represent timezones with fixed offset from UTC such as UTC itself or North + American EST and EDT. + + Special requirement for pickling: A :class:`tzinfo` subclass must have an + :meth:`__init__` method that can be called with no arguments, otherwise it can be + pickled but possibly not unpickled again. This is a technical requirement that + may be relaxed in the future. + + A concrete subclass of :class:`tzinfo` may need to implement the following + methods. Exactly which methods are needed depends on the uses made of aware + :mod:`datetime` objects. If in doubt, simply implement all of them. + + +.. method:: tzinfo.utcoffset(dt) + + Return offset of local time from UTC, as a :class:`timedelta` object that is + positive east of UTC. If local time is west of UTC, this should be negative. + + This represents the *total* offset from UTC; for example, if a + :class:`tzinfo` object represents both time zone and DST adjustments, + :meth:`utcoffset` should return their sum. If the UTC offset isn't known, + return ``None``. Else the value returned must be a :class:`timedelta` object + strictly between ``-timedelta(hours=24)`` and ``timedelta(hours=24)`` + (the magnitude of the offset must be less than one day). Most implementations + of :meth:`utcoffset` will probably look like one of these two:: + + return CONSTANT # fixed-offset class + return CONSTANT + self.dst(dt) # daylight-aware class + + If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return + ``None`` either. + + The default implementation of :meth:`utcoffset` raises + :exc:`NotImplementedError`. + + .. versionchanged:: 3.7 + The UTC offset is not restricted to a whole number of minutes. + + +.. method:: tzinfo.dst(dt) + + Return the daylight saving time (DST) adjustment, as a :class:`timedelta` + object or + ``None`` if DST information isn't known. + + Return ``timedelta(0)`` if DST is not in effect. + If DST is in effect, return the offset as a :class:`timedelta` object + (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has + already been added to the UTC offset returned by :meth:`utcoffset`, so there's + no need to consult :meth:`dst` unless you're interested in obtaining DST info + separately. For example, :meth:`datetime.timetuple` calls its :attr:`~.datetime.tzinfo` + attribute's :meth:`dst` method to determine how the :attr:`tm_isdst` flag + should be set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for + DST changes when crossing time zones. + + An instance *tz* of a :class:`tzinfo` subclass that models both standard and + daylight times must be consistent in this sense: + + ``tz.utcoffset(dt) - tz.dst(dt)`` + + must return the same result for every :class:`.datetime` *dt* with ``dt.tzinfo == + tz`` For sane :class:`tzinfo` subclasses, this expression yields the time + zone's "standard offset", which should not depend on the date or the time, but + only on geographic location. The implementation of :meth:`datetime.astimezone` + relies on this, but cannot detect violations; it's the programmer's + responsibility to ensure it. If a :class:`tzinfo` subclass cannot guarantee + this, it may be able to override the default implementation of + :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless. + + Most implementations of :meth:`dst` will probably look like one of these two:: + + def dst(self, dt): + # a fixed-offset class: doesn't account for DST + return timedelta(0) + + or:: + + def dst(self, dt): + # Code to set dston and dstoff to the time zone's DST + # transition times based on the input dt.year, and expressed + # in standard local time. + + if dston <= dt.replace(tzinfo=None) < dstoff: + return timedelta(hours=1) + else: + return timedelta(0) + + The default implementation of :meth:`dst` raises :exc:`NotImplementedError`. + + .. versionchanged:: 3.7 + The DST offset is not restricted to a whole number of minutes. + + +.. method:: tzinfo.tzname(dt) + + Return the time zone name corresponding to the :class:`.datetime` object *dt*, as + a string. Nothing about string names is defined by the :mod:`datetime` module, + and there's no requirement that it mean anything in particular. For example, + "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all + valid replies. Return ``None`` if a string name isn't known. Note that this is + a method rather than a fixed string primarily because some :class:`tzinfo` + subclasses will wish to return different names depending on the specific value + of *dt* passed, especially if the :class:`tzinfo` class is accounting for + daylight time. + + The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`. + + +These methods are called by a :class:`.datetime` or :class:`.time` object, in +response to their methods of the same names. A :class:`.datetime` object passes +itself as the argument, and a :class:`.time` object passes ``None`` as the +argument. A :class:`tzinfo` subclass's methods should therefore be prepared to +accept a *dt* argument of ``None``, or of class :class:`.datetime`. + +When ``None`` is passed, it's up to the class designer to decide the best +response. For example, returning ``None`` is appropriate if the class wishes to +say that time objects don't participate in the :class:`tzinfo` protocols. It +may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as +there is no other convention for discovering the standard offset. + +When a :class:`.datetime` object is passed in response to a :class:`.datetime` +method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can +rely on this, unless user code calls :class:`tzinfo` methods directly. The +intent is that the :class:`tzinfo` methods interpret *dt* as being in local +time, and not need worry about objects in other timezones. + +There is one more :class:`tzinfo` method that a subclass may wish to override: + + +.. method:: tzinfo.fromutc(dt) + + This is called from the default :class:`datetime.astimezone()` + implementation. When called from that, ``dt.tzinfo`` is *self*, and *dt*'s + date and time data are to be viewed as expressing a UTC time. The purpose + of :meth:`fromutc` is to adjust the date and time data, returning an + equivalent datetime in *self*'s local time. + + Most :class:`tzinfo` subclasses should be able to inherit the default + :meth:`fromutc` implementation without problems. It's strong enough to handle + fixed-offset time zones, and time zones accounting for both standard and + daylight time, and the latter even if the DST transition times differ in + different years. An example of a time zone the default :meth:`fromutc` + implementation may not handle correctly in all cases is one where the standard + offset (from UTC) depends on the specific date and time passed, which can happen + for political reasons. The default implementations of :meth:`astimezone` and + :meth:`fromutc` may not produce the result you want if the result is one of the + hours straddling the moment the standard offset changes. + + Skipping code for error cases, the default :meth:`fromutc` implementation acts + like:: + + def fromutc(self, dt): + # raise ValueError error if dt.tzinfo is not self + dtoff = dt.utcoffset() + dtdst = dt.dst() + # raise ValueError if dtoff is None or dtdst is None + delta = dtoff - dtdst # this is self's standard offset + if delta: + dt += delta # convert to standard local time + dtdst = dt.dst() + # raise ValueError if dtdst is None + if dtdst: + return dt + dtdst + else: + return dt + +In the following :download:`tzinfo_examples.py +<../includes/tzinfo_examples.py>` file there are some examples of +:class:`tzinfo` classes: + +.. literalinclude:: ../includes/tzinfo_examples.py + +Note that there are unavoidable subtleties twice per year in a :class:`tzinfo` +subclass accounting for both standard and daylight time, at the DST transition +points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the +minute after 1:59 (EST) on the second Sunday in March, and ends the minute after +1:59 (EDT) on the first Sunday in November:: + + UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM + EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM + EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM + + start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM + + end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM + +When DST starts (the "start" line), the local wall clock leaps from 1:59 to +3:00. A wall time of the form 2:MM doesn't really make sense on that day, so +``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST +begins. For example, at the Spring forward transition of 2016, we get:: + + >>> from datetime import datetime, timezone + >>> from tzinfo_examples import HOUR, Eastern + >>> u0 = datetime(2016, 3, 13, 5, tzinfo=timezone.utc) + >>> for i in range(4): + ... u = u0 + i*HOUR + ... t = u.astimezone(Eastern) + ... print(u.time(), 'UTC =', t.time(), t.tzname()) + ... + 05:00:00 UTC = 00:00:00 EST + 06:00:00 UTC = 01:00:00 EST + 07:00:00 UTC = 03:00:00 EDT + 08:00:00 UTC = 04:00:00 EDT + + +When DST ends (the "end" line), there's a potentially worse problem: there's an +hour that can't be spelled unambiguously in local wall time: the last hour of +daylight time. In Eastern, that's times of the form 5:MM UTC on the day +daylight time ends. The local wall clock leaps from 1:59 (daylight time) back +to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous. +:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC +hours into the same local hour then. In the Eastern example, UTC times of the +form 5:MM and 6:MM both map to 1:MM when converted to Eastern, but earlier times +have the :attr:`~datetime.fold` attribute set to 0 and the later times have it set to 1. +For example, at the Fall back transition of 2016, we get:: + + >>> u0 = datetime(2016, 11, 6, 4, tzinfo=timezone.utc) + >>> for i in range(4): + ... u = u0 + i*HOUR + ... t = u.astimezone(Eastern) + ... print(u.time(), 'UTC =', t.time(), t.tzname(), t.fold) + ... + 04:00:00 UTC = 00:00:00 EDT 0 + 05:00:00 UTC = 01:00:00 EDT 0 + 06:00:00 UTC = 01:00:00 EST 1 + 07:00:00 UTC = 02:00:00 EST 0 + +Note that the :class:`.datetime` instances that differ only by the value of the +:attr:`~datetime.fold` attribute are considered equal in comparisons. + +Applications that can't bear wall-time ambiguities should explicitly check the +value of the :attr:`~datetime.fold` attribute or avoid using hybrid +:class:`tzinfo` subclasses; there are no ambiguities when using :class:`timezone`, +or any other fixed-offset :class:`tzinfo` subclass (such as a class representing +only EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)). + +.. seealso:: + + `dateutil.tz `_ + The :mod:`datetime` module has a basic :class:`timezone` class (for + handling arbitrary fixed offsets from UTC) and its :attr:`timezone.utc` + attribute (a UTC timezone instance). + + *dateutil.tz* library brings the *IANA timezone database* + (also known as the Olson database) to Python, and its usage is + recommended. + + `IANA timezone database `_ + The Time Zone Database (often called tz, tzdata or zoneinfo) contains code + and data that represent the history of local time for many representative + locations around the globe. It is updated periodically to reflect changes + made by political bodies to time zone boundaries, UTC offsets, and + daylight-saving rules. + + +.. _datetime-timezone: + +:class:`timezone` Objects +-------------------------- + +The :class:`timezone` class is a subclass of :class:`tzinfo`, each +instance of which represents a timezone defined by a fixed offset from +UTC. + +Objects of this class cannot be used to represent timezone information in the +locations where different offsets are used in different days of the year or +where historical changes have been made to civil time. + + +.. class:: timezone(offset, name=None) + + The *offset* argument must be specified as a :class:`timedelta` + object representing the difference between the local time and UTC. It must + be strictly between ``-timedelta(hours=24)`` and + ``timedelta(hours=24)``, otherwise :exc:`ValueError` is raised. + + The *name* argument is optional. If specified it must be a string that + will be used as the value returned by the :meth:`datetime.tzname` method. + + .. versionadded:: 3.2 + + .. versionchanged:: 3.7 + The UTC offset is not restricted to a whole number of minutes. + + +.. method:: timezone.utcoffset(dt) + + Return the fixed value specified when the :class:`timezone` instance is + constructed. + + The *dt* argument is ignored. The return value is a :class:`timedelta` + instance equal to the difference between the local time and UTC. + + .. versionchanged:: 3.7 + The UTC offset is not restricted to a whole number of minutes. + +.. method:: timezone.tzname(dt) + + Return the fixed value specified when the :class:`timezone` instance + is constructed. + + If *name* is not provided in the constructor, the name returned by + ``tzname(dt)`` is generated from the value of the ``offset`` as follows. If + *offset* is ``timedelta(0)``, the name is "UTC", otherwise it is a string in + the format ``UTC±HH:MM``, where ± is the sign of ``offset``, HH and MM are + two digits of ``offset.hours`` and ``offset.minutes`` respectively. + + .. versionchanged:: 3.6 + Name generated from ``offset=timedelta(0)`` is now plain `'UTC'`, not + ``'UTC+00:00'``. + + +.. method:: timezone.dst(dt) + + Always returns ``None``. + +.. method:: timezone.fromutc(dt) + + Return ``dt + offset``. The *dt* argument must be an aware + :class:`.datetime` instance, with ``tzinfo`` set to ``self``. + +Class attributes: + +.. attribute:: timezone.utc + + The UTC timezone, ``timezone(timedelta(0))``. + + +.. index:: + single: % (percent); datetime format + +.. _strftime-strptime-behavior: + +:meth:`strftime` and :meth:`strptime` Behavior +---------------------------------------------- + +:class:`date`, :class:`.datetime`, and :class:`.time` objects all support a +``strftime(format)`` method, to create a string representing the time under the +control of an explicit format string. + +Conversely, the :meth:`datetime.strptime` class method creates a +:class:`.datetime` object from a string representing a date and time and a +corresponding format string. + +The table below provides a high-level comparison of :meth:`strftime` +versus :meth:`strptime`: + ++----------------+--------------------------------------------------------+------------------------------------------------------------------------------+ +| | ``strftime`` | ``strptime`` | ++================+========================================================+==============================================================================+ +| Usage | Convert object to a string according to a given format | Parse a string into a :class:`.datetime` object given a corresponding format | ++----------------+--------------------------------------------------------+------------------------------------------------------------------------------+ +| Type of method | Instance method | Class method | ++----------------+--------------------------------------------------------+------------------------------------------------------------------------------+ +| Method of | :class:`date`; :class:`.datetime`; :class:`.time` | :class:`.datetime` | ++----------------+--------------------------------------------------------+------------------------------------------------------------------------------+ +| Signature | ``strftime(format)`` | ``strptime(date_string, format)`` | ++----------------+--------------------------------------------------------+------------------------------------------------------------------------------+ + + +:meth:`strftime` and :meth:`strptime` Format Codes +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The following is a list of all the format codes that the 1989 C standard +requires, and these work on all platforms with a standard C implementation. + ++-----------+--------------------------------+------------------------+-------+ +| Directive | Meaning | Example | Notes | ++===========+================================+========================+=======+ +| ``%a`` | Weekday as locale's || Sun, Mon, ..., Sat | \(1) | +| | abbreviated name. | (en_US); | | +| | || So, Mo, ..., Sa | | +| | | (de_DE) | | ++-----------+--------------------------------+------------------------+-------+ +| ``%A`` | Weekday as locale's full name. || Sunday, Monday, ..., | \(1) | +| | | Saturday (en_US); | | +| | || Sonntag, Montag, ..., | | +| | | Samstag (de_DE) | | ++-----------+--------------------------------+------------------------+-------+ +| ``%w`` | Weekday as a decimal number, | 0, 1, ..., 6 | | +| | where 0 is Sunday and 6 is | | | +| | Saturday. | | | ++-----------+--------------------------------+------------------------+-------+ +| ``%d`` | Day of the month as a | 01, 02, ..., 31 | \(9) | +| | zero-padded decimal number. | | | ++-----------+--------------------------------+------------------------+-------+ +| ``%b`` | Month as locale's abbreviated || Jan, Feb, ..., Dec | \(1) | +| | name. | (en_US); | | +| | || Jan, Feb, ..., Dez | | +| | | (de_DE) | | ++-----------+--------------------------------+------------------------+-------+ +| ``%B`` | Month as locale's full name. || January, February, | \(1) | +| | | ..., December (en_US);| | +| | || Januar, Februar, ..., | | +| | | Dezember (de_DE) | | ++-----------+--------------------------------+------------------------+-------+ +| ``%m`` | Month as a zero-padded | 01, 02, ..., 12 | \(9) | +| | decimal number. | | | ++-----------+--------------------------------+------------------------+-------+ +| ``%y`` | Year without century as a | 00, 01, ..., 99 | \(9) | +| | zero-padded decimal number. | | | ++-----------+--------------------------------+------------------------+-------+ +| ``%Y`` | Year with century as a decimal | 0001, 0002, ..., 2013, | \(2) | +| | number. | 2014, ..., 9998, 9999 | | ++-----------+--------------------------------+------------------------+-------+ +| ``%H`` | Hour (24-hour clock) as a | 00, 01, ..., 23 | \(9) | +| | zero-padded decimal number. | | | ++-----------+--------------------------------+------------------------+-------+ +| ``%I`` | Hour (12-hour clock) as a | 01, 02, ..., 12 | \(9) | +| | zero-padded decimal number. | | | ++-----------+--------------------------------+------------------------+-------+ +| ``%p`` | Locale's equivalent of either || AM, PM (en_US); | \(1), | +| | AM or PM. || am, pm (de_DE) | \(3) | ++-----------+--------------------------------+------------------------+-------+ +| ``%M`` | Minute as a zero-padded | 00, 01, ..., 59 | \(9) | +| | decimal number. | | | ++-----------+--------------------------------+------------------------+-------+ +| ``%S`` | Second as a zero-padded | 00, 01, ..., 59 | \(4), | +| | decimal number. | | \(9) | ++-----------+--------------------------------+------------------------+-------+ +| ``%f`` | Microsecond as a decimal | 000000, 000001, ..., | \(5) | +| | number, zero-padded on the | 999999 | | +| | left. | | | ++-----------+--------------------------------+------------------------+-------+ +| ``%z`` | UTC offset in the form | (empty), +0000, | \(6) | +| | ``±HHMM[SS[.ffffff]]`` (empty | -0400, +1030, | | +| | string if the object is | +063415, | | +| | naive). | -030712.345216 | | ++-----------+--------------------------------+------------------------+-------+ +| ``%Z`` | Time zone name (empty string | (empty), UTC, GMT | \(6) | +| | if the object is naive). | | | ++-----------+--------------------------------+------------------------+-------+ +| ``%j`` | Day of the year as a | 001, 002, ..., 366 | \(9) | +| | zero-padded decimal number. | | | ++-----------+--------------------------------+------------------------+-------+ +| ``%U`` | Week number of the year | 00, 01, ..., 53 | \(7), | +| | (Sunday as the first day of | | \(9) | +| | the week) as a zero padded | | | +| | decimal number. All days in a | | | +| | new year preceding the first | | | +| | Sunday are considered to be in | | | +| | week 0. | | | ++-----------+--------------------------------+------------------------+-------+ +| ``%W`` | Week number of the year | 00, 01, ..., 53 | \(7), | +| | (Monday as the first day of | | \(9) | +| | the week) as a decimal number. | | | +| | All days in a new year | | | +| | preceding the first Monday | | | +| | are considered to be in | | | +| | week 0. | | | ++-----------+--------------------------------+------------------------+-------+ +| ``%c`` | Locale's appropriate date and || Tue Aug 16 21:30:00 | \(1) | +| | time representation. | 1988 (en_US); | | +| | || Di 16 Aug 21:30:00 | | +| | | 1988 (de_DE) | | ++-----------+--------------------------------+------------------------+-------+ +| ``%x`` | Locale's appropriate date || 08/16/88 (None); | \(1) | +| | representation. || 08/16/1988 (en_US); | | +| | || 16.08.1988 (de_DE) | | ++-----------+--------------------------------+------------------------+-------+ +| ``%X`` | Locale's appropriate time || 21:30:00 (en_US); | \(1) | +| | representation. || 21:30:00 (de_DE) | | ++-----------+--------------------------------+------------------------+-------+ +| ``%%`` | A literal ``'%'`` character. | % | | ++-----------+--------------------------------+------------------------+-------+ + +Several additional directives not required by the C89 standard are included for +convenience. These parameters all correspond to ISO 8601 date values. + ++-----------+--------------------------------+------------------------+-------+ +| Directive | Meaning | Example | Notes | ++===========+================================+========================+=======+ +| ``%G`` | ISO 8601 year with century | 0001, 0002, ..., 2013, | \(8) | +| | representing the year that | 2014, ..., 9998, 9999 | | +| | contains the greater part of | | | +| | the ISO week (``%V``). | | | ++-----------+--------------------------------+------------------------+-------+ +| ``%u`` | ISO 8601 weekday as a decimal | 1, 2, ..., 7 | | +| | number where 1 is Monday. | | | ++-----------+--------------------------------+------------------------+-------+ +| ``%V`` | ISO 8601 week as a decimal | 01, 02, ..., 53 | \(8), | +| | number with Monday as | | \(9) | +| | the first day of the week. | | | +| | Week 01 is the week containing | | | +| | Jan 4. | | | ++-----------+--------------------------------+------------------------+-------+ + +These may not be available on all platforms when used with the :meth:`strftime` +method. The ISO 8601 year and ISO 8601 week directives are not interchangeable +with the year and week number directives above. Calling :meth:`strptime` with +incomplete or ambiguous ISO 8601 directives will raise a :exc:`ValueError`. + +The full set of format codes supported varies across platforms, because Python +calls the platform C library's :func:`strftime` function, and platform +variations are common. To see the full set of format codes supported on your +platform, consult the :manpage:`strftime(3)` documentation. + +.. versionadded:: 3.6 + ``%G``, ``%u`` and ``%V`` were added. + +Technical Detail +^^^^^^^^^^^^^^^^ + +Broadly speaking, ``d.strftime(fmt)`` acts like the :mod:`time` module's +``time.strftime(fmt, d.timetuple())`` although not all objects support a +:meth:`timetuple` method. + +For the :meth:`datetime.strptime` class method, the default value is +``1900-01-01T00:00:00.000``: any components not specified in the format string +will be pulled from the default value. [#]_ + +Using ``datetime.strptime(date_string, format)`` is equivalent to:: + + datetime(*(time.strptime(date_string, format)[0:6])) + +except when the format includes sub-second components or timezone offset +information, which are supported in ``datetime.strptime`` but are discarded by +``time.strptime``. + +For :class:`.time` objects, the format codes for year, month, and day should not +be used, as :class:`time` objects have no such values. If they're used anyway, +``1900`` is substituted for the year, and ``1`` for the month and day. + +For :class:`date` objects, the format codes for hours, minutes, seconds, and +microseconds should not be used, as :class:`date` objects have no such +values. If they're used anyway, ``0`` is substituted for them. + +For the same reason, handling of format strings containing Unicode code points +that can't be represented in the charset of the current locale is also +platform-dependent. On some platforms such code points are preserved intact in +the output, while on others ``strftime`` may raise :exc:`UnicodeError` or return +an empty string instead. + +Notes: + +(1) + Because the format depends on the current locale, care should be taken when + making assumptions about the output value. Field orderings will vary (for + example, "month/day/year" versus "day/month/year"), and the output may + contain Unicode characters encoded using the locale's default encoding (for + example, if the current locale is ``ja_JP``, the default encoding could be + any one of ``eucJP``, ``SJIS``, or ``utf-8``; use :meth:`locale.getlocale` + to determine the current locale's encoding). + +(2) + The :meth:`strptime` method can parse years in the full [1, 9999] range, but + years < 1000 must be zero-filled to 4-digit width. + + .. versionchanged:: 3.2 + In previous versions, :meth:`strftime` method was restricted to + years >= 1900. + + .. versionchanged:: 3.3 + In version 3.2, :meth:`strftime` method was restricted to + years >= 1000. + +(3) + When used with the :meth:`strptime` method, the ``%p`` directive only affects + the output hour field if the ``%I`` directive is used to parse the hour. + +(4) + Unlike the :mod:`time` module, the :mod:`datetime` module does not support + leap seconds. + +(5) + When used with the :meth:`strptime` method, the ``%f`` directive + accepts from one to six digits and zero pads on the right. ``%f`` is + an extension to the set of format characters in the C standard (but + implemented separately in datetime objects, and therefore always + available). + +(6) + For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty + strings. + + For an aware object: + + ``%z`` + :meth:`utcoffset` is transformed into a string of the form + ``±HHMM[SS[.ffffff]]``, where ``HH`` is a 2-digit string giving the number + of UTC offset hours, ``MM`` is a 2-digit string giving the number of UTC + offset minutes, ``SS`` is a 2-digit string giving the number of UTC offset + seconds and ``ffffff`` is a 6-digit string giving the number of UTC + offset microseconds. The ``ffffff`` part is omitted when the offset is a + whole number of seconds and both the ``ffffff`` and the ``SS`` part is + omitted when the offset is a whole number of minutes. For example, if + :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is + replaced with the string ``'-0330'``. + + .. versionchanged:: 3.7 + The UTC offset is not restricted to a whole number of minutes. + + .. versionchanged:: 3.7 + When the ``%z`` directive is provided to the :meth:`strptime` method, + the UTC offsets can have a colon as a separator between hours, minutes + and seconds. + For example, ``'+01:00:00'`` will be parsed as an offset of one hour. + In addition, providing ``'Z'`` is identical to ``'+00:00'``. + + ``%Z`` + In :meth:`strftime`, ``%Z`` is replaced by an empty string if + :meth:`tzname` returns ``None``; otherwise ``%Z`` is replaced by the + returned value, which must be a string. + + :meth:`strptime` only accepts certain values for ``%Z``: + + 1. any value in ``time.tzname`` for your machine's locale + 2. the hard-coded values ``UTC`` and ``GMT`` + + So someone living in Japan may have ``JST``, ``UTC``, and ``GMT`` as + valid values, but probably not ``EST``. It will raise ``ValueError`` for + invalid values. + + .. versionchanged:: 3.2 + When the ``%z`` directive is provided to the :meth:`strptime` method, an + aware :class:`.datetime` object will be produced. The ``tzinfo`` of the + result will be set to a :class:`timezone` instance. + +(7) + When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used + in calculations when the day of the week and the calendar year (``%Y``) + are specified. + +(8) + Similar to ``%U`` and ``%W``, ``%V`` is only used in calculations when the + day of the week and the ISO year (``%G``) are specified in a + :meth:`strptime` format string. Also note that ``%G`` and ``%Y`` are not + interchangeable. + +(9) + When used with the :meth:`strptime` method, the leading zero is optional + for formats ``%d``, ``%m``, ``%H``, ``%I``, ``%M``, ``%S``, ``%J``, ``%U``, + ``%W``, and ``%V``. Format ``%y`` does require a leading zero. + +.. rubric:: Footnotes + +.. [#] If, that is, we ignore the effects of Relativity + +.. [#] This matches the definition of the "proleptic Gregorian" calendar in + Dershowitz and Reingold's book *Calendrical Calculations*, + where it's the base calendar for all computations. See the book for + algorithms for converting between proleptic Gregorian ordinals and + many other calendar systems. + +.. [#] See R. H. van Gent's `guide to the mathematics of the ISO 8601 calendar + `_ + for a good explanation. + +.. [#] Passing ``datetime.strptime('Feb 29', '%b %d')`` will fail since ``1900`` is not a leap year. diff --git a/cpython_2/environment/repo/Doc/library/dbm.rst b/cpython_2/environment/repo/Doc/library/dbm.rst new file mode 100644 index 0000000000000000000000000000000000000000..57ae547b833cc0eb2a76cdfc4ed3d1f5d5b24794 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/dbm.rst @@ -0,0 +1,394 @@ +:mod:`dbm` --- Interfaces to Unix "databases" +============================================= + +.. module:: dbm + :synopsis: Interfaces to various Unix "database" formats. + +**Source code:** :source:`Lib/dbm/__init__.py` + +-------------- + +:mod:`dbm` is a generic interface to variants of the DBM database --- +:mod:`dbm.gnu` or :mod:`dbm.ndbm`. If none of these modules is installed, the +slow-but-simple implementation in module :mod:`dbm.dumb` will be used. There +is a `third party interface `_ to +the Oracle Berkeley DB. + + +.. exception:: error + + A tuple containing the exceptions that can be raised by each of the supported + modules, with a unique exception also named :exc:`dbm.error` as the first + item --- the latter is used when :exc:`dbm.error` is raised. + + +.. function:: whichdb(filename) + + This function attempts to guess which of the several simple database modules + available --- :mod:`dbm.gnu`, :mod:`dbm.ndbm` or :mod:`dbm.dumb` --- should + be used to open a given file. + + Returns one of the following values: ``None`` if the file can't be opened + because it's unreadable or doesn't exist; the empty string (``''``) if the + file's format can't be guessed; or a string containing the required module + name, such as ``'dbm.ndbm'`` or ``'dbm.gnu'``. + + +.. function:: open(file, flag='r', mode=0o666) + + Open the database file *file* and return a corresponding object. + + If the database file already exists, the :func:`whichdb` function is used to + determine its type and the appropriate module is used; if it does not exist, + the first module listed above that can be imported is used. + + The optional *flag* argument can be: + + +---------+-------------------------------------------+ + | Value | Meaning | + +=========+===========================================+ + | ``'r'`` | Open existing database for reading only | + | | (default) | + +---------+-------------------------------------------+ + | ``'w'`` | Open existing database for reading and | + | | writing | + +---------+-------------------------------------------+ + | ``'c'`` | Open database for reading and writing, | + | | creating it if it doesn't exist | + +---------+-------------------------------------------+ + | ``'n'`` | Always create a new, empty database, open | + | | for reading and writing | + +---------+-------------------------------------------+ + + The optional *mode* argument is the Unix mode of the file, used only when the + database has to be created. It defaults to octal ``0o666`` (and will be + modified by the prevailing umask). + + +The object returned by :func:`.open` supports the same basic functionality as +dictionaries; keys and their corresponding values can be stored, retrieved, and +deleted, and the :keyword:`in` operator and the :meth:`keys` method are +available, as well as :meth:`get` and :meth:`setdefault`. + +.. versionchanged:: 3.2 + :meth:`get` and :meth:`setdefault` are now available in all database modules. + +.. versionchanged:: 3.8 + Deleting a key from a read-only database raises database module specific error + instead of :exc:`KeyError`. + +Key and values are always stored as bytes. This means that when +strings are used they are implicitly converted to the default encoding before +being stored. + +These objects also support being used in a :keyword:`with` statement, which +will automatically close them when done. + +.. versionchanged:: 3.4 + Added native support for the context management protocol to the objects + returned by :func:`.open`. + +The following example records some hostnames and a corresponding title, and +then prints out the contents of the database:: + + import dbm + + # Open database, creating it if necessary. + with dbm.open('cache', 'c') as db: + + # Record some values + db[b'hello'] = b'there' + db['www.python.org'] = 'Python Website' + db['www.cnn.com'] = 'Cable News Network' + + # Note that the keys are considered bytes now. + assert db[b'www.python.org'] == b'Python Website' + # Notice how the value is now in bytes. + assert db['www.cnn.com'] == b'Cable News Network' + + # Often-used methods of the dict interface work too. + print(db.get('python.org', b'not present')) + + # Storing a non-string key or value will raise an exception (most + # likely a TypeError). + db['www.yahoo.com'] = 4 + + # db is automatically closed when leaving the with statement. + + +.. seealso:: + + Module :mod:`shelve` + Persistence module which stores non-string data. + + +The individual submodules are described in the following sections. + + +:mod:`dbm.gnu` --- GNU's reinterpretation of dbm +------------------------------------------------ + +.. module:: dbm.gnu + :platform: Unix + :synopsis: GNU's reinterpretation of dbm. + +**Source code:** :source:`Lib/dbm/gnu.py` + +-------------- + +This module is quite similar to the :mod:`dbm` module, but uses the GNU library +``gdbm`` instead to provide some additional functionality. Please note that the +file formats created by :mod:`dbm.gnu` and :mod:`dbm.ndbm` are incompatible. + +The :mod:`dbm.gnu` module provides an interface to the GNU DBM library. +``dbm.gnu.gdbm`` objects behave like mappings (dictionaries), except that keys and +values are always converted to bytes before storing. Printing a ``gdbm`` +object doesn't print the +keys and values, and the :meth:`items` and :meth:`values` methods are not +supported. + +.. exception:: error + + Raised on :mod:`dbm.gnu`-specific errors, such as I/O errors. :exc:`KeyError` is + raised for general mapping errors like specifying an incorrect key. + + +.. function:: open(filename[, flag[, mode]]) + + Open a ``gdbm`` database and return a :class:`gdbm` object. The *filename* + argument is the name of the database file. + + The optional *flag* argument can be: + + +---------+-------------------------------------------+ + | Value | Meaning | + +=========+===========================================+ + | ``'r'`` | Open existing database for reading only | + | | (default) | + +---------+-------------------------------------------+ + | ``'w'`` | Open existing database for reading and | + | | writing | + +---------+-------------------------------------------+ + | ``'c'`` | Open database for reading and writing, | + | | creating it if it doesn't exist | + +---------+-------------------------------------------+ + | ``'n'`` | Always create a new, empty database, open | + | | for reading and writing | + +---------+-------------------------------------------+ + + The following additional characters may be appended to the flag to control + how the database is opened: + + +---------+--------------------------------------------+ + | Value | Meaning | + +=========+============================================+ + | ``'f'`` | Open the database in fast mode. Writes | + | | to the database will not be synchronized. | + +---------+--------------------------------------------+ + | ``'s'`` | Synchronized mode. This will cause changes | + | | to the database to be immediately written | + | | to the file. | + +---------+--------------------------------------------+ + | ``'u'`` | Do not lock database. | + +---------+--------------------------------------------+ + + Not all flags are valid for all versions of ``gdbm``. The module constant + :const:`open_flags` is a string of supported flag characters. The exception + :exc:`error` is raised if an invalid flag is specified. + + The optional *mode* argument is the Unix mode of the file, used only when the + database has to be created. It defaults to octal ``0o666``. + + In addition to the dictionary-like methods, ``gdbm`` objects have the + following methods: + + .. method:: gdbm.firstkey() + + It's possible to loop over every key in the database using this method and the + :meth:`nextkey` method. The traversal is ordered by ``gdbm``'s internal + hash values, and won't be sorted by the key values. This method returns + the starting key. + + .. method:: gdbm.nextkey(key) + + Returns the key that follows *key* in the traversal. The following code prints + every key in the database ``db``, without having to create a list in memory that + contains them all:: + + k = db.firstkey() + while k != None: + print(k) + k = db.nextkey(k) + + .. method:: gdbm.reorganize() + + If you have carried out a lot of deletions and would like to shrink the space + used by the ``gdbm`` file, this routine will reorganize the database. ``gdbm`` + objects will not shorten the length of a database file except by using this + reorganization; otherwise, deleted file space will be kept and reused as new + (key, value) pairs are added. + + .. method:: gdbm.sync() + + When the database has been opened in fast mode, this method forces any + unwritten data to be written to the disk. + + .. method:: gdbm.close() + + Close the ``gdbm`` database. + +:mod:`dbm.ndbm` --- Interface based on ndbm +------------------------------------------- + +.. module:: dbm.ndbm + :platform: Unix + :synopsis: The standard "database" interface, based on ndbm. + +**Source code:** :source:`Lib/dbm/ndbm.py` + +-------------- + +The :mod:`dbm.ndbm` module provides an interface to the Unix "(n)dbm" library. +Dbm objects behave like mappings (dictionaries), except that keys and values are +always stored as bytes. Printing a ``dbm`` object doesn't print the keys and +values, and the :meth:`items` and :meth:`values` methods are not supported. + +This module can be used with the "classic" ndbm interface or the GNU GDBM +compatibility interface. On Unix, the :program:`configure` script will attempt +to locate the appropriate header file to simplify building this module. + +.. exception:: error + + Raised on :mod:`dbm.ndbm`-specific errors, such as I/O errors. :exc:`KeyError` is raised + for general mapping errors like specifying an incorrect key. + + +.. data:: library + + Name of the ``ndbm`` implementation library used. + + +.. function:: open(filename[, flag[, mode]]) + + Open a dbm database and return a ``ndbm`` object. The *filename* argument is the + name of the database file (without the :file:`.dir` or :file:`.pag` extensions). + + The optional *flag* argument must be one of these values: + + +---------+-------------------------------------------+ + | Value | Meaning | + +=========+===========================================+ + | ``'r'`` | Open existing database for reading only | + | | (default) | + +---------+-------------------------------------------+ + | ``'w'`` | Open existing database for reading and | + | | writing | + +---------+-------------------------------------------+ + | ``'c'`` | Open database for reading and writing, | + | | creating it if it doesn't exist | + +---------+-------------------------------------------+ + | ``'n'`` | Always create a new, empty database, open | + | | for reading and writing | + +---------+-------------------------------------------+ + + The optional *mode* argument is the Unix mode of the file, used only when the + database has to be created. It defaults to octal ``0o666`` (and will be + modified by the prevailing umask). + + In addition to the dictionary-like methods, ``ndbm`` objects + provide the following method: + + .. method:: ndbm.close() + + Close the ``ndbm`` database. + + +:mod:`dbm.dumb` --- Portable DBM implementation +----------------------------------------------- + +.. module:: dbm.dumb + :synopsis: Portable implementation of the simple DBM interface. + +**Source code:** :source:`Lib/dbm/dumb.py` + +.. index:: single: databases + +.. note:: + + The :mod:`dbm.dumb` module is intended as a last resort fallback for the + :mod:`dbm` module when a more robust module is not available. The :mod:`dbm.dumb` + module is not written for speed and is not nearly as heavily used as the other + database modules. + +-------------- + +The :mod:`dbm.dumb` module provides a persistent dictionary-like interface which +is written entirely in Python. Unlike other modules such as :mod:`dbm.gnu` no +external library is required. As with other persistent mappings, the keys and +values are always stored as bytes. + +The module defines the following: + + +.. exception:: error + + Raised on :mod:`dbm.dumb`-specific errors, such as I/O errors. :exc:`KeyError` is + raised for general mapping errors like specifying an incorrect key. + + +.. function:: open(filename[, flag[, mode]]) + + Open a ``dumbdbm`` database and return a dumbdbm object. The *filename* argument is + the basename of the database file (without any specific extensions). When a + dumbdbm database is created, files with :file:`.dat` and :file:`.dir` extensions + are created. + + The optional *flag* argument can be: + + +---------+-------------------------------------------+ + | Value | Meaning | + +=========+===========================================+ + | ``'r'`` | Open existing database for reading only | + | | (default) | + +---------+-------------------------------------------+ + | ``'w'`` | Open existing database for reading and | + | | writing | + +---------+-------------------------------------------+ + | ``'c'`` | Open database for reading and writing, | + | | creating it if it doesn't exist | + +---------+-------------------------------------------+ + | ``'n'`` | Always create a new, empty database, open | + | | for reading and writing | + +---------+-------------------------------------------+ + + The optional *mode* argument is the Unix mode of the file, used only when the + database has to be created. It defaults to octal ``0o666`` (and will be modified + by the prevailing umask). + + .. warning:: + It is possible to crash the Python interpreter when loading a database + with a sufficiently large/complex entry due to stack depth limitations in + Python's AST compiler. + + .. versionchanged:: 3.5 + :func:`.open` always creates a new database when the flag has the value + ``'n'``. + + .. versionchanged:: 3.8 + A database opened with flags ``'r'`` is now read-only. Opening with + flags ``'r'`` and ``'w'`` no longer creates a database if it does not + exist. + + In addition to the methods provided by the + :class:`collections.abc.MutableMapping` class, :class:`dumbdbm` objects + provide the following methods: + + .. method:: dumbdbm.sync() + + Synchronize the on-disk directory and data files. This method is called + by the :meth:`Shelve.sync` method. + + .. method:: dumbdbm.close() + + Close the ``dumbdbm`` database. + diff --git a/cpython_2/environment/repo/Doc/library/debug.rst b/cpython_2/environment/repo/Doc/library/debug.rst new file mode 100644 index 0000000000000000000000000000000000000000..60223657a440434120e4776c26da0455c28cf9dd --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/debug.rst @@ -0,0 +1,21 @@ +*********************** +Debugging and Profiling +*********************** + +These libraries help you with Python development: the debugger enables you to +step through code, analyze stack frames and set breakpoints etc., and the +profilers run code and give you a detailed breakdown of execution times, +allowing you to identify bottlenecks in your programs. Auditing events +provide visibility into runtime behaviors that would otherwise require +intrusive debugging or patching. + +.. toctree:: + + audit_events.rst + bdb.rst + faulthandler.rst + pdb.rst + profile.rst + timeit.rst + trace.rst + tracemalloc.rst diff --git a/cpython_2/environment/repo/Doc/library/decimal.rst b/cpython_2/environment/repo/Doc/library/decimal.rst new file mode 100644 index 0000000000000000000000000000000000000000..69a20fca17898abbc6f7a81dfc7ba5ab85cbb2c1 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/decimal.rst @@ -0,0 +1,2196 @@ +:mod:`decimal` --- Decimal fixed point and floating point arithmetic +==================================================================== + +.. module:: decimal + :synopsis: Implementation of the General Decimal Arithmetic Specification. + +.. moduleauthor:: Eric Price +.. moduleauthor:: Facundo Batista +.. moduleauthor:: Raymond Hettinger +.. moduleauthor:: Aahz +.. moduleauthor:: Tim Peters +.. moduleauthor:: Stefan Krah +.. sectionauthor:: Raymond D. Hettinger + +**Source code:** :source:`Lib/decimal.py` + +.. import modules for testing inline doctests with the Sphinx doctest builder +.. testsetup:: * + + import decimal + import math + from decimal import * + # make sure each group gets a fresh context + setcontext(Context()) + +.. testcleanup:: * + + # make sure other tests (outside this file) get a fresh context + setcontext(Context()) + +-------------- + +The :mod:`decimal` module provides support for fast correctly-rounded +decimal floating point arithmetic. It offers several advantages over the +:class:`float` datatype: + +* Decimal "is based on a floating-point model which was designed with people + in mind, and necessarily has a paramount guiding principle -- computers must + provide an arithmetic that works in the same way as the arithmetic that + people learn at school." -- excerpt from the decimal arithmetic specification. + +* Decimal numbers can be represented exactly. In contrast, numbers like + :const:`1.1` and :const:`2.2` do not have exact representations in binary + floating point. End users typically would not expect ``1.1 + 2.2`` to display + as :const:`3.3000000000000003` as it does with binary floating point. + +* The exactness carries over into arithmetic. In decimal floating point, ``0.1 + + 0.1 + 0.1 - 0.3`` is exactly equal to zero. In binary floating point, the result + is :const:`5.5511151231257827e-017`. While near to zero, the differences + prevent reliable equality testing and differences can accumulate. For this + reason, decimal is preferred in accounting applications which have strict + equality invariants. + +* The decimal module incorporates a notion of significant places so that ``1.30 + + 1.20`` is :const:`2.50`. The trailing zero is kept to indicate significance. + This is the customary presentation for monetary applications. For + multiplication, the "schoolbook" approach uses all the figures in the + multiplicands. For instance, ``1.3 * 1.2`` gives :const:`1.56` while ``1.30 * + 1.20`` gives :const:`1.5600`. + +* Unlike hardware based binary floating point, the decimal module has a user + alterable precision (defaulting to 28 places) which can be as large as needed for + a given problem: + + >>> from decimal import * + >>> getcontext().prec = 6 + >>> Decimal(1) / Decimal(7) + Decimal('0.142857') + >>> getcontext().prec = 28 + >>> Decimal(1) / Decimal(7) + Decimal('0.1428571428571428571428571429') + +* Both binary and decimal floating point are implemented in terms of published + standards. While the built-in float type exposes only a modest portion of its + capabilities, the decimal module exposes all required parts of the standard. + When needed, the programmer has full control over rounding and signal handling. + This includes an option to enforce exact arithmetic by using exceptions + to block any inexact operations. + +* The decimal module was designed to support "without prejudice, both exact + unrounded decimal arithmetic (sometimes called fixed-point arithmetic) + and rounded floating-point arithmetic." -- excerpt from the decimal + arithmetic specification. + +The module design is centered around three concepts: the decimal number, the +context for arithmetic, and signals. + +A decimal number is immutable. It has a sign, coefficient digits, and an +exponent. To preserve significance, the coefficient digits do not truncate +trailing zeros. Decimals also include special values such as +:const:`Infinity`, :const:`-Infinity`, and :const:`NaN`. The standard also +differentiates :const:`-0` from :const:`+0`. + +The context for arithmetic is an environment specifying precision, rounding +rules, limits on exponents, flags indicating the results of operations, and trap +enablers which determine whether signals are treated as exceptions. Rounding +options include :const:`ROUND_CEILING`, :const:`ROUND_DOWN`, +:const:`ROUND_FLOOR`, :const:`ROUND_HALF_DOWN`, :const:`ROUND_HALF_EVEN`, +:const:`ROUND_HALF_UP`, :const:`ROUND_UP`, and :const:`ROUND_05UP`. + +Signals are groups of exceptional conditions arising during the course of +computation. Depending on the needs of the application, signals may be ignored, +considered as informational, or treated as exceptions. The signals in the +decimal module are: :const:`Clamped`, :const:`InvalidOperation`, +:const:`DivisionByZero`, :const:`Inexact`, :const:`Rounded`, :const:`Subnormal`, +:const:`Overflow`, :const:`Underflow` and :const:`FloatOperation`. + +For each signal there is a flag and a trap enabler. When a signal is +encountered, its flag is set to one, then, if the trap enabler is +set to one, an exception is raised. Flags are sticky, so the user needs to +reset them before monitoring a calculation. + + +.. seealso:: + + * IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic + Specification `_. + +.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + + +.. _decimal-tutorial: + +Quick-start Tutorial +-------------------- + +The usual start to using decimals is importing the module, viewing the current +context with :func:`getcontext` and, if necessary, setting new values for +precision, rounding, or enabled traps:: + + >>> from decimal import * + >>> getcontext() + Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, + capitals=1, clamp=0, flags=[], traps=[Overflow, DivisionByZero, + InvalidOperation]) + + >>> getcontext().prec = 7 # Set a new precision + +Decimal instances can be constructed from integers, strings, floats, or tuples. +Construction from an integer or a float performs an exact conversion of the +value of that integer or float. Decimal numbers include special values such as +:const:`NaN` which stands for "Not a number", positive and negative +:const:`Infinity`, and :const:`-0`:: + + >>> getcontext().prec = 28 + >>> Decimal(10) + Decimal('10') + >>> Decimal('3.14') + Decimal('3.14') + >>> Decimal(3.14) + Decimal('3.140000000000000124344978758017532527446746826171875') + >>> Decimal((0, (3, 1, 4), -2)) + Decimal('3.14') + >>> Decimal(str(2.0 ** 0.5)) + Decimal('1.4142135623730951') + >>> Decimal(2) ** Decimal('0.5') + Decimal('1.414213562373095048801688724') + >>> Decimal('NaN') + Decimal('NaN') + >>> Decimal('-Infinity') + Decimal('-Infinity') + +If the :exc:`FloatOperation` signal is trapped, accidental mixing of +decimals and floats in constructors or ordering comparisons raises +an exception:: + + >>> c = getcontext() + >>> c.traps[FloatOperation] = True + >>> Decimal(3.14) + Traceback (most recent call last): + File "", line 1, in + decimal.FloatOperation: [] + >>> Decimal('3.5') < 3.7 + Traceback (most recent call last): + File "", line 1, in + decimal.FloatOperation: [] + >>> Decimal('3.5') == 3.5 + True + +.. versionadded:: 3.3 + +The significance of a new Decimal is determined solely by the number of digits +input. Context precision and rounding only come into play during arithmetic +operations. + +.. doctest:: newcontext + + >>> getcontext().prec = 6 + >>> Decimal('3.0') + Decimal('3.0') + >>> Decimal('3.1415926535') + Decimal('3.1415926535') + >>> Decimal('3.1415926535') + Decimal('2.7182818285') + Decimal('5.85987') + >>> getcontext().rounding = ROUND_UP + >>> Decimal('3.1415926535') + Decimal('2.7182818285') + Decimal('5.85988') + +If the internal limits of the C version are exceeded, constructing +a decimal raises :class:`InvalidOperation`:: + + >>> Decimal("1e9999999999999999999") + Traceback (most recent call last): + File "", line 1, in + decimal.InvalidOperation: [] + +.. versionchanged:: 3.3 + +Decimals interact well with much of the rest of Python. Here is a small decimal +floating point flying circus: + +.. doctest:: + :options: +NORMALIZE_WHITESPACE + + >>> data = list(map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split())) + >>> max(data) + Decimal('9.25') + >>> min(data) + Decimal('0.03') + >>> sorted(data) + [Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'), + Decimal('2.35'), Decimal('3.45'), Decimal('9.25')] + >>> sum(data) + Decimal('19.29') + >>> a,b,c = data[:3] + >>> str(a) + '1.34' + >>> float(a) + 1.34 + >>> round(a, 1) + Decimal('1.3') + >>> int(a) + 1 + >>> a * 5 + Decimal('6.70') + >>> a * b + Decimal('2.5058') + >>> c % a + Decimal('0.77') + +And some mathematical functions are also available to Decimal: + + >>> getcontext().prec = 28 + >>> Decimal(2).sqrt() + Decimal('1.414213562373095048801688724') + >>> Decimal(1).exp() + Decimal('2.718281828459045235360287471') + >>> Decimal('10').ln() + Decimal('2.302585092994045684017991455') + >>> Decimal('10').log10() + Decimal('1') + +The :meth:`quantize` method rounds a number to a fixed exponent. This method is +useful for monetary applications that often round results to a fixed number of +places: + + >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN) + Decimal('7.32') + >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP) + Decimal('8') + +As shown above, the :func:`getcontext` function accesses the current context and +allows the settings to be changed. This approach meets the needs of most +applications. + +For more advanced work, it may be useful to create alternate contexts using the +Context() constructor. To make an alternate active, use the :func:`setcontext` +function. + +In accordance with the standard, the :mod:`decimal` module provides two ready to +use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The +former is especially useful for debugging because many of the traps are +enabled: + +.. doctest:: newcontext + :options: +NORMALIZE_WHITESPACE + + >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN) + >>> setcontext(myothercontext) + >>> Decimal(1) / Decimal(7) + Decimal('0.142857142857142857142857142857142857142857142857142857142857') + + >>> ExtendedContext + Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, + capitals=1, clamp=0, flags=[], traps=[]) + >>> setcontext(ExtendedContext) + >>> Decimal(1) / Decimal(7) + Decimal('0.142857143') + >>> Decimal(42) / Decimal(0) + Decimal('Infinity') + + >>> setcontext(BasicContext) + >>> Decimal(42) / Decimal(0) + Traceback (most recent call last): + File "", line 1, in -toplevel- + Decimal(42) / Decimal(0) + DivisionByZero: x / 0 + +Contexts also have signal flags for monitoring exceptional conditions +encountered during computations. The flags remain set until explicitly cleared, +so it is best to clear the flags before each set of monitored computations by +using the :meth:`clear_flags` method. :: + + >>> setcontext(ExtendedContext) + >>> getcontext().clear_flags() + >>> Decimal(355) / Decimal(113) + Decimal('3.14159292') + >>> getcontext() + Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, + capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[]) + +The *flags* entry shows that the rational approximation to :const:`Pi` was +rounded (digits beyond the context precision were thrown away) and that the +result is inexact (some of the discarded digits were non-zero). + +Individual traps are set using the dictionary in the :attr:`traps` field of a +context: + +.. doctest:: newcontext + + >>> setcontext(ExtendedContext) + >>> Decimal(1) / Decimal(0) + Decimal('Infinity') + >>> getcontext().traps[DivisionByZero] = 1 + >>> Decimal(1) / Decimal(0) + Traceback (most recent call last): + File "", line 1, in -toplevel- + Decimal(1) / Decimal(0) + DivisionByZero: x / 0 + +Most programs adjust the current context only once, at the beginning of the +program. And, in many applications, data is converted to :class:`Decimal` with +a single cast inside a loop. With context set and decimals created, the bulk of +the program manipulates the data no differently than with other Python numeric +types. + +.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + + +.. _decimal-decimal: + +Decimal objects +--------------- + + +.. class:: Decimal(value="0", context=None) + + Construct a new :class:`Decimal` object based from *value*. + + *value* can be an integer, string, tuple, :class:`float`, or another :class:`Decimal` + object. If no *value* is given, returns ``Decimal('0')``. If *value* is a + string, it should conform to the decimal numeric string syntax after leading + and trailing whitespace characters, as well as underscores throughout, are removed:: + + sign ::= '+' | '-' + digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' + indicator ::= 'e' | 'E' + digits ::= digit [digit]... + decimal-part ::= digits '.' [digits] | ['.'] digits + exponent-part ::= indicator [sign] digits + infinity ::= 'Infinity' | 'Inf' + nan ::= 'NaN' [digits] | 'sNaN' [digits] + numeric-value ::= decimal-part [exponent-part] | infinity + numeric-string ::= [sign] numeric-value | [sign] nan + + Other Unicode decimal digits are also permitted where ``digit`` + appears above. These include decimal digits from various other + alphabets (for example, Arabic-Indic and Devanāgarī digits) along + with the fullwidth digits ``'\uff10'`` through ``'\uff19'``. + + If *value* is a :class:`tuple`, it should have three components, a sign + (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of + digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))`` + returns ``Decimal('1.414')``. + + If *value* is a :class:`float`, the binary floating point value is losslessly + converted to its exact decimal equivalent. This conversion can often require + 53 or more digits of precision. For example, ``Decimal(float('1.1'))`` + converts to + ``Decimal('1.100000000000000088817841970012523233890533447265625')``. + + The *context* precision does not affect how many digits are stored. That is + determined exclusively by the number of digits in *value*. For example, + ``Decimal('3.00000')`` records all five zeros even if the context precision is + only three. + + The purpose of the *context* argument is determining what to do if *value* is a + malformed string. If the context traps :const:`InvalidOperation`, an exception + is raised; otherwise, the constructor returns a new Decimal with the value of + :const:`NaN`. + + Once constructed, :class:`Decimal` objects are immutable. + + .. versionchanged:: 3.2 + The argument to the constructor is now permitted to be a :class:`float` + instance. + + .. versionchanged:: 3.3 + :class:`float` arguments raise an exception if the :exc:`FloatOperation` + trap is set. By default the trap is off. + + .. versionchanged:: 3.6 + Underscores are allowed for grouping, as with integral and floating-point + literals in code. + + Decimal floating point objects share many properties with the other built-in + numeric types such as :class:`float` and :class:`int`. All of the usual math + operations and special methods apply. Likewise, decimal objects can be + copied, pickled, printed, used as dictionary keys, used as set elements, + compared, sorted, and coerced to another type (such as :class:`float` or + :class:`int`). + + There are some small differences between arithmetic on Decimal objects and + arithmetic on integers and floats. When the remainder operator ``%`` is + applied to Decimal objects, the sign of the result is the sign of the + *dividend* rather than the sign of the divisor:: + + >>> (-7) % 4 + 1 + >>> Decimal(-7) % Decimal(4) + Decimal('-3') + + The integer division operator ``//`` behaves analogously, returning the + integer part of the true quotient (truncating towards zero) rather than its + floor, so as to preserve the usual identity ``x == (x // y) * y + x % y``:: + + >>> -7 // 4 + -2 + >>> Decimal(-7) // Decimal(4) + Decimal('-1') + + The ``%`` and ``//`` operators implement the ``remainder`` and + ``divide-integer`` operations (respectively) as described in the + specification. + + Decimal objects cannot generally be combined with floats or + instances of :class:`fractions.Fraction` in arithmetic operations: + an attempt to add a :class:`Decimal` to a :class:`float`, for + example, will raise a :exc:`TypeError`. However, it is possible to + use Python's comparison operators to compare a :class:`Decimal` + instance ``x`` with another number ``y``. This avoids confusing results + when doing equality comparisons between numbers of different types. + + .. versionchanged:: 3.2 + Mixed-type comparisons between :class:`Decimal` instances and other + numeric types are now fully supported. + + In addition to the standard numeric properties, decimal floating point + objects also have a number of specialized methods: + + + .. method:: adjusted() + + Return the adjusted exponent after shifting out the coefficient's + rightmost digits until only the lead digit remains: + ``Decimal('321e+5').adjusted()`` returns seven. Used for determining the + position of the most significant digit with respect to the decimal point. + + .. method:: as_integer_ratio() + + Return a pair ``(n, d)`` of integers that represent the given + :class:`Decimal` instance as a fraction, in lowest terms and + with a positive denominator:: + + >>> Decimal('-3.14').as_integer_ratio() + (-157, 50) + + The conversion is exact. Raise OverflowError on infinities and ValueError + on NaNs. + + .. versionadded:: 3.6 + + .. method:: as_tuple() + + Return a :term:`named tuple` representation of the number: + ``DecimalTuple(sign, digits, exponent)``. + + + .. method:: canonical() + + Return the canonical encoding of the argument. Currently, the encoding of + a :class:`Decimal` instance is always canonical, so this operation returns + its argument unchanged. + + .. method:: compare(other, context=None) + + Compare the values of two Decimal instances. :meth:`compare` returns a + Decimal instance, and if either operand is a NaN then the result is a + NaN:: + + a or b is a NaN ==> Decimal('NaN') + a < b ==> Decimal('-1') + a == b ==> Decimal('0') + a > b ==> Decimal('1') + + .. method:: compare_signal(other, context=None) + + This operation is identical to the :meth:`compare` method, except that all + NaNs signal. That is, if neither operand is a signaling NaN then any + quiet NaN operand is treated as though it were a signaling NaN. + + .. method:: compare_total(other, context=None) + + Compare two operands using their abstract representation rather than their + numerical value. Similar to the :meth:`compare` method, but the result + gives a total ordering on :class:`Decimal` instances. Two + :class:`Decimal` instances with the same numeric value but different + representations compare unequal in this ordering: + + >>> Decimal('12.0').compare_total(Decimal('12')) + Decimal('-1') + + Quiet and signaling NaNs are also included in the total ordering. The + result of this function is ``Decimal('0')`` if both operands have the same + representation, ``Decimal('-1')`` if the first operand is lower in the + total order than the second, and ``Decimal('1')`` if the first operand is + higher in the total order than the second operand. See the specification + for details of the total order. + + This operation is unaffected by context and is quiet: no flags are changed + and no rounding is performed. As an exception, the C version may raise + InvalidOperation if the second operand cannot be converted exactly. + + .. method:: compare_total_mag(other, context=None) + + Compare two operands using their abstract representation rather than their + value as in :meth:`compare_total`, but ignoring the sign of each operand. + ``x.compare_total_mag(y)`` is equivalent to + ``x.copy_abs().compare_total(y.copy_abs())``. + + This operation is unaffected by context and is quiet: no flags are changed + and no rounding is performed. As an exception, the C version may raise + InvalidOperation if the second operand cannot be converted exactly. + + .. method:: conjugate() + + Just returns self, this method is only to comply with the Decimal + Specification. + + .. method:: copy_abs() + + Return the absolute value of the argument. This operation is unaffected + by the context and is quiet: no flags are changed and no rounding is + performed. + + .. method:: copy_negate() + + Return the negation of the argument. This operation is unaffected by the + context and is quiet: no flags are changed and no rounding is performed. + + .. method:: copy_sign(other, context=None) + + Return a copy of the first operand with the sign set to be the same as the + sign of the second operand. For example: + + >>> Decimal('2.3').copy_sign(Decimal('-1.5')) + Decimal('-2.3') + + This operation is unaffected by context and is quiet: no flags are changed + and no rounding is performed. As an exception, the C version may raise + InvalidOperation if the second operand cannot be converted exactly. + + .. method:: exp(context=None) + + Return the value of the (natural) exponential function ``e**x`` at the + given number. The result is correctly rounded using the + :const:`ROUND_HALF_EVEN` rounding mode. + + >>> Decimal(1).exp() + Decimal('2.718281828459045235360287471') + >>> Decimal(321).exp() + Decimal('2.561702493119680037517373933E+139') + + .. method:: from_float(f) + + Classmethod that converts a float to a decimal number, exactly. + + Note `Decimal.from_float(0.1)` is not the same as `Decimal('0.1')`. + Since 0.1 is not exactly representable in binary floating point, the + value is stored as the nearest representable value which is + `0x1.999999999999ap-4`. That equivalent value in decimal is + `0.1000000000000000055511151231257827021181583404541015625`. + + .. note:: From Python 3.2 onwards, a :class:`Decimal` instance + can also be constructed directly from a :class:`float`. + + .. doctest:: + + >>> Decimal.from_float(0.1) + Decimal('0.1000000000000000055511151231257827021181583404541015625') + >>> Decimal.from_float(float('nan')) + Decimal('NaN') + >>> Decimal.from_float(float('inf')) + Decimal('Infinity') + >>> Decimal.from_float(float('-inf')) + Decimal('-Infinity') + + .. versionadded:: 3.1 + + .. method:: fma(other, third, context=None) + + Fused multiply-add. Return self*other+third with no rounding of the + intermediate product self*other. + + >>> Decimal(2).fma(3, 5) + Decimal('11') + + .. method:: is_canonical() + + Return :const:`True` if the argument is canonical and :const:`False` + otherwise. Currently, a :class:`Decimal` instance is always canonical, so + this operation always returns :const:`True`. + + .. method:: is_finite() + + Return :const:`True` if the argument is a finite number, and + :const:`False` if the argument is an infinity or a NaN. + + .. method:: is_infinite() + + Return :const:`True` if the argument is either positive or negative + infinity and :const:`False` otherwise. + + .. method:: is_nan() + + Return :const:`True` if the argument is a (quiet or signaling) NaN and + :const:`False` otherwise. + + .. method:: is_normal(context=None) + + Return :const:`True` if the argument is a *normal* finite number. Return + :const:`False` if the argument is zero, subnormal, infinite or a NaN. + + .. method:: is_qnan() + + Return :const:`True` if the argument is a quiet NaN, and + :const:`False` otherwise. + + .. method:: is_signed() + + Return :const:`True` if the argument has a negative sign and + :const:`False` otherwise. Note that zeros and NaNs can both carry signs. + + .. method:: is_snan() + + Return :const:`True` if the argument is a signaling NaN and :const:`False` + otherwise. + + .. method:: is_subnormal(context=None) + + Return :const:`True` if the argument is subnormal, and :const:`False` + otherwise. + + .. method:: is_zero() + + Return :const:`True` if the argument is a (positive or negative) zero and + :const:`False` otherwise. + + .. method:: ln(context=None) + + Return the natural (base e) logarithm of the operand. The result is + correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode. + + .. method:: log10(context=None) + + Return the base ten logarithm of the operand. The result is correctly + rounded using the :const:`ROUND_HALF_EVEN` rounding mode. + + .. method:: logb(context=None) + + For a nonzero number, return the adjusted exponent of its operand as a + :class:`Decimal` instance. If the operand is a zero then + ``Decimal('-Infinity')`` is returned and the :const:`DivisionByZero` flag + is raised. If the operand is an infinity then ``Decimal('Infinity')`` is + returned. + + .. method:: logical_and(other, context=None) + + :meth:`logical_and` is a logical operation which takes two *logical + operands* (see :ref:`logical_operands_label`). The result is the + digit-wise ``and`` of the two operands. + + .. method:: logical_invert(context=None) + + :meth:`logical_invert` is a logical operation. The + result is the digit-wise inversion of the operand. + + .. method:: logical_or(other, context=None) + + :meth:`logical_or` is a logical operation which takes two *logical + operands* (see :ref:`logical_operands_label`). The result is the + digit-wise ``or`` of the two operands. + + .. method:: logical_xor(other, context=None) + + :meth:`logical_xor` is a logical operation which takes two *logical + operands* (see :ref:`logical_operands_label`). The result is the + digit-wise exclusive or of the two operands. + + .. method:: max(other, context=None) + + Like ``max(self, other)`` except that the context rounding rule is applied + before returning and that :const:`NaN` values are either signaled or + ignored (depending on the context and whether they are signaling or + quiet). + + .. method:: max_mag(other, context=None) + + Similar to the :meth:`.max` method, but the comparison is done using the + absolute values of the operands. + + .. method:: min(other, context=None) + + Like ``min(self, other)`` except that the context rounding rule is applied + before returning and that :const:`NaN` values are either signaled or + ignored (depending on the context and whether they are signaling or + quiet). + + .. method:: min_mag(other, context=None) + + Similar to the :meth:`.min` method, but the comparison is done using the + absolute values of the operands. + + .. method:: next_minus(context=None) + + Return the largest number representable in the given context (or in the + current thread's context if no context is given) that is smaller than the + given operand. + + .. method:: next_plus(context=None) + + Return the smallest number representable in the given context (or in the + current thread's context if no context is given) that is larger than the + given operand. + + .. method:: next_toward(other, context=None) + + If the two operands are unequal, return the number closest to the first + operand in the direction of the second operand. If both operands are + numerically equal, return a copy of the first operand with the sign set to + be the same as the sign of the second operand. + + .. method:: normalize(context=None) + + Normalize the number by stripping the rightmost trailing zeros and + converting any result equal to :const:`Decimal('0')` to + :const:`Decimal('0e0')`. Used for producing canonical values for attributes + of an equivalence class. For example, ``Decimal('32.100')`` and + ``Decimal('0.321000e+2')`` both normalize to the equivalent value + ``Decimal('32.1')``. + + .. method:: number_class(context=None) + + Return a string describing the *class* of the operand. The returned value + is one of the following ten strings. + + * ``"-Infinity"``, indicating that the operand is negative infinity. + * ``"-Normal"``, indicating that the operand is a negative normal number. + * ``"-Subnormal"``, indicating that the operand is negative and subnormal. + * ``"-Zero"``, indicating that the operand is a negative zero. + * ``"+Zero"``, indicating that the operand is a positive zero. + * ``"+Subnormal"``, indicating that the operand is positive and subnormal. + * ``"+Normal"``, indicating that the operand is a positive normal number. + * ``"+Infinity"``, indicating that the operand is positive infinity. + * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number). + * ``"sNaN"``, indicating that the operand is a signaling NaN. + + .. method:: quantize(exp, rounding=None, context=None) + + Return a value equal to the first operand after rounding and having the + exponent of the second operand. + + >>> Decimal('1.41421356').quantize(Decimal('1.000')) + Decimal('1.414') + + Unlike other operations, if the length of the coefficient after the + quantize operation would be greater than precision, then an + :const:`InvalidOperation` is signaled. This guarantees that, unless there + is an error condition, the quantized exponent is always equal to that of + the right-hand operand. + + Also unlike other operations, quantize never signals Underflow, even if + the result is subnormal and inexact. + + If the exponent of the second operand is larger than that of the first + then rounding may be necessary. In this case, the rounding mode is + determined by the ``rounding`` argument if given, else by the given + ``context`` argument; if neither argument is given the rounding mode of + the current thread's context is used. + + An error is returned whenever the resulting exponent is greater than + :attr:`Emax` or less than :attr:`Etiny`. + + .. method:: radix() + + Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal` + class does all its arithmetic. Included for compatibility with the + specification. + + .. method:: remainder_near(other, context=None) + + Return the remainder from dividing *self* by *other*. This differs from + ``self % other`` in that the sign of the remainder is chosen so as to + minimize its absolute value. More precisely, the return value is + ``self - n * other`` where ``n`` is the integer nearest to the exact + value of ``self / other``, and if two integers are equally near then the + even one is chosen. + + If the result is zero then its sign will be the sign of *self*. + + >>> Decimal(18).remainder_near(Decimal(10)) + Decimal('-2') + >>> Decimal(25).remainder_near(Decimal(10)) + Decimal('5') + >>> Decimal(35).remainder_near(Decimal(10)) + Decimal('-5') + + .. method:: rotate(other, context=None) + + Return the result of rotating the digits of the first operand by an amount + specified by the second operand. The second operand must be an integer in + the range -precision through precision. The absolute value of the second + operand gives the number of places to rotate. If the second operand is + positive then rotation is to the left; otherwise rotation is to the right. + The coefficient of the first operand is padded on the left with zeros to + length precision if necessary. The sign and exponent of the first operand + are unchanged. + + .. method:: same_quantum(other, context=None) + + Test whether self and other have the same exponent or whether both are + :const:`NaN`. + + This operation is unaffected by context and is quiet: no flags are changed + and no rounding is performed. As an exception, the C version may raise + InvalidOperation if the second operand cannot be converted exactly. + + .. method:: scaleb(other, context=None) + + Return the first operand with exponent adjusted by the second. + Equivalently, return the first operand multiplied by ``10**other``. The + second operand must be an integer. + + .. method:: shift(other, context=None) + + Return the result of shifting the digits of the first operand by an amount + specified by the second operand. The second operand must be an integer in + the range -precision through precision. The absolute value of the second + operand gives the number of places to shift. If the second operand is + positive then the shift is to the left; otherwise the shift is to the + right. Digits shifted into the coefficient are zeros. The sign and + exponent of the first operand are unchanged. + + .. method:: sqrt(context=None) + + Return the square root of the argument to full precision. + + + .. method:: to_eng_string(context=None) + + Convert to a string, using engineering notation if an exponent is needed. + + Engineering notation has an exponent which is a multiple of 3. This + can leave up to 3 digits to the left of the decimal place and may + require the addition of either one or two trailing zeros. + + For example, this converts ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``. + + .. method:: to_integral(rounding=None, context=None) + + Identical to the :meth:`to_integral_value` method. The ``to_integral`` + name has been kept for compatibility with older versions. + + .. method:: to_integral_exact(rounding=None, context=None) + + Round to the nearest integer, signaling :const:`Inexact` or + :const:`Rounded` as appropriate if rounding occurs. The rounding mode is + determined by the ``rounding`` parameter if given, else by the given + ``context``. If neither parameter is given then the rounding mode of the + current context is used. + + .. method:: to_integral_value(rounding=None, context=None) + + Round to the nearest integer without signaling :const:`Inexact` or + :const:`Rounded`. If given, applies *rounding*; otherwise, uses the + rounding method in either the supplied *context* or the current context. + + +.. _logical_operands_label: + +Logical operands +^^^^^^^^^^^^^^^^ + +The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`, +and :meth:`logical_xor` methods expect their arguments to be *logical +operands*. A *logical operand* is a :class:`Decimal` instance whose +exponent and sign are both zero, and whose digits are all either +:const:`0` or :const:`1`. + +.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + + +.. _decimal-context: + +Context objects +--------------- + +Contexts are environments for arithmetic operations. They govern precision, set +rules for rounding, determine which signals are treated as exceptions, and limit +the range for exponents. + +Each thread has its own current context which is accessed or changed using the +:func:`getcontext` and :func:`setcontext` functions: + + +.. function:: getcontext() + + Return the current context for the active thread. + + +.. function:: setcontext(c) + + Set the current context for the active thread to *c*. + +You can also use the :keyword:`with` statement and the :func:`localcontext` +function to temporarily change the active context. + +.. function:: localcontext(ctx=None) + + Return a context manager that will set the current context for the active thread + to a copy of *ctx* on entry to the with-statement and restore the previous context + when exiting the with-statement. If no context is specified, a copy of the + current context is used. + + For example, the following code sets the current decimal precision to 42 places, + performs a calculation, and then automatically restores the previous context:: + + from decimal import localcontext + + with localcontext() as ctx: + ctx.prec = 42 # Perform a high precision calculation + s = calculate_something() + s = +s # Round the final result back to the default precision + +New contexts can also be created using the :class:`Context` constructor +described below. In addition, the module provides three pre-made contexts: + + +.. class:: BasicContext + + This is a standard context defined by the General Decimal Arithmetic + Specification. Precision is set to nine. Rounding is set to + :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated + as exceptions) except :const:`Inexact`, :const:`Rounded`, and + :const:`Subnormal`. + + Because many of the traps are enabled, this context is useful for debugging. + + +.. class:: ExtendedContext + + This is a standard context defined by the General Decimal Arithmetic + Specification. Precision is set to nine. Rounding is set to + :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that + exceptions are not raised during computations). + + Because the traps are disabled, this context is useful for applications that + prefer to have result value of :const:`NaN` or :const:`Infinity` instead of + raising exceptions. This allows an application to complete a run in the + presence of conditions that would otherwise halt the program. + + +.. class:: DefaultContext + + This context is used by the :class:`Context` constructor as a prototype for new + contexts. Changing a field (such a precision) has the effect of changing the + default for new contexts created by the :class:`Context` constructor. + + This context is most useful in multi-threaded environments. Changing one of the + fields before threads are started has the effect of setting system-wide + defaults. Changing the fields after threads have started is not recommended as + it would require thread synchronization to prevent race conditions. + + In single threaded environments, it is preferable to not use this context at + all. Instead, simply create contexts explicitly as described below. + + The default values are :attr:`prec`\ =\ :const:`28`, + :attr:`rounding`\ =\ :const:`ROUND_HALF_EVEN`, + and enabled traps for :class:`Overflow`, :class:`InvalidOperation`, and + :class:`DivisionByZero`. + +In addition to the three supplied contexts, new contexts can be created with the +:class:`Context` constructor. + + +.. class:: Context(prec=None, rounding=None, Emin=None, Emax=None, capitals=None, clamp=None, flags=None, traps=None) + + Creates a new context. If a field is not specified or is :const:`None`, the + default values are copied from the :const:`DefaultContext`. If the *flags* + field is not specified or is :const:`None`, all flags are cleared. + + *prec* is an integer in the range [:const:`1`, :const:`MAX_PREC`] that sets + the precision for arithmetic operations in the context. + + The *rounding* option is one of the constants listed in the section + `Rounding Modes`_. + + The *traps* and *flags* fields list any signals to be set. Generally, new + contexts should only set traps and leave the flags clear. + + The *Emin* and *Emax* fields are integers specifying the outer limits allowable + for exponents. *Emin* must be in the range [:const:`MIN_EMIN`, :const:`0`], + *Emax* in the range [:const:`0`, :const:`MAX_EMAX`]. + + The *capitals* field is either :const:`0` or :const:`1` (the default). If set to + :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a + lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`. + + The *clamp* field is either :const:`0` (the default) or :const:`1`. + If set to :const:`1`, the exponent ``e`` of a :class:`Decimal` + instance representable in this context is strictly limited to the + range ``Emin - prec + 1 <= e <= Emax - prec + 1``. If *clamp* is + :const:`0` then a weaker condition holds: the adjusted exponent of + the :class:`Decimal` instance is at most ``Emax``. When *clamp* is + :const:`1`, a large normal number will, where possible, have its + exponent reduced and a corresponding number of zeros added to its + coefficient, in order to fit the exponent constraints; this + preserves the value of the number but loses information about + significant trailing zeros. For example:: + + >>> Context(prec=6, Emax=999, clamp=1).create_decimal('1.23e999') + Decimal('1.23000E+999') + + A *clamp* value of :const:`1` allows compatibility with the + fixed-width decimal interchange formats specified in IEEE 754. + + The :class:`Context` class defines several general purpose methods as well as + a large number of methods for doing arithmetic directly in a given context. + In addition, for each of the :class:`Decimal` methods described above (with + the exception of the :meth:`adjusted` and :meth:`as_tuple` methods) there is + a corresponding :class:`Context` method. For example, for a :class:`Context` + instance ``C`` and :class:`Decimal` instance ``x``, ``C.exp(x)`` is + equivalent to ``x.exp(context=C)``. Each :class:`Context` method accepts a + Python integer (an instance of :class:`int`) anywhere that a + Decimal instance is accepted. + + + .. method:: clear_flags() + + Resets all of the flags to :const:`0`. + + .. method:: clear_traps() + + Resets all of the traps to :const:`0`. + + .. versionadded:: 3.3 + + .. method:: copy() + + Return a duplicate of the context. + + .. method:: copy_decimal(num) + + Return a copy of the Decimal instance num. + + .. method:: create_decimal(num) + + Creates a new Decimal instance from *num* but using *self* as + context. Unlike the :class:`Decimal` constructor, the context precision, + rounding method, flags, and traps are applied to the conversion. + + This is useful because constants are often given to a greater precision + than is needed by the application. Another benefit is that rounding + immediately eliminates unintended effects from digits beyond the current + precision. In the following example, using unrounded inputs means that + adding zero to a sum can change the result: + + .. doctest:: newcontext + + >>> getcontext().prec = 3 + >>> Decimal('3.4445') + Decimal('1.0023') + Decimal('4.45') + >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023') + Decimal('4.44') + + This method implements the to-number operation of the IBM specification. + If the argument is a string, no leading or trailing whitespace or + underscores are permitted. + + .. method:: create_decimal_from_float(f) + + Creates a new Decimal instance from a float *f* but rounding using *self* + as the context. Unlike the :meth:`Decimal.from_float` class method, + the context precision, rounding method, flags, and traps are applied to + the conversion. + + .. doctest:: + + >>> context = Context(prec=5, rounding=ROUND_DOWN) + >>> context.create_decimal_from_float(math.pi) + Decimal('3.1415') + >>> context = Context(prec=5, traps=[Inexact]) + >>> context.create_decimal_from_float(math.pi) + Traceback (most recent call last): + ... + decimal.Inexact: None + + .. versionadded:: 3.1 + + .. method:: Etiny() + + Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent + value for subnormal results. When underflow occurs, the exponent is set + to :const:`Etiny`. + + .. method:: Etop() + + Returns a value equal to ``Emax - prec + 1``. + + The usual approach to working with decimals is to create :class:`Decimal` + instances and then apply arithmetic operations which take place within the + current context for the active thread. An alternative approach is to use + context methods for calculating within a specific context. The methods are + similar to those for the :class:`Decimal` class and are only briefly + recounted here. + + + .. method:: abs(x) + + Returns the absolute value of *x*. + + + .. method:: add(x, y) + + Return the sum of *x* and *y*. + + + .. method:: canonical(x) + + Returns the same Decimal object *x*. + + + .. method:: compare(x, y) + + Compares *x* and *y* numerically. + + + .. method:: compare_signal(x, y) + + Compares the values of the two operands numerically. + + + .. method:: compare_total(x, y) + + Compares two operands using their abstract representation. + + + .. method:: compare_total_mag(x, y) + + Compares two operands using their abstract representation, ignoring sign. + + + .. method:: copy_abs(x) + + Returns a copy of *x* with the sign set to 0. + + + .. method:: copy_negate(x) + + Returns a copy of *x* with the sign inverted. + + + .. method:: copy_sign(x, y) + + Copies the sign from *y* to *x*. + + + .. method:: divide(x, y) + + Return *x* divided by *y*. + + + .. method:: divide_int(x, y) + + Return *x* divided by *y*, truncated to an integer. + + + .. method:: divmod(x, y) + + Divides two numbers and returns the integer part of the result. + + + .. method:: exp(x) + + Returns `e ** x`. + + + .. method:: fma(x, y, z) + + Returns *x* multiplied by *y*, plus *z*. + + + .. method:: is_canonical(x) + + Returns ``True`` if *x* is canonical; otherwise returns ``False``. + + + .. method:: is_finite(x) + + Returns ``True`` if *x* is finite; otherwise returns ``False``. + + + .. method:: is_infinite(x) + + Returns ``True`` if *x* is infinite; otherwise returns ``False``. + + + .. method:: is_nan(x) + + Returns ``True`` if *x* is a qNaN or sNaN; otherwise returns ``False``. + + + .. method:: is_normal(x) + + Returns ``True`` if *x* is a normal number; otherwise returns ``False``. + + + .. method:: is_qnan(x) + + Returns ``True`` if *x* is a quiet NaN; otherwise returns ``False``. + + + .. method:: is_signed(x) + + Returns ``True`` if *x* is negative; otherwise returns ``False``. + + + .. method:: is_snan(x) + + Returns ``True`` if *x* is a signaling NaN; otherwise returns ``False``. + + + .. method:: is_subnormal(x) + + Returns ``True`` if *x* is subnormal; otherwise returns ``False``. + + + .. method:: is_zero(x) + + Returns ``True`` if *x* is a zero; otherwise returns ``False``. + + + .. method:: ln(x) + + Returns the natural (base e) logarithm of *x*. + + + .. method:: log10(x) + + Returns the base 10 logarithm of *x*. + + + .. method:: logb(x) + + Returns the exponent of the magnitude of the operand's MSD. + + + .. method:: logical_and(x, y) + + Applies the logical operation *and* between each operand's digits. + + + .. method:: logical_invert(x) + + Invert all the digits in *x*. + + + .. method:: logical_or(x, y) + + Applies the logical operation *or* between each operand's digits. + + + .. method:: logical_xor(x, y) + + Applies the logical operation *xor* between each operand's digits. + + + .. method:: max(x, y) + + Compares two values numerically and returns the maximum. + + + .. method:: max_mag(x, y) + + Compares the values numerically with their sign ignored. + + + .. method:: min(x, y) + + Compares two values numerically and returns the minimum. + + + .. method:: min_mag(x, y) + + Compares the values numerically with their sign ignored. + + + .. method:: minus(x) + + Minus corresponds to the unary prefix minus operator in Python. + + + .. method:: multiply(x, y) + + Return the product of *x* and *y*. + + + .. method:: next_minus(x) + + Returns the largest representable number smaller than *x*. + + + .. method:: next_plus(x) + + Returns the smallest representable number larger than *x*. + + + .. method:: next_toward(x, y) + + Returns the number closest to *x*, in direction towards *y*. + + + .. method:: normalize(x) + + Reduces *x* to its simplest form. + + + .. method:: number_class(x) + + Returns an indication of the class of *x*. + + + .. method:: plus(x) + + Plus corresponds to the unary prefix plus operator in Python. This + operation applies the context precision and rounding, so it is *not* an + identity operation. + + + .. method:: power(x, y, modulo=None) + + Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if given. + + With two arguments, compute ``x**y``. If ``x`` is negative then ``y`` + must be integral. The result will be inexact unless ``y`` is integral and + the result is finite and can be expressed exactly in 'precision' digits. + The rounding mode of the context is used. Results are always correctly-rounded + in the Python version. + + .. versionchanged:: 3.3 + The C module computes :meth:`power` in terms of the correctly-rounded + :meth:`exp` and :meth:`ln` functions. The result is well-defined but + only "almost always correctly-rounded". + + With three arguments, compute ``(x**y) % modulo``. For the three argument + form, the following restrictions on the arguments hold: + + - all three arguments must be integral + - ``y`` must be nonnegative + - at least one of ``x`` or ``y`` must be nonzero + - ``modulo`` must be nonzero and have at most 'precision' digits + + The value resulting from ``Context.power(x, y, modulo)`` is + equal to the value that would be obtained by computing ``(x**y) + % modulo`` with unbounded precision, but is computed more + efficiently. The exponent of the result is zero, regardless of + the exponents of ``x``, ``y`` and ``modulo``. The result is + always exact. + + + .. method:: quantize(x, y) + + Returns a value equal to *x* (rounded), having the exponent of *y*. + + + .. method:: radix() + + Just returns 10, as this is Decimal, :) + + + .. method:: remainder(x, y) + + Returns the remainder from integer division. + + The sign of the result, if non-zero, is the same as that of the original + dividend. + + + .. method:: remainder_near(x, y) + + Returns ``x - y * n``, where *n* is the integer nearest the exact value + of ``x / y`` (if the result is 0 then its sign will be the sign of *x*). + + + .. method:: rotate(x, y) + + Returns a rotated copy of *x*, *y* times. + + + .. method:: same_quantum(x, y) + + Returns ``True`` if the two operands have the same exponent. + + + .. method:: scaleb (x, y) + + Returns the first operand after adding the second value its exp. + + + .. method:: shift(x, y) + + Returns a shifted copy of *x*, *y* times. + + + .. method:: sqrt(x) + + Square root of a non-negative number to context precision. + + + .. method:: subtract(x, y) + + Return the difference between *x* and *y*. + + + .. method:: to_eng_string(x) + + Convert to a string, using engineering notation if an exponent is needed. + + Engineering notation has an exponent which is a multiple of 3. This + can leave up to 3 digits to the left of the decimal place and may + require the addition of either one or two trailing zeros. + + + .. method:: to_integral_exact(x) + + Rounds to an integer. + + + .. method:: to_sci_string(x) + + Converts a number to a string using scientific notation. + +.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +.. _decimal-rounding-modes: + +Constants +--------- + +The constants in this section are only relevant for the C module. They +are also included in the pure Python version for compatibility. + ++---------------------+---------------------+-------------------------------+ +| | 32-bit | 64-bit | ++=====================+=====================+===============================+ +| .. data:: MAX_PREC | :const:`425000000` | :const:`999999999999999999` | ++---------------------+---------------------+-------------------------------+ +| .. data:: MAX_EMAX | :const:`425000000` | :const:`999999999999999999` | ++---------------------+---------------------+-------------------------------+ +| .. data:: MIN_EMIN | :const:`-425000000` | :const:`-999999999999999999` | ++---------------------+---------------------+-------------------------------+ +| .. data:: MIN_ETINY | :const:`-849999999` | :const:`-1999999999999999997` | ++---------------------+---------------------+-------------------------------+ + + +.. data:: HAVE_THREADS + + The value is ``True``. Deprecated, because Python now always has threads. + +.. deprecated:: 3.9 + +.. data:: HAVE_CONTEXTVAR + + The default value is ``True``. If Python is compiled ``--without-decimal-contextvar``, + the C version uses a thread-local rather than a coroutine-local context and the value + is ``False``. This is slightly faster in some nested context scenarios. + +.. versionadded:: 3.9 backported to 3.7 and 3.8. + + +Rounding modes +-------------- + +.. data:: ROUND_CEILING + + Round towards :const:`Infinity`. + +.. data:: ROUND_DOWN + + Round towards zero. + +.. data:: ROUND_FLOOR + + Round towards :const:`-Infinity`. + +.. data:: ROUND_HALF_DOWN + + Round to nearest with ties going towards zero. + +.. data:: ROUND_HALF_EVEN + + Round to nearest with ties going to nearest even integer. + +.. data:: ROUND_HALF_UP + + Round to nearest with ties going away from zero. + +.. data:: ROUND_UP + + Round away from zero. + +.. data:: ROUND_05UP + + Round away from zero if last digit after rounding towards zero would have + been 0 or 5; otherwise round towards zero. + + +.. _decimal-signals: + +Signals +------- + +Signals represent conditions that arise during computation. Each corresponds to +one context flag and one context trap enabler. + +The context flag is set whenever the condition is encountered. After the +computation, flags may be checked for informational purposes (for instance, to +determine whether a computation was exact). After checking the flags, be sure to +clear all flags before starting the next computation. + +If the context's trap enabler is set for the signal, then the condition causes a +Python exception to be raised. For example, if the :class:`DivisionByZero` trap +is set, then a :exc:`DivisionByZero` exception is raised upon encountering the +condition. + + +.. class:: Clamped + + Altered an exponent to fit representation constraints. + + Typically, clamping occurs when an exponent falls outside the context's + :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to + fit by adding zeros to the coefficient. + + +.. class:: DecimalException + + Base class for other signals and a subclass of :exc:`ArithmeticError`. + + +.. class:: DivisionByZero + + Signals the division of a non-infinite number by zero. + + Can occur with division, modulo division, or when raising a number to a negative + power. If this signal is not trapped, returns :const:`Infinity` or + :const:`-Infinity` with the sign determined by the inputs to the calculation. + + +.. class:: Inexact + + Indicates that rounding occurred and the result is not exact. + + Signals when non-zero digits were discarded during rounding. The rounded result + is returned. The signal flag or trap is used to detect when results are + inexact. + + +.. class:: InvalidOperation + + An invalid operation was performed. + + Indicates that an operation was requested that does not make sense. If not + trapped, returns :const:`NaN`. Possible causes include:: + + Infinity - Infinity + 0 * Infinity + Infinity / Infinity + x % 0 + Infinity % x + sqrt(-x) and x > 0 + 0 ** 0 + x ** (non-integer) + x ** Infinity + + +.. class:: Overflow + + Numerical overflow. + + Indicates the exponent is larger than :attr:`Emax` after rounding has + occurred. If not trapped, the result depends on the rounding mode, either + pulling inward to the largest representable finite number or rounding outward + to :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded` + are also signaled. + + +.. class:: Rounded + + Rounding occurred though possibly no information was lost. + + Signaled whenever rounding discards digits; even if those digits are zero + (such as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns + the result unchanged. This signal is used to detect loss of significant + digits. + + +.. class:: Subnormal + + Exponent was lower than :attr:`Emin` prior to rounding. + + Occurs when an operation result is subnormal (the exponent is too small). If + not trapped, returns the result unchanged. + + +.. class:: Underflow + + Numerical underflow with result rounded to zero. + + Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact` + and :class:`Subnormal` are also signaled. + + +.. class:: FloatOperation + + Enable stricter semantics for mixing floats and Decimals. + + If the signal is not trapped (default), mixing floats and Decimals is + permitted in the :class:`~decimal.Decimal` constructor, + :meth:`~decimal.Context.create_decimal` and all comparison operators. + Both conversion and comparisons are exact. Any occurrence of a mixed + operation is silently recorded by setting :exc:`FloatOperation` in the + context flags. Explicit conversions with :meth:`~decimal.Decimal.from_float` + or :meth:`~decimal.Context.create_decimal_from_float` do not set the flag. + + Otherwise (the signal is trapped), only equality comparisons and explicit + conversions are silent. All other mixed operations raise :exc:`FloatOperation`. + + +The following table summarizes the hierarchy of signals:: + + exceptions.ArithmeticError(exceptions.Exception) + DecimalException + Clamped + DivisionByZero(DecimalException, exceptions.ZeroDivisionError) + Inexact + Overflow(Inexact, Rounded) + Underflow(Inexact, Rounded, Subnormal) + InvalidOperation + Rounded + Subnormal + FloatOperation(DecimalException, exceptions.TypeError) + +.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + + + +.. _decimal-notes: + +Floating Point Notes +-------------------- + + +Mitigating round-off error with increased precision +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The use of decimal floating point eliminates decimal representation error +(making it possible to represent :const:`0.1` exactly); however, some operations +can still incur round-off error when non-zero digits exceed the fixed precision. + +The effects of round-off error can be amplified by the addition or subtraction +of nearly offsetting quantities resulting in loss of significance. Knuth +provides two instructive examples where rounded floating point arithmetic with +insufficient precision causes the breakdown of the associative and distributive +properties of addition: + +.. doctest:: newcontext + + # Examples from Seminumerical Algorithms, Section 4.2.2. + >>> from decimal import Decimal, getcontext + >>> getcontext().prec = 8 + + >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111') + >>> (u + v) + w + Decimal('9.5111111') + >>> u + (v + w) + Decimal('10') + + >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003') + >>> (u*v) + (u*w) + Decimal('0.01') + >>> u * (v+w) + Decimal('0.0060000') + +The :mod:`decimal` module makes it possible to restore the identities by +expanding the precision sufficiently to avoid loss of significance: + +.. doctest:: newcontext + + >>> getcontext().prec = 20 + >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111') + >>> (u + v) + w + Decimal('9.51111111') + >>> u + (v + w) + Decimal('9.51111111') + >>> + >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003') + >>> (u*v) + (u*w) + Decimal('0.0060000') + >>> u * (v+w) + Decimal('0.0060000') + + +Special values +^^^^^^^^^^^^^^ + +The number system for the :mod:`decimal` module provides special values +including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`, +and two zeros, :const:`+0` and :const:`-0`. + +Infinities can be constructed directly with: ``Decimal('Infinity')``. Also, +they can arise from dividing by zero when the :exc:`DivisionByZero` signal is +not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity +can result from rounding beyond the limits of the largest representable number. + +The infinities are signed (affine) and can be used in arithmetic operations +where they get treated as very large, indeterminate numbers. For instance, +adding a constant to infinity gives another infinite result. + +Some operations are indeterminate and return :const:`NaN`, or if the +:exc:`InvalidOperation` signal is trapped, raise an exception. For example, +``0/0`` returns :const:`NaN` which means "not a number". This variety of +:const:`NaN` is quiet and, once created, will flow through other computations +always resulting in another :const:`NaN`. This behavior can be useful for a +series of computations that occasionally have missing inputs --- it allows the +calculation to proceed while flagging specific results as invalid. + +A variant is :const:`sNaN` which signals rather than remaining quiet after every +operation. This is a useful return value when an invalid result needs to +interrupt a calculation for special handling. + +The behavior of Python's comparison operators can be a little surprising where a +:const:`NaN` is involved. A test for equality where one of the operands is a +quiet or signaling :const:`NaN` always returns :const:`False` (even when doing +``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns +:const:`True`. An attempt to compare two Decimals using any of the ``<``, +``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal +if either operand is a :const:`NaN`, and return :const:`False` if this signal is +not trapped. Note that the General Decimal Arithmetic specification does not +specify the behavior of direct comparisons; these rules for comparisons +involving a :const:`NaN` were taken from the IEEE 854 standard (see Table 3 in +section 5.7). To ensure strict standards-compliance, use the :meth:`compare` +and :meth:`compare-signal` methods instead. + +The signed zeros can result from calculations that underflow. They keep the sign +that would have resulted if the calculation had been carried out to greater +precision. Since their magnitude is zero, both positive and negative zeros are +treated as equal and their sign is informational. + +In addition to the two signed zeros which are distinct yet equal, there are +various representations of zero with differing precisions yet equivalent in +value. This takes a bit of getting used to. For an eye accustomed to +normalized floating point representations, it is not immediately obvious that +the following calculation returns a value equal to zero: + + >>> 1 / Decimal('Infinity') + Decimal('0E-1000026') + +.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + + +.. _decimal-threads: + +Working with threads +-------------------- + +The :func:`getcontext` function accesses a different :class:`Context` object for +each thread. Having separate thread contexts means that threads may make +changes (such as ``getcontext().prec=10``) without interfering with other threads. + +Likewise, the :func:`setcontext` function automatically assigns its target to +the current thread. + +If :func:`setcontext` has not been called before :func:`getcontext`, then +:func:`getcontext` will automatically create a new context for use in the +current thread. + +The new context is copied from a prototype context called *DefaultContext*. To +control the defaults so that each thread will use the same values throughout the +application, directly modify the *DefaultContext* object. This should be done +*before* any threads are started so that there won't be a race condition between +threads calling :func:`getcontext`. For example:: + + # Set applicationwide defaults for all threads about to be launched + DefaultContext.prec = 12 + DefaultContext.rounding = ROUND_DOWN + DefaultContext.traps = ExtendedContext.traps.copy() + DefaultContext.traps[InvalidOperation] = 1 + setcontext(DefaultContext) + + # Afterwards, the threads can be started + t1.start() + t2.start() + t3.start() + . . . + +.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + + +.. _decimal-recipes: + +Recipes +------- + +Here are a few recipes that serve as utility functions and that demonstrate ways +to work with the :class:`Decimal` class:: + + def moneyfmt(value, places=2, curr='', sep=',', dp='.', + pos='', neg='-', trailneg=''): + """Convert Decimal to a money formatted string. + + places: required number of places after the decimal point + curr: optional currency symbol before the sign (may be blank) + sep: optional grouping separator (comma, period, space, or blank) + dp: decimal point indicator (comma or period) + only specify as blank when places is zero + pos: optional sign for positive numbers: '+', space or blank + neg: optional sign for negative numbers: '-', '(', space or blank + trailneg:optional trailing minus indicator: '-', ')', space or blank + + >>> d = Decimal('-1234567.8901') + >>> moneyfmt(d, curr='$') + '-$1,234,567.89' + >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-') + '1.234.568-' + >>> moneyfmt(d, curr='$', neg='(', trailneg=')') + '($1,234,567.89)' + >>> moneyfmt(Decimal(123456789), sep=' ') + '123 456 789.00' + >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>') + '<0.02>' + + """ + q = Decimal(10) ** -places # 2 places --> '0.01' + sign, digits, exp = value.quantize(q).as_tuple() + result = [] + digits = list(map(str, digits)) + build, next = result.append, digits.pop + if sign: + build(trailneg) + for i in range(places): + build(next() if digits else '0') + if places: + build(dp) + if not digits: + build('0') + i = 0 + while digits: + build(next()) + i += 1 + if i == 3 and digits: + i = 0 + build(sep) + build(curr) + build(neg if sign else pos) + return ''.join(reversed(result)) + + def pi(): + """Compute Pi to the current precision. + + >>> print(pi()) + 3.141592653589793238462643383 + + """ + getcontext().prec += 2 # extra digits for intermediate steps + three = Decimal(3) # substitute "three=3.0" for regular floats + lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24 + while s != lasts: + lasts = s + n, na = n+na, na+8 + d, da = d+da, da+32 + t = (t * n) / d + s += t + getcontext().prec -= 2 + return +s # unary plus applies the new precision + + def exp(x): + """Return e raised to the power of x. Result type matches input type. + + >>> print(exp(Decimal(1))) + 2.718281828459045235360287471 + >>> print(exp(Decimal(2))) + 7.389056098930650227230427461 + >>> print(exp(2.0)) + 7.38905609893 + >>> print(exp(2+0j)) + (7.38905609893+0j) + + """ + getcontext().prec += 2 + i, lasts, s, fact, num = 0, 0, 1, 1, 1 + while s != lasts: + lasts = s + i += 1 + fact *= i + num *= x + s += num / fact + getcontext().prec -= 2 + return +s + + def cos(x): + """Return the cosine of x as measured in radians. + + The Taylor series approximation works best for a small value of x. + For larger values, first compute x = x % (2 * pi). + + >>> print(cos(Decimal('0.5'))) + 0.8775825618903727161162815826 + >>> print(cos(0.5)) + 0.87758256189 + >>> print(cos(0.5+0j)) + (0.87758256189+0j) + + """ + getcontext().prec += 2 + i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1 + while s != lasts: + lasts = s + i += 2 + fact *= i * (i-1) + num *= x * x + sign *= -1 + s += num / fact * sign + getcontext().prec -= 2 + return +s + + def sin(x): + """Return the sine of x as measured in radians. + + The Taylor series approximation works best for a small value of x. + For larger values, first compute x = x % (2 * pi). + + >>> print(sin(Decimal('0.5'))) + 0.4794255386042030002732879352 + >>> print(sin(0.5)) + 0.479425538604 + >>> print(sin(0.5+0j)) + (0.479425538604+0j) + + """ + getcontext().prec += 2 + i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1 + while s != lasts: + lasts = s + i += 2 + fact *= i * (i-1) + num *= x * x + sign *= -1 + s += num / fact * sign + getcontext().prec -= 2 + return +s + + +.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + + +.. _decimal-faq: + +Decimal FAQ +----------- + +Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to +minimize typing when using the interactive interpreter? + +A. Some users abbreviate the constructor to just a single letter: + + >>> D = decimal.Decimal + >>> D('1.23') + D('3.45') + Decimal('4.68') + +Q. In a fixed-point application with two decimal places, some inputs have many +places and need to be rounded. Others are not supposed to have excess digits +and need to be validated. What methods should be used? + +A. The :meth:`quantize` method rounds to a fixed number of decimal places. If +the :const:`Inexact` trap is set, it is also useful for validation: + + >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01') + + >>> # Round to two places + >>> Decimal('3.214').quantize(TWOPLACES) + Decimal('3.21') + + >>> # Validate that a number does not exceed two places + >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact])) + Decimal('3.21') + + >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact])) + Traceback (most recent call last): + ... + Inexact: None + +Q. Once I have valid two place inputs, how do I maintain that invariant +throughout an application? + +A. Some operations like addition, subtraction, and multiplication by an integer +will automatically preserve fixed point. Others operations, like division and +non-integer multiplication, will change the number of decimal places and need to +be followed-up with a :meth:`quantize` step: + + >>> a = Decimal('102.72') # Initial fixed-point values + >>> b = Decimal('3.17') + >>> a + b # Addition preserves fixed-point + Decimal('105.89') + >>> a - b + Decimal('99.55') + >>> a * 42 # So does integer multiplication + Decimal('4314.24') + >>> (a * b).quantize(TWOPLACES) # Must quantize non-integer multiplication + Decimal('325.62') + >>> (b / a).quantize(TWOPLACES) # And quantize division + Decimal('0.03') + +In developing fixed-point applications, it is convenient to define functions +to handle the :meth:`quantize` step: + + >>> def mul(x, y, fp=TWOPLACES): + ... return (x * y).quantize(fp) + >>> def div(x, y, fp=TWOPLACES): + ... return (x / y).quantize(fp) + + >>> mul(a, b) # Automatically preserve fixed-point + Decimal('325.62') + >>> div(b, a) + Decimal('0.03') + +Q. There are many ways to express the same value. The numbers :const:`200`, +:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at +various precisions. Is there a way to transform them to a single recognizable +canonical value? + +A. The :meth:`normalize` method maps all equivalent values to a single +representative: + + >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split()) + >>> [v.normalize() for v in values] + [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')] + +Q. Some decimal values always print with exponential notation. Is there a way +to get a non-exponential representation? + +A. For some values, exponential notation is the only way to express the number +of significant places in the coefficient. For example, expressing +:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the +original's two-place significance. + +If an application does not care about tracking significance, it is easy to +remove the exponent and trailing zeroes, losing significance, but keeping the +value unchanged: + + >>> def remove_exponent(d): + ... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize() + + >>> remove_exponent(Decimal('5E+3')) + Decimal('5000') + +Q. Is there a way to convert a regular float to a :class:`Decimal`? + +A. Yes, any binary floating point number can be exactly expressed as a +Decimal though an exact conversion may take more precision than intuition would +suggest: + +.. doctest:: + + >>> Decimal(math.pi) + Decimal('3.141592653589793115997963468544185161590576171875') + +Q. Within a complex calculation, how can I make sure that I haven't gotten a +spurious result because of insufficient precision or rounding anomalies. + +A. The decimal module makes it easy to test results. A best practice is to +re-run calculations using greater precision and with various rounding modes. +Widely differing results indicate insufficient precision, rounding mode issues, +ill-conditioned inputs, or a numerically unstable algorithm. + +Q. I noticed that context precision is applied to the results of operations but +not to the inputs. Is there anything to watch out for when mixing values of +different precisions? + +A. Yes. The principle is that all values are considered to be exact and so is +the arithmetic on those values. Only the results are rounded. The advantage +for inputs is that "what you type is what you get". A disadvantage is that the +results can look odd if you forget that the inputs haven't been rounded: + +.. doctest:: newcontext + + >>> getcontext().prec = 3 + >>> Decimal('3.104') + Decimal('2.104') + Decimal('5.21') + >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104') + Decimal('5.20') + +The solution is either to increase precision or to force rounding of inputs +using the unary plus operation: + +.. doctest:: newcontext + + >>> getcontext().prec = 3 + >>> +Decimal('1.23456789') # unary plus triggers rounding + Decimal('1.23') + +Alternatively, inputs can be rounded upon creation using the +:meth:`Context.create_decimal` method: + + >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678') + Decimal('1.2345') + +Q. Is the CPython implementation fast for large numbers? + +A. Yes. In the CPython and PyPy3 implementations, the C/CFFI versions of +the decimal module integrate the high speed `libmpdec +`_ library for +arbitrary precision correctly-rounded decimal floating point arithmetic [#]_. +``libmpdec`` uses `Karatsuba multiplication +`_ +for medium-sized numbers and the `Number Theoretic Transform +`_ +for very large numbers. + +The context must be adapted for exact arbitrary precision arithmetic. :attr:`Emin` +and :attr:`Emax` should always be set to the maximum values, :attr:`clamp` +should always be 0 (the default). Setting :attr:`prec` requires some care. + +The easiest approach for trying out bignum arithmetic is to use the maximum +value for :attr:`prec` as well [#]_:: + + >>> setcontext(Context(prec=MAX_PREC, Emax=MAX_EMAX, Emin=MIN_EMIN)) + >>> x = Decimal(2) ** 256 + >>> x / 128 + Decimal('904625697166532776746648320380374280103671755200316906558262375061821325312') + + +For inexact results, :attr:`MAX_PREC` is far too large on 64-bit platforms and +the available memory will be insufficient:: + + >>> Decimal(1) / 3 + Traceback (most recent call last): + File "", line 1, in + MemoryError + +On systems with overallocation (e.g. Linux), a more sophisticated approach is to +adjust :attr:`prec` to the amount of available RAM. Suppose that you have 8GB of +RAM and expect 10 simultaneous operands using a maximum of 500MB each:: + + >>> import sys + >>> + >>> # Maximum number of digits for a single operand using 500MB in 8-byte words + >>> # with 19 digits per word (4-byte and 9 digits for the 32-bit build): + >>> maxdigits = 19 * ((500 * 1024**2) // 8) + >>> + >>> # Check that this works: + >>> c = Context(prec=maxdigits, Emax=MAX_EMAX, Emin=MIN_EMIN) + >>> c.traps[Inexact] = True + >>> setcontext(c) + >>> + >>> # Fill the available precision with nines: + >>> x = Decimal(0).logical_invert() * 9 + >>> sys.getsizeof(x) + 524288112 + >>> x + 2 + Traceback (most recent call last): + File "", line 1, in + decimal.Inexact: [] + +In general (and especially on systems without overallocation), it is recommended +to estimate even tighter bounds and set the :attr:`Inexact` trap if all calculations +are expected to be exact. + + +.. [#] + .. versionadded:: 3.3 + +.. [#] + .. versionchanged:: 3.9 + This approach now works for all exact results except for non-integer powers. + Also backported to 3.7 and 3.8. diff --git a/cpython_2/environment/repo/Doc/library/development.rst b/cpython_2/environment/repo/Doc/library/development.rst new file mode 100644 index 0000000000000000000000000000000000000000..9edce758688e2d7f4deca24bb2b67a71c0e9527d --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/development.rst @@ -0,0 +1,27 @@ +.. _development: + +***************** +Development Tools +***************** + +The modules described in this chapter help you write software. For example, the +:mod:`pydoc` module takes a module and generates documentation based on the +module's contents. The :mod:`doctest` and :mod:`unittest` modules contains +frameworks for writing unit tests that automatically exercise code and verify +that the expected output is produced. :program:`2to3` can translate Python 2.x +source code into valid Python 3.x code. + +The list of modules described in this chapter is: + + +.. toctree:: + + typing.rst + pydoc.rst + devmode.rst + doctest.rst + unittest.rst + unittest.mock.rst + unittest.mock-examples.rst + 2to3.rst + test.rst diff --git a/cpython_2/environment/repo/Doc/library/devmode.rst b/cpython_2/environment/repo/Doc/library/devmode.rst new file mode 100644 index 0000000000000000000000000000000000000000..d5a40cdeeac5efb4e02056178ae434f4649d7304 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/devmode.rst @@ -0,0 +1,214 @@ +.. _devmode: + +Python Development Mode +======================= + +.. versionadded:: 3.7 + +The Python Development Mode introduces additional runtime checks that are too +expensive to be enabled by default. It should not be more verbose than the +default if the code is correct; new warnings are only emitted when an issue is +detected. + +It can be enabled using the :option:`-X dev <-X>` command line option or by +setting the :envvar:`PYTHONDEVMODE` environment variable to ``1``. + +Effects of the Python Development Mode +====================================== + +Enabling the Python Development Mode is similar to the following command, but +with additional effects described below:: + + PYTHONMALLOC=debug PYTHONASYNCIODEBUG=1 python3 -W default -X faulthandler + +Effects of the Python Development Mode: + +* Add ``default`` :ref:`warning filter `. The + following warnings are shown: + + * :exc:`DeprecationWarning` + * :exc:`ImportWarning` + * :exc:`PendingDeprecationWarning` + * :exc:`ResourceWarning` + + Normally, the above warnings are filtered by the default :ref:`warning + filters `. + + It behaves as if the :option:`-W default <-W>` command line option is used. + + Use the :option:`-W error <-W>` command line option or set the + :envvar:`PYTHONWARNINGS` environment variable to ``error`` to treat warnings + as errors. + +* Install debug hooks on memory allocators to check for: + + * Buffer underflow + * Buffer overflow + * Memory allocator API violation + * Unsafe usage of the GIL + + See the :c:func:`PyMem_SetupDebugHooks` C function. + + It behaves as if the :envvar:`PYTHONMALLOC` environment variable is set to + ``debug``. + + To enable the Python Development Mode without installing debug hooks on + memory allocators, set the :envvar:`PYTHONMALLOC` environment variable to + ``default``. + +* Call :func:`faulthandler.enable` at Python startup to install handlers for + the :const:`SIGSEGV`, :const:`SIGFPE`, :const:`SIGABRT`, :const:`SIGBUS` and + :const:`SIGILL` signals to dump the Python traceback on a crash. + + It behaves as if the :option:`-X faulthandler <-X>` command line option is + used or if the :envvar:`PYTHONFAULTHANDLER` environment variable is set to + ``1``. + +* Enable :ref:`asyncio debug mode `. For example, + :mod:`asyncio` checks for coroutines that were not awaited and logs them. + + It behaves as if the :envvar:`PYTHONASYNCIODEBUG` environment variable is set + to ``1``. + +* Check the *encoding* and *errors* arguments for string encoding and decoding + operations. Examples: :func:`open`, :meth:`str.encode` and + :meth:`bytes.decode`. + + By default, for best performance, the *errors* argument is only checked at + the first encoding/decoding error and the *encoding* argument is sometimes + ignored for empty strings. + +* The :class:`io.IOBase` destructor logs ``close()`` exceptions. +* Set the :attr:`~sys.flags.dev_mode` attribute of :attr:`sys.flags` to + ``True``. + +The Python Development Mode does not enable the :mod:`tracemalloc` module by +default, because the overhead cost (to performance and memory) would be too +large. Enabling the :mod:`tracemalloc` module provides additional information +on the origin of some errors. For example, :exc:`ResourceWarning` logs the +traceback where the resource was allocated, and a buffer overflow error logs +the traceback where the memory block was allocated. + +The Python Development Mode does not prevent the :option:`-O` command line +option from removing :keyword:`assert` statements nor from setting +:const:`__debug__` to ``False``. + +.. versionchanged:: 3.8 + The :class:`io.IOBase` destructor now logs ``close()`` exceptions. + +.. versionchanged:: 3.9 + The *encoding* and *errors* arguments are now checked for string encoding + and decoding operations. + + +ResourceWarning Example +======================= + +Example of a script counting the number of lines of the text file specified in +the command line:: + + import sys + + def main(): + fp = open(sys.argv[1]) + nlines = len(fp.readlines()) + print(nlines) + # The file is closed implicitly + + if __name__ == "__main__": + main() + +The script does not close the file explicitly. By default, Python does not emit +any warning. Example using README.txt, which has 269 lines: + +.. code-block:: shell-session + + $ python3 script.py README.txt + 269 + +Enabling the Python Development Mode displays a :exc:`ResourceWarning` warning: + +.. code-block:: shell-session + + $ python3 -X dev script.py README.txt + 269 + script.py:10: ResourceWarning: unclosed file <_io.TextIOWrapper name='README.rst' mode='r' encoding='UTF-8'> + main() + ResourceWarning: Enable tracemalloc to get the object allocation traceback + +In addition, enabling :mod:`tracemalloc` shows the line where the file was +opened: + +.. code-block:: shell-session + + $ python3 -X dev -X tracemalloc=5 script.py README.rst + 269 + script.py:10: ResourceWarning: unclosed file <_io.TextIOWrapper name='README.rst' mode='r' encoding='UTF-8'> + main() + Object allocated at (most recent call last): + File "script.py", lineno 10 + main() + File "script.py", lineno 4 + fp = open(sys.argv[1]) + +The fix is to close explicitly the file. Example using a context manager:: + + def main(): + # Close the file explicitly when exiting the with block + with open(sys.argv[1]) as fp: + nlines = len(fp.readlines()) + print(nlines) + +Not closing a resource explicitly can leave a resource open for way longer than +expected; it can cause severe issues upon exiting Python. It is bad in +CPython, but it is even worse in PyPy. Closing resources explicitly makes an +application more deterministic and more reliable. + + +Bad file descriptor error example +================================= + +Script displaying the first line of itself:: + + import os + + def main(): + fp = open(__file__) + firstline = fp.readline() + print(firstline.rstrip()) + os.close(fp.fileno()) + # The file is closed implicitly + + main() + +By default, Python does not emit any warning: + +.. code-block:: shell-session + + $ python3 script.py + import os + +The Python Development Mode shows a :exc:`ResourceWarning` and logs a "Bad file +descriptor" error when finalizing the file object: + +.. code-block:: shell-session + + $ python3 script.py + import os + script.py:10: ResourceWarning: unclosed file <_io.TextIOWrapper name='script.py' mode='r' encoding='UTF-8'> + main() + ResourceWarning: Enable tracemalloc to get the object allocation traceback + Exception ignored in: <_io.TextIOWrapper name='script.py' mode='r' encoding='UTF-8'> + Traceback (most recent call last): + File "script.py", line 10, in + main() + OSError: [Errno 9] Bad file descriptor + +``os.close(fp.fileno())`` closes the file descriptor. When the file object +finalizer tries to close the file descriptor again, it fails with the ``Bad +file descriptor`` error. A file descriptor must be closed only once. In the +worst case scenario, closing it twice can lead to a crash (see :issue:`18748` +for an example). + +The fix is to remove the ``os.close(fp.fileno())`` line, or open the file with +``closefd=False``. diff --git a/cpython_2/environment/repo/Doc/library/dialog.rst b/cpython_2/environment/repo/Doc/library/dialog.rst new file mode 100644 index 0000000000000000000000000000000000000000..dc82a974ce095d8937b9a908faeb8caa8ca7a7a3 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/dialog.rst @@ -0,0 +1,230 @@ +Tkinter Dialogs +=============== + +:mod:`tkinter.simpledialog` --- Standard Tkinter input dialogs +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. module:: tkinter.simpledialog + :platform: Tk + :synopsis: Simple dialog windows + +**Source code:** :source:`Lib/tkinter/simpledialog.py` + +-------------- + +The :mod:`tkinter.simpledialog` module contains convenience classes and +functions for creating simple modal dialogs to get a value from the user. + + +.. function:: askfloat(title, prompt, **kw) + askinteger(title, prompt, **kw) + askstring(title, prompt, **kw) + + The above three functions provide dialogs that prompt the user to enter a value + of the desired type. + +.. class:: Dialog(parent, title=None) + + The base class for custom dialogs. + + .. method:: body(master) + + Override to construct the dialog's interface and return the widget that + should have initial focus. + + .. method:: buttonbox() + + Default behaviour adds OK and Cancel buttons. Override for custom button + layouts. + + + +:mod:`tkinter.filedialog` --- File selection dialogs +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. module:: tkinter.filedialog + :platform: Tk + :synopsis: Dialog classes for file selection + +**Source code:** :source:`Lib/tkinter/filedialog.py` + +-------------- + +The :mod:`tkinter.filedialog` module provides classes and factory functions for +creating file/directory selection windows. + +Native Load/Save Dialogs +------------------------ + +The following classes and functions provide file dialog windows that combine a +native look-and-feel with configuration options to customize behaviour. +The following keyword arguments are applicable to the classes and functions +listed below: + + | *parent* - the window to place the dialog on top of + + | *title* - the title of the window + + | *initialdir* - the directory that the dialog starts in + + | *initialfile* - the file selected upon opening of the dialog + + | *filetypes* - a sequence of (label, pattern) tuples, '*' wildcard is allowed + + | *defaultextension* - default extension to append to file (save dialogs) + + | *multiple* - when true, selection of multiple items is allowed + + +**Static factory functions** + +The below functions when called create a modal, native look-and-feel dialog, +wait for the user's selection, then return the selected value(s) or ``None`` to the +caller. + +.. function:: askopenfile(mode="r", **options) + askopenfiles(mode="r", **options) + + The above two functions create an :class:`Open` dialog and return the opened + file object(s) in read-only mode. + +.. function:: asksaveasfile(mode="w", **options) + + Create a :class:`SaveAs` dialog and return a file object opened in write-only mode. + +.. function:: askopenfilename(**options) + askopenfilenames(**options) + + The above two functions create an :class:`Open` dialog and return the + selected filename(s) that correspond to existing file(s). + +.. function:: asksaveasfilename(**options) + + Create a :class:`SaveAs` dialog and return the selected filename. + +.. function:: askdirectory(**options) + + | Prompt user to select a directory. + | Additional keyword option: + | *mustexist* - determines if selection must be an existing directory. + +.. class:: Open(master=None, **options) + SaveAs(master=None, **options) + + The above two classes provide native dialog windows for saving and loading + files. + +**Convenience classes** + +The below classes are used for creating file/directory windows from scratch. +These do not emulate the native look-and-feel of the platform. + +.. class:: Directory(master=None, **options) + + Create a dialog prompting the user to select a directory. + +.. note:: The *FileDialog* class should be subclassed for custom event + handling and behaviour. + +.. class:: FileDialog(master, title=None) + + Create a basic file selection dialog. + + .. method:: cancel_command(event=None) + + Trigger the termination of the dialog window. + + .. method:: dirs_double_event(event) + + Event handler for double-click event on directory. + + .. method:: dirs_select_event(event) + + Event handler for click event on directory. + + .. method:: files_double_event(event) + + Event handler for double-click event on file. + + .. method:: files_select_event(event) + + Event handler for single-click event on file. + + .. method:: filter_command(event=None) + + Filter the files by directory. + + .. method:: get_filter() + + Retrieve the file filter currently in use. + + .. method:: get_selection() + + Retrieve the currently selected item. + + .. method:: go(dir_or_file=os.curdir, pattern="*", default="", key=None) + + Render dialog and start event loop. + + .. method:: ok_event(event) + + Exit dialog returning current selection. + + .. method:: quit(how=None) + + Exit dialog returning filename, if any. + + .. method:: set_filter(dir, pat) + + Set the file filter. + + .. method:: set_selection(file) + + Update the current file selection to *file*. + + +.. class:: LoadFileDialog(master, title=None) + + A subclass of FileDialog that creates a dialog window for selecting an + existing file. + + .. method:: ok_command() + + Test that a file is provided and that the selection indicates an + already existing file. + +.. class:: SaveFileDialog(master, title=None) + + A subclass of FileDialog that creates a dialog window for selecting a + destination file. + + .. method:: ok_command() + + Test whether or not the selection points to a valid file that is not a + directory. Confirmation is required if an already existing file is + selected. + +:mod:`tkinter.commondialog` --- Dialog window templates +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. module:: tkinter.commondialog + :platform: Tk + :synopsis: Tkinter base class for dialogs + +**Source code:** :source:`Lib/tkinter/commondialog.py` + +-------------- + +The :mod:`tkinter.commondialog` module provides the :class:`Dialog` class that +is the base class for dialogs defined in other supporting modules. + +.. class:: Dialog(master=None, **options) + + .. method:: show(color=None, **options) + + Render the Dialog window. + + +.. seealso:: + + Modules :mod:`tkinter.messagebox`, :ref:`tut-files` diff --git a/cpython_2/environment/repo/Doc/library/difflib.rst b/cpython_2/environment/repo/Doc/library/difflib.rst new file mode 100644 index 0000000000000000000000000000000000000000..7a898c21b52e03b947041a6f5b08b494ecb4f548 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/difflib.rst @@ -0,0 +1,763 @@ +:mod:`difflib` --- Helpers for computing deltas +=============================================== + +.. module:: difflib + :synopsis: Helpers for computing differences between objects. + +.. moduleauthor:: Tim Peters +.. sectionauthor:: Tim Peters +.. Markup by Fred L. Drake, Jr. + +**Source code:** :source:`Lib/difflib.py` + +.. testsetup:: + + import sys + from difflib import * + +-------------- + +This module provides classes and functions for comparing sequences. It +can be used for example, for comparing files, and can produce difference +information in various formats, including HTML and context and unified +diffs. For comparing directories and files, see also, the :mod:`filecmp` module. + + +.. class:: SequenceMatcher + + This is a flexible class for comparing pairs of sequences of any type, so long + as the sequence elements are :term:`hashable`. The basic algorithm predates, and is a + little fancier than, an algorithm published in the late 1980's by Ratcliff and + Obershelp under the hyperbolic name "gestalt pattern matching." The idea is to + find the longest contiguous matching subsequence that contains no "junk" + elements; these "junk" elements are ones that are uninteresting in some + sense, such as blank lines or whitespace. (Handling junk is an + extension to the Ratcliff and Obershelp algorithm.) The same + idea is then applied recursively to the pieces of the sequences to the left and + to the right of the matching subsequence. This does not yield minimal edit + sequences, but does tend to yield matches that "look right" to people. + + **Timing:** The basic Ratcliff-Obershelp algorithm is cubic time in the worst + case and quadratic time in the expected case. :class:`SequenceMatcher` is + quadratic time for the worst case and has expected-case behavior dependent in a + complicated way on how many elements the sequences have in common; best case + time is linear. + + **Automatic junk heuristic:** :class:`SequenceMatcher` supports a heuristic that + automatically treats certain sequence items as junk. The heuristic counts how many + times each individual item appears in the sequence. If an item's duplicates (after + the first one) account for more than 1% of the sequence and the sequence is at least + 200 items long, this item is marked as "popular" and is treated as junk for + the purpose of sequence matching. This heuristic can be turned off by setting + the ``autojunk`` argument to ``False`` when creating the :class:`SequenceMatcher`. + + .. versionadded:: 3.2 + The *autojunk* parameter. + + +.. class:: Differ + + This is a class for comparing sequences of lines of text, and producing + human-readable differences or deltas. Differ uses :class:`SequenceMatcher` + both to compare sequences of lines, and to compare sequences of characters + within similar (near-matching) lines. + + Each line of a :class:`Differ` delta begins with a two-letter code: + + +----------+-------------------------------------------+ + | Code | Meaning | + +==========+===========================================+ + | ``'- '`` | line unique to sequence 1 | + +----------+-------------------------------------------+ + | ``'+ '`` | line unique to sequence 2 | + +----------+-------------------------------------------+ + | ``' '`` | line common to both sequences | + +----------+-------------------------------------------+ + | ``'? '`` | line not present in either input sequence | + +----------+-------------------------------------------+ + + Lines beginning with '``?``' attempt to guide the eye to intraline differences, + and were not present in either input sequence. These lines can be confusing if + the sequences contain tab characters. + + +.. class:: HtmlDiff + + This class can be used to create an HTML table (or a complete HTML file + containing the table) showing a side by side, line by line comparison of text + with inter-line and intra-line change highlights. The table can be generated in + either full or contextual difference mode. + + The constructor for this class is: + + + .. method:: __init__(tabsize=8, wrapcolumn=None, linejunk=None, charjunk=IS_CHARACTER_JUNK) + + Initializes instance of :class:`HtmlDiff`. + + *tabsize* is an optional keyword argument to specify tab stop spacing and + defaults to ``8``. + + *wrapcolumn* is an optional keyword to specify column number where lines are + broken and wrapped, defaults to ``None`` where lines are not wrapped. + + *linejunk* and *charjunk* are optional keyword arguments passed into :func:`ndiff` + (used by :class:`HtmlDiff` to generate the side by side HTML differences). See + :func:`ndiff` documentation for argument default values and descriptions. + + The following methods are public: + + .. method:: make_file(fromlines, tolines, fromdesc='', todesc='', context=False, \ + numlines=5, *, charset='utf-8') + + Compares *fromlines* and *tolines* (lists of strings) and returns a string which + is a complete HTML file containing a table showing line by line differences with + inter-line and intra-line changes highlighted. + + *fromdesc* and *todesc* are optional keyword arguments to specify from/to file + column header strings (both default to an empty string). + + *context* and *numlines* are both optional keyword arguments. Set *context* to + ``True`` when contextual differences are to be shown, else the default is + ``False`` to show the full files. *numlines* defaults to ``5``. When *context* + is ``True`` *numlines* controls the number of context lines which surround the + difference highlights. When *context* is ``False`` *numlines* controls the + number of lines which are shown before a difference highlight when using the + "next" hyperlinks (setting to zero would cause the "next" hyperlinks to place + the next difference highlight at the top of the browser without any leading + context). + + .. note:: + *fromdesc* and *todesc* are interpreted as unescaped HTML and should be + properly escaped while receiving input from untrusted sources. + + .. versionchanged:: 3.5 + *charset* keyword-only argument was added. The default charset of + HTML document changed from ``'ISO-8859-1'`` to ``'utf-8'``. + + .. method:: make_table(fromlines, tolines, fromdesc='', todesc='', context=False, numlines=5) + + Compares *fromlines* and *tolines* (lists of strings) and returns a string which + is a complete HTML table showing line by line differences with inter-line and + intra-line changes highlighted. + + The arguments for this method are the same as those for the :meth:`make_file` + method. + + :file:`Tools/scripts/diff.py` is a command-line front-end to this class and + contains a good example of its use. + + +.. function:: context_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\\n') + + Compare *a* and *b* (lists of strings); return a delta (a :term:`generator` + generating the delta lines) in context diff format. + + Context diffs are a compact way of showing just the lines that have changed plus + a few lines of context. The changes are shown in a before/after style. The + number of context lines is set by *n* which defaults to three. + + By default, the diff control lines (those with ``***`` or ``---``) are created + with a trailing newline. This is helpful so that inputs created from + :func:`io.IOBase.readlines` result in diffs that are suitable for use with + :func:`io.IOBase.writelines` since both the inputs and outputs have trailing + newlines. + + For inputs that do not have trailing newlines, set the *lineterm* argument to + ``""`` so that the output will be uniformly newline free. + + The context diff format normally has a header for filenames and modification + times. Any or all of these may be specified using strings for *fromfile*, + *tofile*, *fromfiledate*, and *tofiledate*. The modification times are normally + expressed in the ISO 8601 format. If not specified, the + strings default to blanks. + + >>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n'] + >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n'] + >>> sys.stdout.writelines(context_diff(s1, s2, fromfile='before.py', tofile='after.py')) + *** before.py + --- after.py + *************** + *** 1,4 **** + ! bacon + ! eggs + ! ham + guido + --- 1,4 ---- + ! python + ! eggy + ! hamster + guido + + See :ref:`difflib-interface` for a more detailed example. + + +.. function:: get_close_matches(word, possibilities, n=3, cutoff=0.6) + + Return a list of the best "good enough" matches. *word* is a sequence for which + close matches are desired (typically a string), and *possibilities* is a list of + sequences against which to match *word* (typically a list of strings). + + Optional argument *n* (default ``3``) is the maximum number of close matches to + return; *n* must be greater than ``0``. + + Optional argument *cutoff* (default ``0.6``) is a float in the range [0, 1]. + Possibilities that don't score at least that similar to *word* are ignored. + + The best (no more than *n*) matches among the possibilities are returned in a + list, sorted by similarity score, most similar first. + + >>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy']) + ['apple', 'ape'] + >>> import keyword + >>> get_close_matches('wheel', keyword.kwlist) + ['while'] + >>> get_close_matches('pineapple', keyword.kwlist) + [] + >>> get_close_matches('accept', keyword.kwlist) + ['except'] + + +.. function:: ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK) + + Compare *a* and *b* (lists of strings); return a :class:`Differ`\ -style + delta (a :term:`generator` generating the delta lines). + + Optional keyword parameters *linejunk* and *charjunk* are filtering functions + (or ``None``): + + *linejunk*: A function that accepts a single string argument, and returns + true if the string is junk, or false if not. The default is ``None``. There + is also a module-level function :func:`IS_LINE_JUNK`, which filters out lines + without visible characters, except for at most one pound character (``'#'``) + -- however the underlying :class:`SequenceMatcher` class does a dynamic + analysis of which lines are so frequent as to constitute noise, and this + usually works better than using this function. + + *charjunk*: A function that accepts a character (a string of length 1), and + returns if the character is junk, or false if not. The default is module-level + function :func:`IS_CHARACTER_JUNK`, which filters out whitespace characters (a + blank or tab; it's a bad idea to include newline in this!). + + :file:`Tools/scripts/ndiff.py` is a command-line front-end to this function. + + >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True), + ... 'ore\ntree\nemu\n'.splitlines(keepends=True)) + >>> print(''.join(diff), end="") + - one + ? ^ + + ore + ? ^ + - two + - three + ? - + + tree + + emu + + +.. function:: restore(sequence, which) + + Return one of the two sequences that generated a delta. + + Given a *sequence* produced by :meth:`Differ.compare` or :func:`ndiff`, extract + lines originating from file 1 or 2 (parameter *which*), stripping off line + prefixes. + + Example: + + >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True), + ... 'ore\ntree\nemu\n'.splitlines(keepends=True)) + >>> diff = list(diff) # materialize the generated delta into a list + >>> print(''.join(restore(diff, 1)), end="") + one + two + three + >>> print(''.join(restore(diff, 2)), end="") + ore + tree + emu + + +.. function:: unified_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\\n') + + Compare *a* and *b* (lists of strings); return a delta (a :term:`generator` + generating the delta lines) in unified diff format. + + Unified diffs are a compact way of showing just the lines that have changed plus + a few lines of context. The changes are shown in an inline style (instead of + separate before/after blocks). The number of context lines is set by *n* which + defaults to three. + + By default, the diff control lines (those with ``---``, ``+++``, or ``@@``) are + created with a trailing newline. This is helpful so that inputs created from + :func:`io.IOBase.readlines` result in diffs that are suitable for use with + :func:`io.IOBase.writelines` since both the inputs and outputs have trailing + newlines. + + For inputs that do not have trailing newlines, set the *lineterm* argument to + ``""`` so that the output will be uniformly newline free. + + The context diff format normally has a header for filenames and modification + times. Any or all of these may be specified using strings for *fromfile*, + *tofile*, *fromfiledate*, and *tofiledate*. The modification times are normally + expressed in the ISO 8601 format. If not specified, the + strings default to blanks. + + + >>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n'] + >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n'] + >>> sys.stdout.writelines(unified_diff(s1, s2, fromfile='before.py', tofile='after.py')) + --- before.py + +++ after.py + @@ -1,4 +1,4 @@ + -bacon + -eggs + -ham + +python + +eggy + +hamster + guido + + See :ref:`difflib-interface` for a more detailed example. + +.. function:: diff_bytes(dfunc, a, b, fromfile=b'', tofile=b'', fromfiledate=b'', tofiledate=b'', n=3, lineterm=b'\\n') + + Compare *a* and *b* (lists of bytes objects) using *dfunc*; yield a + sequence of delta lines (also bytes) in the format returned by *dfunc*. + *dfunc* must be a callable, typically either :func:`unified_diff` or + :func:`context_diff`. + + Allows you to compare data with unknown or inconsistent encoding. All + inputs except *n* must be bytes objects, not str. Works by losslessly + converting all inputs (except *n*) to str, and calling ``dfunc(a, b, + fromfile, tofile, fromfiledate, tofiledate, n, lineterm)``. The output of + *dfunc* is then converted back to bytes, so the delta lines that you + receive have the same unknown/inconsistent encodings as *a* and *b*. + + .. versionadded:: 3.5 + +.. function:: IS_LINE_JUNK(line) + + Return ``True`` for ignorable lines. The line *line* is ignorable if *line* is + blank or contains a single ``'#'``, otherwise it is not ignorable. Used as a + default for parameter *linejunk* in :func:`ndiff` in older versions. + + +.. function:: IS_CHARACTER_JUNK(ch) + + Return ``True`` for ignorable characters. The character *ch* is ignorable if *ch* + is a space or tab, otherwise it is not ignorable. Used as a default for + parameter *charjunk* in :func:`ndiff`. + + +.. seealso:: + + `Pattern Matching: The Gestalt Approach `_ + Discussion of a similar algorithm by John W. Ratcliff and D. E. Metzener. This + was published in `Dr. Dobb's Journal `_ in July, 1988. + + +.. _sequence-matcher: + +SequenceMatcher Objects +----------------------- + +The :class:`SequenceMatcher` class has this constructor: + + +.. class:: SequenceMatcher(isjunk=None, a='', b='', autojunk=True) + + Optional argument *isjunk* must be ``None`` (the default) or a one-argument + function that takes a sequence element and returns true if and only if the + element is "junk" and should be ignored. Passing ``None`` for *isjunk* is + equivalent to passing ``lambda x: False``; in other words, no elements are ignored. + For example, pass:: + + lambda x: x in " \t" + + if you're comparing lines as sequences of characters, and don't want to synch up + on blanks or hard tabs. + + The optional arguments *a* and *b* are sequences to be compared; both default to + empty strings. The elements of both sequences must be :term:`hashable`. + + The optional argument *autojunk* can be used to disable the automatic junk + heuristic. + + .. versionadded:: 3.2 + The *autojunk* parameter. + + SequenceMatcher objects get three data attributes: *bjunk* is the + set of elements of *b* for which *isjunk* is ``True``; *bpopular* is the set of + non-junk elements considered popular by the heuristic (if it is not + disabled); *b2j* is a dict mapping the remaining elements of *b* to a list + of positions where they occur. All three are reset whenever *b* is reset + with :meth:`set_seqs` or :meth:`set_seq2`. + + .. versionadded:: 3.2 + The *bjunk* and *bpopular* attributes. + + :class:`SequenceMatcher` objects have the following methods: + + .. method:: set_seqs(a, b) + + Set the two sequences to be compared. + + :class:`SequenceMatcher` computes and caches detailed information about the + second sequence, so if you want to compare one sequence against many + sequences, use :meth:`set_seq2` to set the commonly used sequence once and + call :meth:`set_seq1` repeatedly, once for each of the other sequences. + + + .. method:: set_seq1(a) + + Set the first sequence to be compared. The second sequence to be compared + is not changed. + + + .. method:: set_seq2(b) + + Set the second sequence to be compared. The first sequence to be compared + is not changed. + + + .. method:: find_longest_match(alo=0, ahi=None, blo=0, bhi=None) + + Find longest matching block in ``a[alo:ahi]`` and ``b[blo:bhi]``. + + If *isjunk* was omitted or ``None``, :meth:`find_longest_match` returns + ``(i, j, k)`` such that ``a[i:i+k]`` is equal to ``b[j:j+k]``, where ``alo + <= i <= i+k <= ahi`` and ``blo <= j <= j+k <= bhi``. For all ``(i', j', + k')`` meeting those conditions, the additional conditions ``k >= k'``, ``i + <= i'``, and if ``i == i'``, ``j <= j'`` are also met. In other words, of + all maximal matching blocks, return one that starts earliest in *a*, and + of all those maximal matching blocks that start earliest in *a*, return + the one that starts earliest in *b*. + + >>> s = SequenceMatcher(None, " abcd", "abcd abcd") + >>> s.find_longest_match(0, 5, 0, 9) + Match(a=0, b=4, size=5) + + If *isjunk* was provided, first the longest matching block is determined + as above, but with the additional restriction that no junk element appears + in the block. Then that block is extended as far as possible by matching + (only) junk elements on both sides. So the resulting block never matches + on junk except as identical junk happens to be adjacent to an interesting + match. + + Here's the same example as before, but considering blanks to be junk. That + prevents ``' abcd'`` from matching the ``' abcd'`` at the tail end of the + second sequence directly. Instead only the ``'abcd'`` can match, and + matches the leftmost ``'abcd'`` in the second sequence: + + >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd") + >>> s.find_longest_match(0, 5, 0, 9) + Match(a=1, b=0, size=4) + + If no blocks match, this returns ``(alo, blo, 0)``. + + This method returns a :term:`named tuple` ``Match(a, b, size)``. + + .. versionchanged:: 3.9 + Added default arguments. + + + .. method:: get_matching_blocks() + + Return list of triples describing non-overlapping matching subsequences. + Each triple is of the form ``(i, j, n)``, + and means that ``a[i:i+n] == b[j:j+n]``. The + triples are monotonically increasing in *i* and *j*. + + The last triple is a dummy, and has the value ``(len(a), len(b), 0)``. It + is the only triple with ``n == 0``. If ``(i, j, n)`` and ``(i', j', n')`` + are adjacent triples in the list, and the second is not the last triple in + the list, then ``i+n < i'`` or ``j+n < j'``; in other words, adjacent + triples always describe non-adjacent equal blocks. + + .. XXX Explain why a dummy is used! + + .. doctest:: + + >>> s = SequenceMatcher(None, "abxcd", "abcd") + >>> s.get_matching_blocks() + [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)] + + + .. method:: get_opcodes() + + Return list of 5-tuples describing how to turn *a* into *b*. Each tuple is + of the form ``(tag, i1, i2, j1, j2)``. The first tuple has ``i1 == j1 == + 0``, and remaining tuples have *i1* equal to the *i2* from the preceding + tuple, and, likewise, *j1* equal to the previous *j2*. + + The *tag* values are strings, with these meanings: + + +---------------+---------------------------------------------+ + | Value | Meaning | + +===============+=============================================+ + | ``'replace'`` | ``a[i1:i2]`` should be replaced by | + | | ``b[j1:j2]``. | + +---------------+---------------------------------------------+ + | ``'delete'`` | ``a[i1:i2]`` should be deleted. Note that | + | | ``j1 == j2`` in this case. | + +---------------+---------------------------------------------+ + | ``'insert'`` | ``b[j1:j2]`` should be inserted at | + | | ``a[i1:i1]``. Note that ``i1 == i2`` in | + | | this case. | + +---------------+---------------------------------------------+ + | ``'equal'`` | ``a[i1:i2] == b[j1:j2]`` (the sub-sequences | + | | are equal). | + +---------------+---------------------------------------------+ + + For example:: + + >>> a = "qabxcd" + >>> b = "abycdf" + >>> s = SequenceMatcher(None, a, b) + >>> for tag, i1, i2, j1, j2 in s.get_opcodes(): + ... print('{:7} a[{}:{}] --> b[{}:{}] {!r:>8} --> {!r}'.format( + ... tag, i1, i2, j1, j2, a[i1:i2], b[j1:j2])) + delete a[0:1] --> b[0:0] 'q' --> '' + equal a[1:3] --> b[0:2] 'ab' --> 'ab' + replace a[3:4] --> b[2:3] 'x' --> 'y' + equal a[4:6] --> b[3:5] 'cd' --> 'cd' + insert a[6:6] --> b[5:6] '' --> 'f' + + + .. method:: get_grouped_opcodes(n=3) + + Return a :term:`generator` of groups with up to *n* lines of context. + + Starting with the groups returned by :meth:`get_opcodes`, this method + splits out smaller change clusters and eliminates intervening ranges which + have no changes. + + The groups are returned in the same format as :meth:`get_opcodes`. + + + .. method:: ratio() + + Return a measure of the sequences' similarity as a float in the range [0, + 1]. + + Where T is the total number of elements in both sequences, and M is the + number of matches, this is 2.0\*M / T. Note that this is ``1.0`` if the + sequences are identical, and ``0.0`` if they have nothing in common. + + This is expensive to compute if :meth:`get_matching_blocks` or + :meth:`get_opcodes` hasn't already been called, in which case you may want + to try :meth:`quick_ratio` or :meth:`real_quick_ratio` first to get an + upper bound. + + .. note:: + + Caution: The result of a :meth:`ratio` call may depend on the order of + the arguments. For instance:: + + >>> SequenceMatcher(None, 'tide', 'diet').ratio() + 0.25 + >>> SequenceMatcher(None, 'diet', 'tide').ratio() + 0.5 + + + .. method:: quick_ratio() + + Return an upper bound on :meth:`ratio` relatively quickly. + + + .. method:: real_quick_ratio() + + Return an upper bound on :meth:`ratio` very quickly. + + +The three methods that return the ratio of matching to total characters can give +different results due to differing levels of approximation, although +:meth:`quick_ratio` and :meth:`real_quick_ratio` are always at least as large as +:meth:`ratio`: + + >>> s = SequenceMatcher(None, "abcd", "bcde") + >>> s.ratio() + 0.75 + >>> s.quick_ratio() + 0.75 + >>> s.real_quick_ratio() + 1.0 + + +.. _sequencematcher-examples: + +SequenceMatcher Examples +------------------------ + +This example compares two strings, considering blanks to be "junk": + + >>> s = SequenceMatcher(lambda x: x == " ", + ... "private Thread currentThread;", + ... "private volatile Thread currentThread;") + +:meth:`ratio` returns a float in [0, 1], measuring the similarity of the +sequences. As a rule of thumb, a :meth:`ratio` value over 0.6 means the +sequences are close matches: + + >>> print(round(s.ratio(), 3)) + 0.866 + +If you're only interested in where the sequences match, +:meth:`get_matching_blocks` is handy: + + >>> for block in s.get_matching_blocks(): + ... print("a[%d] and b[%d] match for %d elements" % block) + a[0] and b[0] match for 8 elements + a[8] and b[17] match for 21 elements + a[29] and b[38] match for 0 elements + +Note that the last tuple returned by :meth:`get_matching_blocks` is always a +dummy, ``(len(a), len(b), 0)``, and this is the only case in which the last +tuple element (number of elements matched) is ``0``. + +If you want to know how to change the first sequence into the second, use +:meth:`get_opcodes`: + + >>> for opcode in s.get_opcodes(): + ... print("%6s a[%d:%d] b[%d:%d]" % opcode) + equal a[0:8] b[0:8] + insert a[8:8] b[8:17] + equal a[8:29] b[17:38] + +.. seealso:: + + * The :func:`get_close_matches` function in this module which shows how + simple code building on :class:`SequenceMatcher` can be used to do useful + work. + + * `Simple version control recipe + `_ for a small application + built with :class:`SequenceMatcher`. + + +.. _differ-objects: + +Differ Objects +-------------- + +Note that :class:`Differ`\ -generated deltas make no claim to be **minimal** +diffs. To the contrary, minimal diffs are often counter-intuitive, because they +synch up anywhere possible, sometimes accidental matches 100 pages apart. +Restricting synch points to contiguous matches preserves some notion of +locality, at the occasional cost of producing a longer diff. + +The :class:`Differ` class has this constructor: + + +.. class:: Differ(linejunk=None, charjunk=None) + + Optional keyword parameters *linejunk* and *charjunk* are for filter functions + (or ``None``): + + *linejunk*: A function that accepts a single string argument, and returns true + if the string is junk. The default is ``None``, meaning that no line is + considered junk. + + *charjunk*: A function that accepts a single character argument (a string of + length 1), and returns true if the character is junk. The default is ``None``, + meaning that no character is considered junk. + + These junk-filtering functions speed up matching to find + differences and do not cause any differing lines or characters to + be ignored. Read the description of the + :meth:`~SequenceMatcher.find_longest_match` method's *isjunk* + parameter for an explanation. + + :class:`Differ` objects are used (deltas generated) via a single method: + + + .. method:: Differ.compare(a, b) + + Compare two sequences of lines, and generate the delta (a sequence of lines). + + Each sequence must contain individual single-line strings ending with + newlines. Such sequences can be obtained from the + :meth:`~io.IOBase.readlines` method of file-like objects. The delta + generated also consists of newline-terminated strings, ready to be + printed as-is via the :meth:`~io.IOBase.writelines` method of a + file-like object. + + +.. _differ-examples: + +Differ Example +-------------- + +This example compares two texts. First we set up the texts, sequences of +individual single-line strings ending with newlines (such sequences can also be +obtained from the :meth:`~io.BaseIO.readlines` method of file-like objects): + + >>> text1 = ''' 1. Beautiful is better than ugly. + ... 2. Explicit is better than implicit. + ... 3. Simple is better than complex. + ... 4. Complex is better than complicated. + ... '''.splitlines(keepends=True) + >>> len(text1) + 4 + >>> text1[0][-1] + '\n' + >>> text2 = ''' 1. Beautiful is better than ugly. + ... 3. Simple is better than complex. + ... 4. Complicated is better than complex. + ... 5. Flat is better than nested. + ... '''.splitlines(keepends=True) + +Next we instantiate a Differ object: + + >>> d = Differ() + +Note that when instantiating a :class:`Differ` object we may pass functions to +filter out line and character "junk." See the :meth:`Differ` constructor for +details. + +Finally, we compare the two: + + >>> result = list(d.compare(text1, text2)) + +``result`` is a list of strings, so let's pretty-print it: + + >>> from pprint import pprint + >>> pprint(result) + [' 1. Beautiful is better than ugly.\n', + '- 2. Explicit is better than implicit.\n', + '- 3. Simple is better than complex.\n', + '+ 3. Simple is better than complex.\n', + '? ++\n', + '- 4. Complex is better than complicated.\n', + '? ^ ---- ^\n', + '+ 4. Complicated is better than complex.\n', + '? ++++ ^ ^\n', + '+ 5. Flat is better than nested.\n'] + +As a single multi-line string it looks like this: + + >>> import sys + >>> sys.stdout.writelines(result) + 1. Beautiful is better than ugly. + - 2. Explicit is better than implicit. + - 3. Simple is better than complex. + + 3. Simple is better than complex. + ? ++ + - 4. Complex is better than complicated. + ? ^ ---- ^ + + 4. Complicated is better than complex. + ? ++++ ^ ^ + + 5. Flat is better than nested. + + +.. _difflib-interface: + +A command-line interface to difflib +----------------------------------- + +This example shows how to use difflib to create a ``diff``-like utility. +It is also contained in the Python source distribution, as +:file:`Tools/scripts/diff.py`. + +.. literalinclude:: ../../Tools/scripts/diff.py diff --git a/cpython_2/environment/repo/Doc/library/dis.rst b/cpython_2/environment/repo/Doc/library/dis.rst new file mode 100644 index 0000000000000000000000000000000000000000..f871ec4f13def8b15f2a2f318101339a2eabc78a --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/dis.rst @@ -0,0 +1,1261 @@ +:mod:`dis` --- Disassembler for Python bytecode +=============================================== + +.. module:: dis + :synopsis: Disassembler for Python bytecode. + +**Source code:** :source:`Lib/dis.py` + +-------------- + +The :mod:`dis` module supports the analysis of CPython :term:`bytecode` by +disassembling it. The CPython bytecode which this module takes as an input is +defined in the file :file:`Include/opcode.h` and used by the compiler and the +interpreter. + +.. impl-detail:: + + Bytecode is an implementation detail of the CPython interpreter. No + guarantees are made that bytecode will not be added, removed, or changed + between versions of Python. Use of this module should not be considered to + work across Python VMs or Python releases. + + .. versionchanged:: 3.6 + Use 2 bytes for each instruction. Previously the number of bytes varied + by instruction. + + +Example: Given the function :func:`myfunc`:: + + def myfunc(alist): + return len(alist) + +the following command can be used to display the disassembly of +:func:`myfunc`:: + + >>> dis.dis(myfunc) + 2 0 LOAD_GLOBAL 0 (len) + 2 LOAD_FAST 0 (alist) + 4 CALL_FUNCTION 1 + 6 RETURN_VALUE + +(The "2" is a line number). + +Bytecode analysis +----------------- + +.. versionadded:: 3.4 + +The bytecode analysis API allows pieces of Python code to be wrapped in a +:class:`Bytecode` object that provides easy access to details of the compiled +code. + +.. class:: Bytecode(x, *, first_line=None, current_offset=None) + + + Analyse the bytecode corresponding to a function, generator, asynchronous + generator, coroutine, method, string of source code, or a code object (as + returned by :func:`compile`). + + This is a convenience wrapper around many of the functions listed below, most + notably :func:`get_instructions`, as iterating over a :class:`Bytecode` + instance yields the bytecode operations as :class:`Instruction` instances. + + If *first_line* is not ``None``, it indicates the line number that should be + reported for the first source line in the disassembled code. Otherwise, the + source line information (if any) is taken directly from the disassembled code + object. + + If *current_offset* is not ``None``, it refers to an instruction offset in the + disassembled code. Setting this means :meth:`.dis` will display a "current + instruction" marker against the specified opcode. + + .. classmethod:: from_traceback(tb) + + Construct a :class:`Bytecode` instance from the given traceback, setting + *current_offset* to the instruction responsible for the exception. + + .. data:: codeobj + + The compiled code object. + + .. data:: first_line + + The first source line of the code object (if available) + + .. method:: dis() + + Return a formatted view of the bytecode operations (the same as printed by + :func:`dis.dis`, but returned as a multi-line string). + + .. method:: info() + + Return a formatted multi-line string with detailed information about the + code object, like :func:`code_info`. + + .. versionchanged:: 3.7 + This can now handle coroutine and asynchronous generator objects. + +Example:: + + >>> bytecode = dis.Bytecode(myfunc) + >>> for instr in bytecode: + ... print(instr.opname) + ... + LOAD_GLOBAL + LOAD_FAST + CALL_FUNCTION + RETURN_VALUE + + +Analysis functions +------------------ + +The :mod:`dis` module also defines the following analysis functions that convert +the input directly to the desired output. They can be useful if only a single +operation is being performed, so the intermediate analysis object isn't useful: + +.. function:: code_info(x) + + Return a formatted multi-line string with detailed code object information + for the supplied function, generator, asynchronous generator, coroutine, + method, source code string or code object. + + Note that the exact contents of code info strings are highly implementation + dependent and they may change arbitrarily across Python VMs or Python + releases. + + .. versionadded:: 3.2 + + .. versionchanged:: 3.7 + This can now handle coroutine and asynchronous generator objects. + + +.. function:: show_code(x, *, file=None) + + Print detailed code object information for the supplied function, method, + source code string or code object to *file* (or ``sys.stdout`` if *file* + is not specified). + + This is a convenient shorthand for ``print(code_info(x), file=file)``, + intended for interactive exploration at the interpreter prompt. + + .. versionadded:: 3.2 + + .. versionchanged:: 3.4 + Added *file* parameter. + + +.. function:: dis(x=None, *, file=None, depth=None) + + Disassemble the *x* object. *x* can denote either a module, a class, a + method, a function, a generator, an asynchronous generator, a coroutine, + a code object, a string of source code or a byte sequence of raw bytecode. + For a module, it disassembles all functions. For a class, it disassembles + all methods (including class and static methods). For a code object or + sequence of raw bytecode, it prints one line per bytecode instruction. + It also recursively disassembles nested code objects (the code of + comprehensions, generator expressions and nested functions, and the code + used for building nested classes). + Strings are first compiled to code objects with the :func:`compile` + built-in function before being disassembled. If no object is provided, this + function disassembles the last traceback. + + The disassembly is written as text to the supplied *file* argument if + provided and to ``sys.stdout`` otherwise. + + The maximal depth of recursion is limited by *depth* unless it is ``None``. + ``depth=0`` means no recursion. + + .. versionchanged:: 3.4 + Added *file* parameter. + + .. versionchanged:: 3.7 + Implemented recursive disassembling and added *depth* parameter. + + .. versionchanged:: 3.7 + This can now handle coroutine and asynchronous generator objects. + + +.. function:: distb(tb=None, *, file=None) + + Disassemble the top-of-stack function of a traceback, using the last + traceback if none was passed. The instruction causing the exception is + indicated. + + The disassembly is written as text to the supplied *file* argument if + provided and to ``sys.stdout`` otherwise. + + .. versionchanged:: 3.4 + Added *file* parameter. + + +.. function:: disassemble(code, lasti=-1, *, file=None) + disco(code, lasti=-1, *, file=None) + + Disassemble a code object, indicating the last instruction if *lasti* was + provided. The output is divided in the following columns: + + #. the line number, for the first instruction of each line + #. the current instruction, indicated as ``-->``, + #. a labelled instruction, indicated with ``>>``, + #. the address of the instruction, + #. the operation code name, + #. operation parameters, and + #. interpretation of the parameters in parentheses. + + The parameter interpretation recognizes local and global variable names, + constant values, branch targets, and compare operators. + + The disassembly is written as text to the supplied *file* argument if + provided and to ``sys.stdout`` otherwise. + + .. versionchanged:: 3.4 + Added *file* parameter. + + +.. function:: get_instructions(x, *, first_line=None) + + Return an iterator over the instructions in the supplied function, method, + source code string or code object. + + The iterator generates a series of :class:`Instruction` named tuples giving + the details of each operation in the supplied code. + + If *first_line* is not ``None``, it indicates the line number that should be + reported for the first source line in the disassembled code. Otherwise, the + source line information (if any) is taken directly from the disassembled code + object. + + .. versionadded:: 3.4 + + +.. function:: findlinestarts(code) + + This generator function uses the ``co_firstlineno`` and ``co_lnotab`` + attributes of the code object *code* to find the offsets which are starts of + lines in the source code. They are generated as ``(offset, lineno)`` pairs. + See :source:`Objects/lnotab_notes.txt` for the ``co_lnotab`` format and + how to decode it. + + .. versionchanged:: 3.6 + Line numbers can be decreasing. Before, they were always increasing. + + +.. function:: findlabels(code) + + Detect all offsets in the raw compiled bytecode string *code* which are jump targets, and + return a list of these offsets. + + +.. function:: stack_effect(opcode, oparg=None, *, jump=None) + + Compute the stack effect of *opcode* with argument *oparg*. + + If the code has a jump target and *jump* is ``True``, :func:`~stack_effect` + will return the stack effect of jumping. If *jump* is ``False``, + it will return the stack effect of not jumping. And if *jump* is + ``None`` (default), it will return the maximal stack effect of both cases. + + .. versionadded:: 3.4 + + .. versionchanged:: 3.8 + Added *jump* parameter. + + +.. _bytecodes: + +Python Bytecode Instructions +---------------------------- + +The :func:`get_instructions` function and :class:`Bytecode` class provide +details of bytecode instructions as :class:`Instruction` instances: + +.. class:: Instruction + + Details for a bytecode operation + + .. data:: opcode + + numeric code for operation, corresponding to the opcode values listed + below and the bytecode values in the :ref:`opcode_collections`. + + + .. data:: opname + + human readable name for operation + + + .. data:: arg + + numeric argument to operation (if any), otherwise ``None`` + + + .. data:: argval + + resolved arg value (if known), otherwise same as arg + + + .. data:: argrepr + + human readable description of operation argument + + + .. data:: offset + + start index of operation within bytecode sequence + + + .. data:: starts_line + + line started by this opcode (if any), otherwise ``None`` + + + .. data:: is_jump_target + + ``True`` if other code jumps to here, otherwise ``False`` + + .. versionadded:: 3.4 + + +The Python compiler currently generates the following bytecode instructions. + + +**General instructions** + +.. opcode:: NOP + + Do nothing code. Used as a placeholder by the bytecode optimizer. + + +.. opcode:: POP_TOP + + Removes the top-of-stack (TOS) item. + + +.. opcode:: ROT_TWO + + Swaps the two top-most stack items. + + +.. opcode:: ROT_THREE + + Lifts second and third stack item one position up, moves top down to position + three. + + +.. opcode:: ROT_FOUR + + Lifts second, third and forth stack items one position up, moves top down + to position four. + + .. versionadded:: 3.8 + + +.. opcode:: DUP_TOP + + Duplicates the reference on top of the stack. + + .. versionadded:: 3.2 + + +.. opcode:: DUP_TOP_TWO + + Duplicates the two references on top of the stack, leaving them in the + same order. + + .. versionadded:: 3.2 + + +**Unary operations** + +Unary operations take the top of the stack, apply the operation, and push the +result back on the stack. + +.. opcode:: UNARY_POSITIVE + + Implements ``TOS = +TOS``. + + +.. opcode:: UNARY_NEGATIVE + + Implements ``TOS = -TOS``. + + +.. opcode:: UNARY_NOT + + Implements ``TOS = not TOS``. + + +.. opcode:: UNARY_INVERT + + Implements ``TOS = ~TOS``. + + +.. opcode:: GET_ITER + + Implements ``TOS = iter(TOS)``. + + +.. opcode:: GET_YIELD_FROM_ITER + + If ``TOS`` is a :term:`generator iterator` or :term:`coroutine` object + it is left as is. Otherwise, implements ``TOS = iter(TOS)``. + + .. versionadded:: 3.5 + + +**Binary operations** + +Binary operations remove the top of the stack (TOS) and the second top-most +stack item (TOS1) from the stack. They perform the operation, and put the +result back on the stack. + +.. opcode:: BINARY_POWER + + Implements ``TOS = TOS1 ** TOS``. + + +.. opcode:: BINARY_MULTIPLY + + Implements ``TOS = TOS1 * TOS``. + + +.. opcode:: BINARY_MATRIX_MULTIPLY + + Implements ``TOS = TOS1 @ TOS``. + + .. versionadded:: 3.5 + + +.. opcode:: BINARY_FLOOR_DIVIDE + + Implements ``TOS = TOS1 // TOS``. + + +.. opcode:: BINARY_TRUE_DIVIDE + + Implements ``TOS = TOS1 / TOS``. + + +.. opcode:: BINARY_MODULO + + Implements ``TOS = TOS1 % TOS``. + + +.. opcode:: BINARY_ADD + + Implements ``TOS = TOS1 + TOS``. + + +.. opcode:: BINARY_SUBTRACT + + Implements ``TOS = TOS1 - TOS``. + + +.. opcode:: BINARY_SUBSCR + + Implements ``TOS = TOS1[TOS]``. + + +.. opcode:: BINARY_LSHIFT + + Implements ``TOS = TOS1 << TOS``. + + +.. opcode:: BINARY_RSHIFT + + Implements ``TOS = TOS1 >> TOS``. + + +.. opcode:: BINARY_AND + + Implements ``TOS = TOS1 & TOS``. + + +.. opcode:: BINARY_XOR + + Implements ``TOS = TOS1 ^ TOS``. + + +.. opcode:: BINARY_OR + + Implements ``TOS = TOS1 | TOS``. + + +**In-place operations** + +In-place operations are like binary operations, in that they remove TOS and +TOS1, and push the result back on the stack, but the operation is done in-place +when TOS1 supports it, and the resulting TOS may be (but does not have to be) +the original TOS1. + +.. opcode:: INPLACE_POWER + + Implements in-place ``TOS = TOS1 ** TOS``. + + +.. opcode:: INPLACE_MULTIPLY + + Implements in-place ``TOS = TOS1 * TOS``. + + +.. opcode:: INPLACE_MATRIX_MULTIPLY + + Implements in-place ``TOS = TOS1 @ TOS``. + + .. versionadded:: 3.5 + + +.. opcode:: INPLACE_FLOOR_DIVIDE + + Implements in-place ``TOS = TOS1 // TOS``. + + +.. opcode:: INPLACE_TRUE_DIVIDE + + Implements in-place ``TOS = TOS1 / TOS``. + + +.. opcode:: INPLACE_MODULO + + Implements in-place ``TOS = TOS1 % TOS``. + + +.. opcode:: INPLACE_ADD + + Implements in-place ``TOS = TOS1 + TOS``. + + +.. opcode:: INPLACE_SUBTRACT + + Implements in-place ``TOS = TOS1 - TOS``. + + +.. opcode:: INPLACE_LSHIFT + + Implements in-place ``TOS = TOS1 << TOS``. + + +.. opcode:: INPLACE_RSHIFT + + Implements in-place ``TOS = TOS1 >> TOS``. + + +.. opcode:: INPLACE_AND + + Implements in-place ``TOS = TOS1 & TOS``. + + +.. opcode:: INPLACE_XOR + + Implements in-place ``TOS = TOS1 ^ TOS``. + + +.. opcode:: INPLACE_OR + + Implements in-place ``TOS = TOS1 | TOS``. + + +.. opcode:: STORE_SUBSCR + + Implements ``TOS1[TOS] = TOS2``. + + +.. opcode:: DELETE_SUBSCR + + Implements ``del TOS1[TOS]``. + + +**Coroutine opcodes** + +.. opcode:: GET_AWAITABLE + + Implements ``TOS = get_awaitable(TOS)``, where ``get_awaitable(o)`` + returns ``o`` if ``o`` is a coroutine object or a generator object with + the CO_ITERABLE_COROUTINE flag, or resolves + ``o.__await__``. + + .. versionadded:: 3.5 + + +.. opcode:: GET_AITER + + Implements ``TOS = TOS.__aiter__()``. + + .. versionadded:: 3.5 + .. versionchanged:: 3.7 + Returning awaitable objects from ``__aiter__`` is no longer + supported. + + +.. opcode:: GET_ANEXT + + Implements ``PUSH(get_awaitable(TOS.__anext__()))``. See ``GET_AWAITABLE`` + for details about ``get_awaitable`` + + .. versionadded:: 3.5 + + +.. opcode:: END_ASYNC_FOR + + Terminates an :keyword:`async for` loop. Handles an exception raised + when awaiting a next item. If TOS is :exc:`StopAsyncIteration` pop 7 + values from the stack and restore the exception state using the second + three of them. Otherwise re-raise the exception using the three values + from the stack. An exception handler block is removed from the block stack. + + .. versionadded:: 3.8 + + +.. opcode:: BEFORE_ASYNC_WITH + + Resolves ``__aenter__`` and ``__aexit__`` from the object on top of the + stack. Pushes ``__aexit__`` and result of ``__aenter__()`` to the stack. + + .. versionadded:: 3.5 + + +.. opcode:: SETUP_ASYNC_WITH + + Creates a new frame object. + + .. versionadded:: 3.5 + + + +**Miscellaneous opcodes** + +.. opcode:: PRINT_EXPR + + Implements the expression statement for the interactive mode. TOS is removed + from the stack and printed. In non-interactive mode, an expression statement + is terminated with :opcode:`POP_TOP`. + + +.. opcode:: SET_ADD (i) + + Calls ``set.add(TOS1[-i], TOS)``. Used to implement set comprehensions. + + +.. opcode:: LIST_APPEND (i) + + Calls ``list.append(TOS[-i], TOS)``. Used to implement list comprehensions. + + +.. opcode:: MAP_ADD (i) + + Calls ``dict.__setitem__(TOS1[-i], TOS1, TOS)``. Used to implement dict + comprehensions. + + .. versionadded:: 3.1 + .. versionchanged:: 3.8 + Map value is TOS and map key is TOS1. Before, those were reversed. + +For all of the :opcode:`SET_ADD`, :opcode:`LIST_APPEND` and :opcode:`MAP_ADD` +instructions, while the added value or key/value pair is popped off, the +container object remains on the stack so that it is available for further +iterations of the loop. + + +.. opcode:: RETURN_VALUE + + Returns with TOS to the caller of the function. + + +.. opcode:: YIELD_VALUE + + Pops TOS and yields it from a :term:`generator`. + + +.. opcode:: YIELD_FROM + + Pops TOS and delegates to it as a subiterator from a :term:`generator`. + + .. versionadded:: 3.3 + + +.. opcode:: SETUP_ANNOTATIONS + + Checks whether ``__annotations__`` is defined in ``locals()``, if not it is + set up to an empty ``dict``. This opcode is only emitted if a class + or module body contains :term:`variable annotations ` + statically. + + .. versionadded:: 3.6 + + +.. opcode:: IMPORT_STAR + + Loads all symbols not starting with ``'_'`` directly from the module TOS to + the local namespace. The module is popped after loading all names. This + opcode implements ``from module import *``. + + +.. opcode:: POP_BLOCK + + Removes one block from the block stack. Per frame, there is a stack of + blocks, denoting :keyword:`try` statements, and such. + + +.. opcode:: POP_EXCEPT + + Removes one block from the block stack. The popped block must be an exception + handler block, as implicitly created when entering an except handler. In + addition to popping extraneous values from the frame stack, the last three + popped values are used to restore the exception state. + + +.. opcode:: RERAISE + + Re-raises the exception currently on top of the stack. + + .. versionadded:: 3.9 + + +.. opcode:: WITH_EXCEPT_START + + Calls the function in position 7 on the stack with the top three + items on the stack as arguments. + Used to implement the call ``context_manager.__exit__(*exc_info())`` when an exception + has occurred in a :keyword:`with` statement. + + .. versionadded:: 3.9 + + +.. opcode:: LOAD_ASSERTION_ERROR + + Pushes :exc:`AssertionError` onto the stack. Used by the :keyword:`assert` + statement. + + .. versionadded:: 3.9 + + +.. opcode:: LOAD_BUILD_CLASS + + Pushes :func:`builtins.__build_class__` onto the stack. It is later called + by :opcode:`CALL_FUNCTION` to construct a class. + + +.. opcode:: SETUP_WITH (delta) + + This opcode performs several operations before a with block starts. First, + it loads :meth:`~object.__exit__` from the context manager and pushes it onto + the stack for later use by :opcode:`WITH_CLEANUP_START`. Then, + :meth:`~object.__enter__` is called, and a finally block pointing to *delta* + is pushed. Finally, the result of calling the ``__enter__()`` method is pushed onto + the stack. The next opcode will either ignore it (:opcode:`POP_TOP`), or + store it in (a) variable(s) (:opcode:`STORE_FAST`, :opcode:`STORE_NAME`, or + :opcode:`UNPACK_SEQUENCE`). + + .. versionadded:: 3.2 + + +All of the following opcodes use their arguments. + +.. opcode:: STORE_NAME (namei) + + Implements ``name = TOS``. *namei* is the index of *name* in the attribute + :attr:`co_names` of the code object. The compiler tries to use + :opcode:`STORE_FAST` or :opcode:`STORE_GLOBAL` if possible. + + +.. opcode:: DELETE_NAME (namei) + + Implements ``del name``, where *namei* is the index into :attr:`co_names` + attribute of the code object. + + +.. opcode:: UNPACK_SEQUENCE (count) + + Unpacks TOS into *count* individual values, which are put onto the stack + right-to-left. + + +.. opcode:: UNPACK_EX (counts) + + Implements assignment with a starred target: Unpacks an iterable in TOS into + individual values, where the total number of values can be smaller than the + number of items in the iterable: one of the new values will be a list of all + leftover items. + + The low byte of *counts* is the number of values before the list value, the + high byte of *counts* the number of values after it. The resulting values + are put onto the stack right-to-left. + + +.. opcode:: STORE_ATTR (namei) + + Implements ``TOS.name = TOS1``, where *namei* is the index of name in + :attr:`co_names`. + + +.. opcode:: DELETE_ATTR (namei) + + Implements ``del TOS.name``, using *namei* as index into :attr:`co_names`. + + +.. opcode:: STORE_GLOBAL (namei) + + Works as :opcode:`STORE_NAME`, but stores the name as a global. + + +.. opcode:: DELETE_GLOBAL (namei) + + Works as :opcode:`DELETE_NAME`, but deletes a global name. + + +.. opcode:: LOAD_CONST (consti) + + Pushes ``co_consts[consti]`` onto the stack. + + +.. opcode:: LOAD_NAME (namei) + + Pushes the value associated with ``co_names[namei]`` onto the stack. + + +.. opcode:: BUILD_TUPLE (count) + + Creates a tuple consuming *count* items from the stack, and pushes the + resulting tuple onto the stack. + + +.. opcode:: BUILD_LIST (count) + + Works as :opcode:`BUILD_TUPLE`, but creates a list. + + +.. opcode:: BUILD_SET (count) + + Works as :opcode:`BUILD_TUPLE`, but creates a set. + + +.. opcode:: BUILD_MAP (count) + + Pushes a new dictionary object onto the stack. Pops ``2 * count`` items + so that the dictionary holds *count* entries: + ``{..., TOS3: TOS2, TOS1: TOS}``. + + .. versionchanged:: 3.5 + The dictionary is created from stack items instead of creating an + empty dictionary pre-sized to hold *count* items. + + +.. opcode:: BUILD_CONST_KEY_MAP (count) + + The version of :opcode:`BUILD_MAP` specialized for constant keys. Pops the + top element on the stack which contains a tuple of keys, then starting from + ``TOS1``, pops *count* values to form values in the built dictionary. + + .. versionadded:: 3.6 + + +.. opcode:: BUILD_STRING (count) + + Concatenates *count* strings from the stack and pushes the resulting string + onto the stack. + + .. versionadded:: 3.6 + + +.. opcode:: LIST_TO_TUPLE + + Pops a list from the stack and pushes a tuple containing the same values. + + .. versionadded:: 3.9 + + +.. opcode:: LIST_EXTEND (i) + + Calls ``list.extend(TOS1[-i], TOS)``. Used to build lists. + + .. versionadded:: 3.9 + + +.. opcode:: SET_UPDATE (i) + + Calls ``set.update(TOS1[-i], TOS)``. Used to build sets. + + .. versionadded:: 3.9 + + +.. opcode:: DICT_UPDATE (i) + + Calls ``dict.update(TOS1[-i], TOS)``. Used to build dicts. + + .. versionadded:: 3.9 + + +.. opcode:: DICT_MERGE + + Like :opcode:`DICT_UPDATE` but raises an exception for duplicate keys. + + .. versionadded:: 3.9 + + +.. opcode:: LOAD_ATTR (namei) + + Replaces TOS with ``getattr(TOS, co_names[namei])``. + + +.. opcode:: COMPARE_OP (opname) + + Performs a Boolean operation. The operation name can be found in + ``cmp_op[opname]``. + + +.. opcode:: IS_OP (invert) + + Performs ``is`` comparison, or ``is not`` if ``invert`` is 1. + + .. versionadded:: 3.9 + + +.. opcode:: CONTAINS_OP (invert) + + Performs ``in`` comparison, or ``not in`` if ``invert`` is 1. + + .. versionadded:: 3.9 + + +.. opcode:: IMPORT_NAME (namei) + + Imports the module ``co_names[namei]``. TOS and TOS1 are popped and provide + the *fromlist* and *level* arguments of :func:`__import__`. The module + object is pushed onto the stack. The current namespace is not affected: for + a proper import statement, a subsequent :opcode:`STORE_FAST` instruction + modifies the namespace. + + +.. opcode:: IMPORT_FROM (namei) + + Loads the attribute ``co_names[namei]`` from the module found in TOS. The + resulting object is pushed onto the stack, to be subsequently stored by a + :opcode:`STORE_FAST` instruction. + + +.. opcode:: JUMP_FORWARD (delta) + + Increments bytecode counter by *delta*. + + +.. opcode:: POP_JUMP_IF_TRUE (target) + + If TOS is true, sets the bytecode counter to *target*. TOS is popped. + + .. versionadded:: 3.1 + + +.. opcode:: POP_JUMP_IF_FALSE (target) + + If TOS is false, sets the bytecode counter to *target*. TOS is popped. + + .. versionadded:: 3.1 + +.. opcode:: JUMP_IF_NOT_EXC_MATCH (target) + + Tests whether the second value on the stack is an exception matching TOS, + and jumps if it is not. Pops two values from the stack. + + .. versionadded:: 3.9 + + +.. opcode:: JUMP_IF_TRUE_OR_POP (target) + + If TOS is true, sets the bytecode counter to *target* and leaves TOS on the + stack. Otherwise (TOS is false), TOS is popped. + + .. versionadded:: 3.1 + + +.. opcode:: JUMP_IF_FALSE_OR_POP (target) + + If TOS is false, sets the bytecode counter to *target* and leaves TOS on the + stack. Otherwise (TOS is true), TOS is popped. + + .. versionadded:: 3.1 + + +.. opcode:: JUMP_ABSOLUTE (target) + + Set bytecode counter to *target*. + + +.. opcode:: FOR_ITER (delta) + + TOS is an :term:`iterator`. Call its :meth:`~iterator.__next__` method. If + this yields a new value, push it on the stack (leaving the iterator below + it). If the iterator indicates it is exhausted, TOS is popped, and the byte + code counter is incremented by *delta*. + + +.. opcode:: LOAD_GLOBAL (namei) + + Loads the global named ``co_names[namei]`` onto the stack. + + +.. opcode:: SETUP_FINALLY (delta) + + Pushes a try block from a try-finally or try-except clause onto the block + stack. *delta* points to the finally block or the first except block. + + +.. opcode:: LOAD_FAST (var_num) + + Pushes a reference to the local ``co_varnames[var_num]`` onto the stack. + + +.. opcode:: STORE_FAST (var_num) + + Stores TOS into the local ``co_varnames[var_num]``. + + +.. opcode:: DELETE_FAST (var_num) + + Deletes local ``co_varnames[var_num]``. + + +.. opcode:: LOAD_CLOSURE (i) + + Pushes a reference to the cell contained in slot *i* of the cell and free + variable storage. The name of the variable is ``co_cellvars[i]`` if *i* is + less than the length of *co_cellvars*. Otherwise it is ``co_freevars[i - + len(co_cellvars)]``. + + +.. opcode:: LOAD_DEREF (i) + + Loads the cell contained in slot *i* of the cell and free variable storage. + Pushes a reference to the object the cell contains on the stack. + + +.. opcode:: LOAD_CLASSDEREF (i) + + Much like :opcode:`LOAD_DEREF` but first checks the locals dictionary before + consulting the cell. This is used for loading free variables in class + bodies. + + .. versionadded:: 3.4 + + +.. opcode:: STORE_DEREF (i) + + Stores TOS into the cell contained in slot *i* of the cell and free variable + storage. + + +.. opcode:: DELETE_DEREF (i) + + Empties the cell contained in slot *i* of the cell and free variable storage. + Used by the :keyword:`del` statement. + + .. versionadded:: 3.2 + + +.. opcode:: RAISE_VARARGS (argc) + + Raises an exception using one of the 3 forms of the ``raise`` statement, + depending on the value of *argc*: + + * 0: ``raise`` (re-raise previous exception) + * 1: ``raise TOS`` (raise exception instance or type at ``TOS``) + * 2: ``raise TOS1 from TOS`` (raise exception instance or type at ``TOS1`` + with ``__cause__`` set to ``TOS``) + + +.. opcode:: CALL_FUNCTION (argc) + + Calls a callable object with positional arguments. + *argc* indicates the number of positional arguments. + The top of the stack contains positional arguments, with the right-most + argument on top. Below the arguments is a callable object to call. + ``CALL_FUNCTION`` pops all arguments and the callable object off the stack, + calls the callable object with those arguments, and pushes the return value + returned by the callable object. + + .. versionchanged:: 3.6 + This opcode is used only for calls with positional arguments. + + +.. opcode:: CALL_FUNCTION_KW (argc) + + Calls a callable object with positional (if any) and keyword arguments. + *argc* indicates the total number of positional and keyword arguments. + The top element on the stack contains a tuple with the names of the + keyword arguments, which must be strings. + Below that are the values for the keyword arguments, + in the order corresponding to the tuple. + Below that are positional arguments, with the right-most parameter on + top. Below the arguments is a callable object to call. + ``CALL_FUNCTION_KW`` pops all arguments and the callable object off the stack, + calls the callable object with those arguments, and pushes the return value + returned by the callable object. + + .. versionchanged:: 3.6 + Keyword arguments are packed in a tuple instead of a dictionary, + *argc* indicates the total number of arguments. + + +.. opcode:: CALL_FUNCTION_EX (flags) + + Calls a callable object with variable set of positional and keyword + arguments. If the lowest bit of *flags* is set, the top of the stack + contains a mapping object containing additional keyword arguments. + Before the callable is called, the mapping object and iterable object + are each "unpacked" and their contents passed in as keyword and + positional arguments respectively. + ``CALL_FUNCTION_EX`` pops all arguments and the callable object off the stack, + calls the callable object with those arguments, and pushes the return value + returned by the callable object. + + .. versionadded:: 3.6 + + +.. opcode:: LOAD_METHOD (namei) + + Loads a method named ``co_names[namei]`` from the TOS object. TOS is popped. + This bytecode distinguishes two cases: if TOS has a method with the correct + name, the bytecode pushes the unbound method and TOS. TOS will be used as + the first argument (``self``) by :opcode:`CALL_METHOD` when calling the + unbound method. Otherwise, ``NULL`` and the object return by the attribute + lookup are pushed. + + .. versionadded:: 3.7 + + +.. opcode:: CALL_METHOD (argc) + + Calls a method. *argc* is the number of positional arguments. + Keyword arguments are not supported. This opcode is designed to be used + with :opcode:`LOAD_METHOD`. Positional arguments are on top of the stack. + Below them, the two items described in :opcode:`LOAD_METHOD` are on the + stack (either ``self`` and an unbound method object or ``NULL`` and an + arbitrary callable). All of them are popped and the return value is pushed. + + .. versionadded:: 3.7 + + +.. opcode:: MAKE_FUNCTION (flags) + + Pushes a new function object on the stack. From bottom to top, the consumed + stack must consist of values if the argument carries a specified flag value + + * ``0x01`` a tuple of default values for positional-only and + positional-or-keyword parameters in positional order + * ``0x02`` a dictionary of keyword-only parameters' default values + * ``0x04`` an annotation dictionary + * ``0x08`` a tuple containing cells for free variables, making a closure + * the code associated with the function (at TOS1) + * the :term:`qualified name` of the function (at TOS) + + +.. opcode:: BUILD_SLICE (argc) + + .. index:: builtin: slice + + Pushes a slice object on the stack. *argc* must be 2 or 3. If it is 2, + ``slice(TOS1, TOS)`` is pushed; if it is 3, ``slice(TOS2, TOS1, TOS)`` is + pushed. See the :func:`slice` built-in function for more information. + + +.. opcode:: EXTENDED_ARG (ext) + + Prefixes any opcode which has an argument too big to fit into the default one + byte. *ext* holds an additional byte which act as higher bits in the argument. + For each opcode, at most three prefixal ``EXTENDED_ARG`` are allowed, forming + an argument from two-byte to four-byte. + + +.. opcode:: FORMAT_VALUE (flags) + + Used for implementing formatted literal strings (f-strings). Pops + an optional *fmt_spec* from the stack, then a required *value*. + *flags* is interpreted as follows: + + * ``(flags & 0x03) == 0x00``: *value* is formatted as-is. + * ``(flags & 0x03) == 0x01``: call :func:`str` on *value* before + formatting it. + * ``(flags & 0x03) == 0x02``: call :func:`repr` on *value* before + formatting it. + * ``(flags & 0x03) == 0x03``: call :func:`ascii` on *value* before + formatting it. + * ``(flags & 0x04) == 0x04``: pop *fmt_spec* from the stack and use + it, else use an empty *fmt_spec*. + + Formatting is performed using :c:func:`PyObject_Format`. The + result is pushed on the stack. + + .. versionadded:: 3.6 + + +.. opcode:: HAVE_ARGUMENT + + This is not really an opcode. It identifies the dividing line between + opcodes which don't use their argument and those that do + (``< HAVE_ARGUMENT`` and ``>= HAVE_ARGUMENT``, respectively). + + .. versionchanged:: 3.6 + Now every instruction has an argument, but opcodes ``< HAVE_ARGUMENT`` + ignore it. Before, only opcodes ``>= HAVE_ARGUMENT`` had an argument. + + +.. _opcode_collections: + +Opcode collections +------------------ + +These collections are provided for automatic introspection of bytecode +instructions: + +.. data:: opname + + Sequence of operation names, indexable using the bytecode. + + +.. data:: opmap + + Dictionary mapping operation names to bytecodes. + + +.. data:: cmp_op + + Sequence of all compare operation names. + + +.. data:: hasconst + + Sequence of bytecodes that access a constant. + + +.. data:: hasfree + + Sequence of bytecodes that access a free variable (note that 'free' in this + context refers to names in the current scope that are referenced by inner + scopes or names in outer scopes that are referenced from this scope. It does + *not* include references to global or builtin scopes). + + +.. data:: hasname + + Sequence of bytecodes that access an attribute by name. + + +.. data:: hasjrel + + Sequence of bytecodes that have a relative jump target. + + +.. data:: hasjabs + + Sequence of bytecodes that have an absolute jump target. + + +.. data:: haslocal + + Sequence of bytecodes that access a local variable. + + +.. data:: hascompare + + Sequence of bytecodes of Boolean operations. diff --git a/cpython_2/environment/repo/Doc/library/distribution.rst b/cpython_2/environment/repo/Doc/library/distribution.rst new file mode 100644 index 0000000000000000000000000000000000000000..8d4befe41b329cf93e98f13b769b7a9651776e37 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/distribution.rst @@ -0,0 +1,15 @@ +*********************************** +Software Packaging and Distribution +*********************************** + +These libraries help you with publishing and installing Python software. +While these modules are designed to work in conjunction with the +`Python Package Index `__, they can also be used +with a local index server, or without any index server at all. + +.. toctree:: + + distutils.rst + ensurepip.rst + venv.rst + zipapp.rst diff --git a/cpython_2/environment/repo/Doc/library/distutils.rst b/cpython_2/environment/repo/Doc/library/distutils.rst new file mode 100644 index 0000000000000000000000000000000000000000..62abc85ac397a4ea56be2be44c39648fddb6535b --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/distutils.rst @@ -0,0 +1,44 @@ +:mod:`distutils` --- Building and installing Python modules +=========================================================== + +.. module:: distutils + :synopsis: Support for building and installing Python modules into an + existing Python installation. + +.. sectionauthor:: Fred L. Drake, Jr. + +-------------- + +The :mod:`distutils` package provides support for building and installing +additional modules into a Python installation. The new modules may be either +100%-pure Python, or may be extension modules written in C, or may be +collections of Python packages which include modules coded in both Python and C. + +Most Python users will *not* want to use this module directly, but instead +use the cross-version tools maintained by the Python Packaging Authority. In +particular, +`setuptools `__ is an +enhanced alternative to :mod:`distutils` that provides: + +* support for declaring project dependencies +* additional mechanisms for configuring which files to include in source + releases (including plugins for integration with version control systems) +* the ability to declare project "entry points", which can be used as the + basis for application plugin systems +* the ability to automatically generate Windows command line executables at + installation time rather than needing to prebuild them +* consistent behaviour across all supported Python versions + +The recommended `pip `__ installer runs all +``setup.py`` scripts with ``setuptools``, even if the script itself only +imports ``distutils``. Refer to the +`Python Packaging User Guide `_ for more +information. + +For the benefits of packaging tool authors and users seeking a deeper +understanding of the details of the current packaging and distribution +system, the legacy :mod:`distutils` based user documentation and API +reference remain available: + +* :ref:`install-index` +* :ref:`distutils-index` diff --git a/cpython_2/environment/repo/Doc/library/doctest.rst b/cpython_2/environment/repo/Doc/library/doctest.rst new file mode 100644 index 0000000000000000000000000000000000000000..a77322f83acbdef19d464ba1d196a700f309defb --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/doctest.rst @@ -0,0 +1,1866 @@ +:mod:`doctest` --- Test interactive Python examples +=================================================== + +.. module:: doctest + :synopsis: Test pieces of code within docstrings. + +.. moduleauthor:: Tim Peters +.. sectionauthor:: Tim Peters +.. sectionauthor:: Moshe Zadka +.. sectionauthor:: Edward Loper + +**Source code:** :source:`Lib/doctest.py` + +-------------- + +The :mod:`doctest` module searches for pieces of text that look like interactive +Python sessions, and then executes those sessions to verify that they work +exactly as shown. There are several common ways to use doctest: + +* To check that a module's docstrings are up-to-date by verifying that all + interactive examples still work as documented. + +* To perform regression testing by verifying that interactive examples from a + test file or a test object work as expected. + +* To write tutorial documentation for a package, liberally illustrated with + input-output examples. Depending on whether the examples or the expository text + are emphasized, this has the flavor of "literate testing" or "executable + documentation". + +Here's a complete but small example module:: + + """ + This is the "example" module. + + The example module supplies one function, factorial(). For example, + + >>> factorial(5) + 120 + """ + + def factorial(n): + """Return the factorial of n, an exact integer >= 0. + + >>> [factorial(n) for n in range(6)] + [1, 1, 2, 6, 24, 120] + >>> factorial(30) + 265252859812191058636308480000000 + >>> factorial(-1) + Traceback (most recent call last): + ... + ValueError: n must be >= 0 + + Factorials of floats are OK, but the float must be an exact integer: + >>> factorial(30.1) + Traceback (most recent call last): + ... + ValueError: n must be exact integer + >>> factorial(30.0) + 265252859812191058636308480000000 + + It must also not be ridiculously large: + >>> factorial(1e100) + Traceback (most recent call last): + ... + OverflowError: n too large + """ + + import math + if not n >= 0: + raise ValueError("n must be >= 0") + if math.floor(n) != n: + raise ValueError("n must be exact integer") + if n+1 == n: # catch a value like 1e300 + raise OverflowError("n too large") + result = 1 + factor = 2 + while factor <= n: + result *= factor + factor += 1 + return result + + + if __name__ == "__main__": + import doctest + doctest.testmod() + +If you run :file:`example.py` directly from the command line, :mod:`doctest` +works its magic: + +.. code-block:: shell-session + + $ python example.py + $ + +There's no output! That's normal, and it means all the examples worked. Pass +``-v`` to the script, and :mod:`doctest` prints a detailed log of what +it's trying, and prints a summary at the end: + +.. code-block:: shell-session + + $ python example.py -v + Trying: + factorial(5) + Expecting: + 120 + ok + Trying: + [factorial(n) for n in range(6)] + Expecting: + [1, 1, 2, 6, 24, 120] + ok + +And so on, eventually ending with: + +.. code-block:: none + + Trying: + factorial(1e100) + Expecting: + Traceback (most recent call last): + ... + OverflowError: n too large + ok + 2 items passed all tests: + 1 tests in __main__ + 8 tests in __main__.factorial + 9 tests in 2 items. + 9 passed and 0 failed. + Test passed. + $ + +That's all you need to know to start making productive use of :mod:`doctest`! +Jump in. The following sections provide full details. Note that there are many +examples of doctests in the standard Python test suite and libraries. +Especially useful examples can be found in the standard test file +:file:`Lib/test/test_doctest.py`. + + +.. _doctest-simple-testmod: + +Simple Usage: Checking Examples in Docstrings +--------------------------------------------- + +The simplest way to start using doctest (but not necessarily the way you'll +continue to do it) is to end each module :mod:`M` with:: + + if __name__ == "__main__": + import doctest + doctest.testmod() + +:mod:`doctest` then examines docstrings in module :mod:`M`. + +Running the module as a script causes the examples in the docstrings to get +executed and verified:: + + python M.py + +This won't display anything unless an example fails, in which case the failing +example(s) and the cause(s) of the failure(s) are printed to stdout, and the +final line of output is ``***Test Failed*** N failures.``, where *N* is the +number of examples that failed. + +Run it with the ``-v`` switch instead:: + + python M.py -v + +and a detailed report of all examples tried is printed to standard output, along +with assorted summaries at the end. + +You can force verbose mode by passing ``verbose=True`` to :func:`testmod`, or +prohibit it by passing ``verbose=False``. In either of those cases, +``sys.argv`` is not examined by :func:`testmod` (so passing ``-v`` or not +has no effect). + +There is also a command line shortcut for running :func:`testmod`. You can +instruct the Python interpreter to run the doctest module directly from the +standard library and pass the module name(s) on the command line:: + + python -m doctest -v example.py + +This will import :file:`example.py` as a standalone module and run +:func:`testmod` on it. Note that this may not work correctly if the file is +part of a package and imports other submodules from that package. + +For more information on :func:`testmod`, see section :ref:`doctest-basic-api`. + + +.. _doctest-simple-testfile: + +Simple Usage: Checking Examples in a Text File +---------------------------------------------- + +Another simple application of doctest is testing interactive examples in a text +file. This can be done with the :func:`testfile` function:: + + import doctest + doctest.testfile("example.txt") + +That short script executes and verifies any interactive Python examples +contained in the file :file:`example.txt`. The file content is treated as if it +were a single giant docstring; the file doesn't need to contain a Python +program! For example, perhaps :file:`example.txt` contains this: + +.. code-block:: none + + The ``example`` module + ====================== + + Using ``factorial`` + ------------------- + + This is an example text file in reStructuredText format. First import + ``factorial`` from the ``example`` module: + + >>> from example import factorial + + Now use it: + + >>> factorial(6) + 120 + +Running ``doctest.testfile("example.txt")`` then finds the error in this +documentation:: + + File "./example.txt", line 14, in example.txt + Failed example: + factorial(6) + Expected: + 120 + Got: + 720 + +As with :func:`testmod`, :func:`testfile` won't display anything unless an +example fails. If an example does fail, then the failing example(s) and the +cause(s) of the failure(s) are printed to stdout, using the same format as +:func:`testmod`. + +By default, :func:`testfile` looks for files in the calling module's directory. +See section :ref:`doctest-basic-api` for a description of the optional arguments +that can be used to tell it to look for files in other locations. + +Like :func:`testmod`, :func:`testfile`'s verbosity can be set with the +``-v`` command-line switch or with the optional keyword argument +*verbose*. + +There is also a command line shortcut for running :func:`testfile`. You can +instruct the Python interpreter to run the doctest module directly from the +standard library and pass the file name(s) on the command line:: + + python -m doctest -v example.txt + +Because the file name does not end with :file:`.py`, :mod:`doctest` infers that +it must be run with :func:`testfile`, not :func:`testmod`. + +For more information on :func:`testfile`, see section :ref:`doctest-basic-api`. + + +.. _doctest-how-it-works: + +How It Works +------------ + +This section examines in detail how doctest works: which docstrings it looks at, +how it finds interactive examples, what execution context it uses, how it +handles exceptions, and how option flags can be used to control its behavior. +This is the information that you need to know to write doctest examples; for +information about actually running doctest on these examples, see the following +sections. + + +.. _doctest-which-docstrings: + +Which Docstrings Are Examined? +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The module docstring, and all function, class and method docstrings are +searched. Objects imported into the module are not searched. + +In addition, if ``M.__test__`` exists and "is true", it must be a dict, and each +entry maps a (string) name to a function object, class object, or string. +Function and class object docstrings found from ``M.__test__`` are searched, and +strings are treated as if they were docstrings. In output, a key ``K`` in +``M.__test__`` appears with name :: + + .__test__.K + +Any classes found are recursively searched similarly, to test docstrings in +their contained methods and nested classes. + +.. impl-detail:: + Prior to version 3.4, extension modules written in C were not fully + searched by doctest. + + +.. _doctest-finding-examples: + +How are Docstring Examples Recognized? +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +In most cases a copy-and-paste of an interactive console session works fine, +but doctest isn't trying to do an exact emulation of any specific Python shell. + +:: + + >>> # comments are ignored + >>> x = 12 + >>> x + 12 + >>> if x == 13: + ... print("yes") + ... else: + ... print("no") + ... print("NO") + ... print("NO!!!") + ... + no + NO + NO!!! + >>> + +.. index:: + single: >>>; interpreter prompt + single: ...; interpreter prompt + +Any expected output must immediately follow the final ``'>>> '`` or ``'... '`` +line containing the code, and the expected output (if any) extends to the next +``'>>> '`` or all-whitespace line. + +The fine print: + +* Expected output cannot contain an all-whitespace line, since such a line is + taken to signal the end of expected output. If expected output does contain a + blank line, put ```` in your doctest example each place a blank line + is expected. + +* All hard tab characters are expanded to spaces, using 8-column tab stops. + Tabs in output generated by the tested code are not modified. Because any + hard tabs in the sample output *are* expanded, this means that if the code + output includes hard tabs, the only way the doctest can pass is if the + :const:`NORMALIZE_WHITESPACE` option or :ref:`directive ` + is in effect. + Alternatively, the test can be rewritten to capture the output and compare it + to an expected value as part of the test. This handling of tabs in the + source was arrived at through trial and error, and has proven to be the least + error prone way of handling them. It is possible to use a different + algorithm for handling tabs by writing a custom :class:`DocTestParser` class. + +* Output to stdout is captured, but not output to stderr (exception tracebacks + are captured via a different means). + +* If you continue a line via backslashing in an interactive session, or for any + other reason use a backslash, you should use a raw docstring, which will + preserve your backslashes exactly as you type them:: + + >>> def f(x): + ... r'''Backslashes in a raw docstring: m\n''' + >>> print(f.__doc__) + Backslashes in a raw docstring: m\n + + Otherwise, the backslash will be interpreted as part of the string. For example, + the ``\n`` above would be interpreted as a newline character. Alternatively, you + can double each backslash in the doctest version (and not use a raw string):: + + >>> def f(x): + ... '''Backslashes in a raw docstring: m\\n''' + >>> print(f.__doc__) + Backslashes in a raw docstring: m\n + +* The starting column doesn't matter:: + + >>> assert "Easy!" + >>> import math + >>> math.floor(1.9) + 1 + + and as many leading whitespace characters are stripped from the expected output + as appeared in the initial ``'>>> '`` line that started the example. + + +.. _doctest-execution-context: + +What's the Execution Context? +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +By default, each time :mod:`doctest` finds a docstring to test, it uses a +*shallow copy* of :mod:`M`'s globals, so that running tests doesn't change the +module's real globals, and so that one test in :mod:`M` can't leave behind +crumbs that accidentally allow another test to work. This means examples can +freely use any names defined at top-level in :mod:`M`, and names defined earlier +in the docstring being run. Examples cannot see names defined in other +docstrings. + +You can force use of your own dict as the execution context by passing +``globs=your_dict`` to :func:`testmod` or :func:`testfile` instead. + + +.. _doctest-exceptions: + +What About Exceptions? +^^^^^^^^^^^^^^^^^^^^^^ + +No problem, provided that the traceback is the only output produced by the +example: just paste in the traceback. [#]_ Since tracebacks contain details +that are likely to change rapidly (for example, exact file paths and line +numbers), this is one case where doctest works hard to be flexible in what it +accepts. + +Simple example:: + + >>> [1, 2, 3].remove(42) + Traceback (most recent call last): + File "", line 1, in + ValueError: list.remove(x): x not in list + +That doctest succeeds if :exc:`ValueError` is raised, with the ``list.remove(x): +x not in list`` detail as shown. + +The expected output for an exception must start with a traceback header, which +may be either of the following two lines, indented the same as the first line of +the example:: + + Traceback (most recent call last): + Traceback (innermost last): + +The traceback header is followed by an optional traceback stack, whose contents +are ignored by doctest. The traceback stack is typically omitted, or copied +verbatim from an interactive session. + +The traceback stack is followed by the most interesting part: the line(s) +containing the exception type and detail. This is usually the last line of a +traceback, but can extend across multiple lines if the exception has a +multi-line detail:: + + >>> raise ValueError('multi\n line\ndetail') + Traceback (most recent call last): + File "", line 1, in + ValueError: multi + line + detail + +The last three lines (starting with :exc:`ValueError`) are compared against the +exception's type and detail, and the rest are ignored. + +Best practice is to omit the traceback stack, unless it adds significant +documentation value to the example. So the last example is probably better as:: + + >>> raise ValueError('multi\n line\ndetail') + Traceback (most recent call last): + ... + ValueError: multi + line + detail + +Note that tracebacks are treated very specially. In particular, in the +rewritten example, the use of ``...`` is independent of doctest's +:const:`ELLIPSIS` option. The ellipsis in that example could be left out, or +could just as well be three (or three hundred) commas or digits, or an indented +transcript of a Monty Python skit. + +Some details you should read once, but won't need to remember: + +* Doctest can't guess whether your expected output came from an exception + traceback or from ordinary printing. So, e.g., an example that expects + ``ValueError: 42 is prime`` will pass whether :exc:`ValueError` is actually + raised or if the example merely prints that traceback text. In practice, + ordinary output rarely begins with a traceback header line, so this doesn't + create real problems. + +* Each line of the traceback stack (if present) must be indented further than + the first line of the example, *or* start with a non-alphanumeric character. + The first line following the traceback header indented the same and starting + with an alphanumeric is taken to be the start of the exception detail. Of + course this does the right thing for genuine tracebacks. + +* When the :const:`IGNORE_EXCEPTION_DETAIL` doctest option is specified, + everything following the leftmost colon and any module information in the + exception name is ignored. + +* The interactive shell omits the traceback header line for some + :exc:`SyntaxError`\ s. But doctest uses the traceback header line to + distinguish exceptions from non-exceptions. So in the rare case where you need + to test a :exc:`SyntaxError` that omits the traceback header, you will need to + manually add the traceback header line to your test example. + +.. index:: single: ^ (caret); marker + +* For some :exc:`SyntaxError`\ s, Python displays the character position of the + syntax error, using a ``^`` marker:: + + >>> 1 1 + File "", line 1 + 1 1 + ^ + SyntaxError: invalid syntax + + Since the lines showing the position of the error come before the exception type + and detail, they are not checked by doctest. For example, the following test + would pass, even though it puts the ``^`` marker in the wrong location:: + + >>> 1 1 + Traceback (most recent call last): + File "", line 1 + 1 1 + ^ + SyntaxError: invalid syntax + + +.. _option-flags-and-directives: +.. _doctest-options: + +Option Flags +^^^^^^^^^^^^ + +A number of option flags control various aspects of doctest's behavior. +Symbolic names for the flags are supplied as module constants, which can be +:ref:`bitwise ORed ` together and passed to various functions. +The names can also be used in :ref:`doctest directives `, +and may be passed to the doctest command line interface via the ``-o`` option. + +.. versionadded:: 3.4 + The ``-o`` command line option. + +The first group of options define test semantics, controlling aspects of how +doctest decides whether actual output matches an example's expected output: + + +.. data:: DONT_ACCEPT_TRUE_FOR_1 + + By default, if an expected output block contains just ``1``, an actual output + block containing just ``1`` or just ``True`` is considered to be a match, and + similarly for ``0`` versus ``False``. When :const:`DONT_ACCEPT_TRUE_FOR_1` is + specified, neither substitution is allowed. The default behavior caters to that + Python changed the return type of many functions from integer to boolean; + doctests expecting "little integer" output still work in these cases. This + option will probably go away, but not for several years. + + +.. index:: single: +.. data:: DONT_ACCEPT_BLANKLINE + + By default, if an expected output block contains a line containing only the + string ````, then that line will match a blank line in the actual + output. Because a genuinely blank line delimits the expected output, this is + the only way to communicate that a blank line is expected. When + :const:`DONT_ACCEPT_BLANKLINE` is specified, this substitution is not allowed. + + +.. data:: NORMALIZE_WHITESPACE + + When specified, all sequences of whitespace (blanks and newlines) are treated as + equal. Any sequence of whitespace within the expected output will match any + sequence of whitespace within the actual output. By default, whitespace must + match exactly. :const:`NORMALIZE_WHITESPACE` is especially useful when a line of + expected output is very long, and you want to wrap it across multiple lines in + your source. + + +.. index:: single: ...; in doctests +.. data:: ELLIPSIS + + When specified, an ellipsis marker (``...``) in the expected output can match + any substring in the actual output. This includes substrings that span line + boundaries, and empty substrings, so it's best to keep usage of this simple. + Complicated uses can lead to the same kinds of "oops, it matched too much!" + surprises that ``.*`` is prone to in regular expressions. + + +.. data:: IGNORE_EXCEPTION_DETAIL + + When specified, an example that expects an exception passes if an exception of + the expected type is raised, even if the exception detail does not match. For + example, an example expecting ``ValueError: 42`` will pass if the actual + exception raised is ``ValueError: 3*14``, but will fail, e.g., if + :exc:`TypeError` is raised. + + It will also ignore the module name used in Python 3 doctest reports. Hence + both of these variations will work with the flag specified, regardless of + whether the test is run under Python 2.7 or Python 3.2 (or later versions):: + + >>> raise CustomError('message') + Traceback (most recent call last): + CustomError: message + + >>> raise CustomError('message') + Traceback (most recent call last): + my_module.CustomError: message + + Note that :const:`ELLIPSIS` can also be used to ignore the + details of the exception message, but such a test may still fail based + on whether or not the module details are printed as part of the + exception name. Using :const:`IGNORE_EXCEPTION_DETAIL` and the details + from Python 2.3 is also the only clear way to write a doctest that doesn't + care about the exception detail yet continues to pass under Python 2.3 or + earlier (those releases do not support :ref:`doctest directives + ` and ignore them as irrelevant comments). For example:: + + >>> (1, 2)[3] = 'moo' + Traceback (most recent call last): + File "", line 1, in + TypeError: object doesn't support item assignment + + passes under Python 2.3 and later Python versions with the flag specified, + even though the detail + changed in Python 2.4 to say "does not" instead of "doesn't". + + .. versionchanged:: 3.2 + :const:`IGNORE_EXCEPTION_DETAIL` now also ignores any information relating + to the module containing the exception under test. + + +.. data:: SKIP + + When specified, do not run the example at all. This can be useful in contexts + where doctest examples serve as both documentation and test cases, and an + example should be included for documentation purposes, but should not be + checked. E.g., the example's output might be random; or the example might + depend on resources which would be unavailable to the test driver. + + The SKIP flag can also be used for temporarily "commenting out" examples. + + +.. data:: COMPARISON_FLAGS + + A bitmask or'ing together all the comparison flags above. + +The second group of options controls how test failures are reported: + + +.. data:: REPORT_UDIFF + + When specified, failures that involve multi-line expected and actual outputs are + displayed using a unified diff. + + +.. data:: REPORT_CDIFF + + When specified, failures that involve multi-line expected and actual outputs + will be displayed using a context diff. + + +.. data:: REPORT_NDIFF + + When specified, differences are computed by ``difflib.Differ``, using the same + algorithm as the popular :file:`ndiff.py` utility. This is the only method that + marks differences within lines as well as across lines. For example, if a line + of expected output contains digit ``1`` where actual output contains letter + ``l``, a line is inserted with a caret marking the mismatching column positions. + + +.. data:: REPORT_ONLY_FIRST_FAILURE + + When specified, display the first failing example in each doctest, but suppress + output for all remaining examples. This will prevent doctest from reporting + correct examples that break because of earlier failures; but it might also hide + incorrect examples that fail independently of the first failure. When + :const:`REPORT_ONLY_FIRST_FAILURE` is specified, the remaining examples are + still run, and still count towards the total number of failures reported; only + the output is suppressed. + + +.. data:: FAIL_FAST + + When specified, exit after the first failing example and don't attempt to run + the remaining examples. Thus, the number of failures reported will be at most + 1. This flag may be useful during debugging, since examples after the first + failure won't even produce debugging output. + + The doctest command line accepts the option ``-f`` as a shorthand for ``-o + FAIL_FAST``. + + .. versionadded:: 3.4 + + +.. data:: REPORTING_FLAGS + + A bitmask or'ing together all the reporting flags above. + + +There is also a way to register new option flag names, though this isn't +useful unless you intend to extend :mod:`doctest` internals via subclassing: + + +.. function:: register_optionflag(name) + + Create a new option flag with a given name, and return the new flag's integer + value. :func:`register_optionflag` can be used when subclassing + :class:`OutputChecker` or :class:`DocTestRunner` to create new options that are + supported by your subclasses. :func:`register_optionflag` should always be + called using the following idiom:: + + MY_FLAG = register_optionflag('MY_FLAG') + + +.. index:: + single: # (hash); in doctests + single: + (plus); in doctests + single: - (minus); in doctests +.. _doctest-directives: + +Directives +^^^^^^^^^^ + +Doctest directives may be used to modify the :ref:`option flags +` for an individual example. Doctest directives are +special Python comments following an example's source code: + +.. productionlist:: doctest + directive: "#" "doctest:" `directive_options` + directive_options: `directive_option` ("," `directive_option`)\* + directive_option: `on_or_off` `directive_option_name` + on_or_off: "+" \| "-" + directive_option_name: "DONT_ACCEPT_BLANKLINE" \| "NORMALIZE_WHITESPACE" \| ... + +Whitespace is not allowed between the ``+`` or ``-`` and the directive option +name. The directive option name can be any of the option flag names explained +above. + +An example's doctest directives modify doctest's behavior for that single +example. Use ``+`` to enable the named behavior, or ``-`` to disable it. + +For example, this test passes:: + + >>> print(list(range(20))) # doctest: +NORMALIZE_WHITESPACE + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] + +Without the directive it would fail, both because the actual output doesn't have +two blanks before the single-digit list elements, and because the actual output +is on a single line. This test also passes, and also requires a directive to do +so:: + + >>> print(list(range(20))) # doctest: +ELLIPSIS + [0, 1, ..., 18, 19] + +Multiple directives can be used on a single physical line, separated by +commas:: + + >>> print(list(range(20))) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE + [0, 1, ..., 18, 19] + +If multiple directive comments are used for a single example, then they are +combined:: + + >>> print(list(range(20))) # doctest: +ELLIPSIS + ... # doctest: +NORMALIZE_WHITESPACE + [0, 1, ..., 18, 19] + +As the previous example shows, you can add ``...`` lines to your example +containing only directives. This can be useful when an example is too long for +a directive to comfortably fit on the same line:: + + >>> print(list(range(5)) + list(range(10, 20)) + list(range(30, 40))) + ... # doctest: +ELLIPSIS + [0, ..., 4, 10, ..., 19, 30, ..., 39] + +Note that since all options are disabled by default, and directives apply only +to the example they appear in, enabling options (via ``+`` in a directive) is +usually the only meaningful choice. However, option flags can also be passed to +functions that run doctests, establishing different defaults. In such cases, +disabling an option via ``-`` in a directive can be useful. + + +.. _doctest-warnings: + +Warnings +^^^^^^^^ + +:mod:`doctest` is serious about requiring exact matches in expected output. If +even a single character doesn't match, the test fails. This will probably +surprise you a few times, as you learn exactly what Python does and doesn't +guarantee about output. For example, when printing a set, Python doesn't +guarantee that the element is printed in any particular order, so a test like :: + + >>> foo() + {"Hermione", "Harry"} + +is vulnerable! One workaround is to do :: + + >>> foo() == {"Hermione", "Harry"} + True + +instead. Another is to do :: + + >>> d = sorted(foo()) + >>> d + ['Harry', 'Hermione'] + +.. note:: + + Before Python 3.6, when printing a dict, Python did not guarantee that + the key-value pairs was printed in any particular order. + +There are others, but you get the idea. + +Another bad idea is to print things that embed an object address, like :: + + >>> id(1.0) # certain to fail some of the time + 7948648 + >>> class C: pass + >>> C() # the default repr() for instances embeds an address + <__main__.C instance at 0x00AC18F0> + +The :const:`ELLIPSIS` directive gives a nice approach for the last example:: + + >>> C() #doctest: +ELLIPSIS + <__main__.C instance at 0x...> + +Floating-point numbers are also subject to small output variations across +platforms, because Python defers to the platform C library for float formatting, +and C libraries vary widely in quality here. :: + + >>> 1./7 # risky + 0.14285714285714285 + >>> print(1./7) # safer + 0.142857142857 + >>> print(round(1./7, 6)) # much safer + 0.142857 + +Numbers of the form ``I/2.**J`` are safe across all platforms, and I often +contrive doctest examples to produce numbers of that form:: + + >>> 3./4 # utterly safe + 0.75 + +Simple fractions are also easier for people to understand, and that makes for +better documentation. + + +.. _doctest-basic-api: + +Basic API +--------- + +The functions :func:`testmod` and :func:`testfile` provide a simple interface to +doctest that should be sufficient for most basic uses. For a less formal +introduction to these two functions, see sections :ref:`doctest-simple-testmod` +and :ref:`doctest-simple-testfile`. + + +.. function:: testfile(filename, module_relative=True, name=None, package=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, parser=DocTestParser(), encoding=None) + + All arguments except *filename* are optional, and should be specified in keyword + form. + + Test examples in the file named *filename*. Return ``(failure_count, + test_count)``. + + Optional argument *module_relative* specifies how the filename should be + interpreted: + + * If *module_relative* is ``True`` (the default), then *filename* specifies an + OS-independent module-relative path. By default, this path is relative to the + calling module's directory; but if the *package* argument is specified, then it + is relative to that package. To ensure OS-independence, *filename* should use + ``/`` characters to separate path segments, and may not be an absolute path + (i.e., it may not begin with ``/``). + + * If *module_relative* is ``False``, then *filename* specifies an OS-specific + path. The path may be absolute or relative; relative paths are resolved with + respect to the current working directory. + + Optional argument *name* gives the name of the test; by default, or if ``None``, + ``os.path.basename(filename)`` is used. + + Optional argument *package* is a Python package or the name of a Python package + whose directory should be used as the base directory for a module-relative + filename. If no package is specified, then the calling module's directory is + used as the base directory for module-relative filenames. It is an error to + specify *package* if *module_relative* is ``False``. + + Optional argument *globs* gives a dict to be used as the globals when executing + examples. A new shallow copy of this dict is created for the doctest, so its + examples start with a clean slate. By default, or if ``None``, a new empty dict + is used. + + Optional argument *extraglobs* gives a dict merged into the globals used to + execute examples. This works like :meth:`dict.update`: if *globs* and + *extraglobs* have a common key, the associated value in *extraglobs* appears in + the combined dict. By default, or if ``None``, no extra globals are used. This + is an advanced feature that allows parameterization of doctests. For example, a + doctest can be written for a base class, using a generic name for the class, + then reused to test any number of subclasses by passing an *extraglobs* dict + mapping the generic name to the subclass to be tested. + + Optional argument *verbose* prints lots of stuff if true, and prints only + failures if false; by default, or if ``None``, it's true if and only if ``'-v'`` + is in ``sys.argv``. + + Optional argument *report* prints a summary at the end when true, else prints + nothing at the end. In verbose mode, the summary is detailed, else the summary + is very brief (in fact, empty if all tests passed). + + Optional argument *optionflags* (default value 0) takes the + :ref:`bitwise OR ` of option flags. + See section :ref:`doctest-options`. + + Optional argument *raise_on_error* defaults to false. If true, an exception is + raised upon the first failure or unexpected exception in an example. This + allows failures to be post-mortem debugged. Default behavior is to continue + running examples. + + Optional argument *parser* specifies a :class:`DocTestParser` (or subclass) that + should be used to extract tests from the files. It defaults to a normal parser + (i.e., ``DocTestParser()``). + + Optional argument *encoding* specifies an encoding that should be used to + convert the file to unicode. + + +.. function:: testmod(m=None, name=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, exclude_empty=False) + + All arguments are optional, and all except for *m* should be specified in + keyword form. + + Test examples in docstrings in functions and classes reachable from module *m* + (or module :mod:`__main__` if *m* is not supplied or is ``None``), starting with + ``m.__doc__``. + + Also test examples reachable from dict ``m.__test__``, if it exists and is not + ``None``. ``m.__test__`` maps names (strings) to functions, classes and + strings; function and class docstrings are searched for examples; strings are + searched directly, as if they were docstrings. + + Only docstrings attached to objects belonging to module *m* are searched. + + Return ``(failure_count, test_count)``. + + Optional argument *name* gives the name of the module; by default, or if + ``None``, ``m.__name__`` is used. + + Optional argument *exclude_empty* defaults to false. If true, objects for which + no doctests are found are excluded from consideration. The default is a backward + compatibility hack, so that code still using :meth:`doctest.master.summarize` in + conjunction with :func:`testmod` continues to get output for objects with no + tests. The *exclude_empty* argument to the newer :class:`DocTestFinder` + constructor defaults to true. + + Optional arguments *extraglobs*, *verbose*, *report*, *optionflags*, + *raise_on_error*, and *globs* are the same as for function :func:`testfile` + above, except that *globs* defaults to ``m.__dict__``. + + +.. function:: run_docstring_examples(f, globs, verbose=False, name="NoName", compileflags=None, optionflags=0) + + Test examples associated with object *f*; for example, *f* may be a string, + a module, a function, or a class object. + + A shallow copy of dictionary argument *globs* is used for the execution context. + + Optional argument *name* is used in failure messages, and defaults to + ``"NoName"``. + + If optional argument *verbose* is true, output is generated even if there are no + failures. By default, output is generated only in case of an example failure. + + Optional argument *compileflags* gives the set of flags that should be used by + the Python compiler when running the examples. By default, or if ``None``, + flags are deduced corresponding to the set of future features found in *globs*. + + Optional argument *optionflags* works as for function :func:`testfile` above. + + +.. _doctest-unittest-api: + +Unittest API +------------ + +As your collection of doctest'ed modules grows, you'll want a way to run all +their doctests systematically. :mod:`doctest` provides two functions that can +be used to create :mod:`unittest` test suites from modules and text files +containing doctests. To integrate with :mod:`unittest` test discovery, include +a :func:`load_tests` function in your test module:: + + import unittest + import doctest + import my_module_with_doctests + + def load_tests(loader, tests, ignore): + tests.addTests(doctest.DocTestSuite(my_module_with_doctests)) + return tests + +There are two main functions for creating :class:`unittest.TestSuite` instances +from text files and modules with doctests: + + +.. function:: DocFileSuite(*paths, module_relative=True, package=None, setUp=None, tearDown=None, globs=None, optionflags=0, parser=DocTestParser(), encoding=None) + + Convert doctest tests from one or more text files to a + :class:`unittest.TestSuite`. + + The returned :class:`unittest.TestSuite` is to be run by the unittest framework + and runs the interactive examples in each file. If an example in any file + fails, then the synthesized unit test fails, and a :exc:`failureException` + exception is raised showing the name of the file containing the test and a + (sometimes approximate) line number. + + Pass one or more paths (as strings) to text files to be examined. + + Options may be provided as keyword arguments: + + Optional argument *module_relative* specifies how the filenames in *paths* + should be interpreted: + + * If *module_relative* is ``True`` (the default), then each filename in + *paths* specifies an OS-independent module-relative path. By default, this + path is relative to the calling module's directory; but if the *package* + argument is specified, then it is relative to that package. To ensure + OS-independence, each filename should use ``/`` characters to separate path + segments, and may not be an absolute path (i.e., it may not begin with + ``/``). + + * If *module_relative* is ``False``, then each filename in *paths* specifies + an OS-specific path. The path may be absolute or relative; relative paths + are resolved with respect to the current working directory. + + Optional argument *package* is a Python package or the name of a Python + package whose directory should be used as the base directory for + module-relative filenames in *paths*. If no package is specified, then the + calling module's directory is used as the base directory for module-relative + filenames. It is an error to specify *package* if *module_relative* is + ``False``. + + Optional argument *setUp* specifies a set-up function for the test suite. + This is called before running the tests in each file. The *setUp* function + will be passed a :class:`DocTest` object. The setUp function can access the + test globals as the *globs* attribute of the test passed. + + Optional argument *tearDown* specifies a tear-down function for the test + suite. This is called after running the tests in each file. The *tearDown* + function will be passed a :class:`DocTest` object. The setUp function can + access the test globals as the *globs* attribute of the test passed. + + Optional argument *globs* is a dictionary containing the initial global + variables for the tests. A new copy of this dictionary is created for each + test. By default, *globs* is a new empty dictionary. + + Optional argument *optionflags* specifies the default doctest options for the + tests, created by or-ing together individual option flags. See section + :ref:`doctest-options`. See function :func:`set_unittest_reportflags` below + for a better way to set reporting options. + + Optional argument *parser* specifies a :class:`DocTestParser` (or subclass) + that should be used to extract tests from the files. It defaults to a normal + parser (i.e., ``DocTestParser()``). + + Optional argument *encoding* specifies an encoding that should be used to + convert the file to unicode. + + The global ``__file__`` is added to the globals provided to doctests loaded + from a text file using :func:`DocFileSuite`. + + +.. function:: DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None, setUp=None, tearDown=None, checker=None) + + Convert doctest tests for a module to a :class:`unittest.TestSuite`. + + The returned :class:`unittest.TestSuite` is to be run by the unittest framework + and runs each doctest in the module. If any of the doctests fail, then the + synthesized unit test fails, and a :exc:`failureException` exception is raised + showing the name of the file containing the test and a (sometimes approximate) + line number. + + Optional argument *module* provides the module to be tested. It can be a module + object or a (possibly dotted) module name. If not specified, the module calling + this function is used. + + Optional argument *globs* is a dictionary containing the initial global + variables for the tests. A new copy of this dictionary is created for each + test. By default, *globs* is a new empty dictionary. + + Optional argument *extraglobs* specifies an extra set of global variables, which + is merged into *globs*. By default, no extra globals are used. + + Optional argument *test_finder* is the :class:`DocTestFinder` object (or a + drop-in replacement) that is used to extract doctests from the module. + + Optional arguments *setUp*, *tearDown*, and *optionflags* are the same as for + function :func:`DocFileSuite` above. + + This function uses the same search technique as :func:`testmod`. + + .. versionchanged:: 3.5 + :func:`DocTestSuite` returns an empty :class:`unittest.TestSuite` if *module* + contains no docstrings instead of raising :exc:`ValueError`. + + +Under the covers, :func:`DocTestSuite` creates a :class:`unittest.TestSuite` out +of :class:`doctest.DocTestCase` instances, and :class:`DocTestCase` is a +subclass of :class:`unittest.TestCase`. :class:`DocTestCase` isn't documented +here (it's an internal detail), but studying its code can answer questions about +the exact details of :mod:`unittest` integration. + +Similarly, :func:`DocFileSuite` creates a :class:`unittest.TestSuite` out of +:class:`doctest.DocFileCase` instances, and :class:`DocFileCase` is a subclass +of :class:`DocTestCase`. + +So both ways of creating a :class:`unittest.TestSuite` run instances of +:class:`DocTestCase`. This is important for a subtle reason: when you run +:mod:`doctest` functions yourself, you can control the :mod:`doctest` options in +use directly, by passing option flags to :mod:`doctest` functions. However, if +you're writing a :mod:`unittest` framework, :mod:`unittest` ultimately controls +when and how tests get run. The framework author typically wants to control +:mod:`doctest` reporting options (perhaps, e.g., specified by command line +options), but there's no way to pass options through :mod:`unittest` to +:mod:`doctest` test runners. + +For this reason, :mod:`doctest` also supports a notion of :mod:`doctest` +reporting flags specific to :mod:`unittest` support, via this function: + + +.. function:: set_unittest_reportflags(flags) + + Set the :mod:`doctest` reporting flags to use. + + Argument *flags* takes the :ref:`bitwise OR ` of option flags. See + section :ref:`doctest-options`. Only "reporting flags" can be used. + + This is a module-global setting, and affects all future doctests run by module + :mod:`unittest`: the :meth:`runTest` method of :class:`DocTestCase` looks at + the option flags specified for the test case when the :class:`DocTestCase` + instance was constructed. If no reporting flags were specified (which is the + typical and expected case), :mod:`doctest`'s :mod:`unittest` reporting flags are + :ref:`bitwise ORed ` into the option flags, and the option flags + so augmented are passed to the :class:`DocTestRunner` instance created to + run the doctest. If any reporting flags were specified when the + :class:`DocTestCase` instance was constructed, :mod:`doctest`'s + :mod:`unittest` reporting flags are ignored. + + The value of the :mod:`unittest` reporting flags in effect before the function + was called is returned by the function. + + +.. _doctest-advanced-api: + +Advanced API +------------ + +The basic API is a simple wrapper that's intended to make doctest easy to use. +It is fairly flexible, and should meet most users' needs; however, if you +require more fine-grained control over testing, or wish to extend doctest's +capabilities, then you should use the advanced API. + +The advanced API revolves around two container classes, which are used to store +the interactive examples extracted from doctest cases: + +* :class:`Example`: A single Python :term:`statement`, paired with its expected + output. + +* :class:`DocTest`: A collection of :class:`Example`\ s, typically extracted + from a single docstring or text file. + +Additional processing classes are defined to find, parse, and run, and check +doctest examples: + +* :class:`DocTestFinder`: Finds all docstrings in a given module, and uses a + :class:`DocTestParser` to create a :class:`DocTest` from every docstring that + contains interactive examples. + +* :class:`DocTestParser`: Creates a :class:`DocTest` object from a string (such + as an object's docstring). + +* :class:`DocTestRunner`: Executes the examples in a :class:`DocTest`, and uses + an :class:`OutputChecker` to verify their output. + +* :class:`OutputChecker`: Compares the actual output from a doctest example with + the expected output, and decides whether they match. + +The relationships among these processing classes are summarized in the following +diagram:: + + list of: + +------+ +---------+ + |module| --DocTestFinder-> | DocTest | --DocTestRunner-> results + +------+ | ^ +---------+ | ^ (printed) + | | | Example | | | + v | | ... | v | + DocTestParser | Example | OutputChecker + +---------+ + + +.. _doctest-doctest: + +DocTest Objects +^^^^^^^^^^^^^^^ + + +.. class:: DocTest(examples, globs, name, filename, lineno, docstring) + + A collection of doctest examples that should be run in a single namespace. The + constructor arguments are used to initialize the attributes of the same names. + + + :class:`DocTest` defines the following attributes. They are initialized by + the constructor, and should not be modified directly. + + + .. attribute:: examples + + A list of :class:`Example` objects encoding the individual interactive Python + examples that should be run by this test. + + + .. attribute:: globs + + The namespace (aka globals) that the examples should be run in. This is a + dictionary mapping names to values. Any changes to the namespace made by the + examples (such as binding new variables) will be reflected in :attr:`globs` + after the test is run. + + + .. attribute:: name + + A string name identifying the :class:`DocTest`. Typically, this is the name + of the object or file that the test was extracted from. + + + .. attribute:: filename + + The name of the file that this :class:`DocTest` was extracted from; or + ``None`` if the filename is unknown, or if the :class:`DocTest` was not + extracted from a file. + + + .. attribute:: lineno + + The line number within :attr:`filename` where this :class:`DocTest` begins, or + ``None`` if the line number is unavailable. This line number is zero-based + with respect to the beginning of the file. + + + .. attribute:: docstring + + The string that the test was extracted from, or ``None`` if the string is + unavailable, or if the test was not extracted from a string. + + +.. _doctest-example: + +Example Objects +^^^^^^^^^^^^^^^ + + +.. class:: Example(source, want, exc_msg=None, lineno=0, indent=0, options=None) + + A single interactive example, consisting of a Python statement and its expected + output. The constructor arguments are used to initialize the attributes of + the same names. + + + :class:`Example` defines the following attributes. They are initialized by + the constructor, and should not be modified directly. + + + .. attribute:: source + + A string containing the example's source code. This source code consists of a + single Python statement, and always ends with a newline; the constructor adds + a newline when necessary. + + + .. attribute:: want + + The expected output from running the example's source code (either from + stdout, or a traceback in case of exception). :attr:`want` ends with a + newline unless no output is expected, in which case it's an empty string. The + constructor adds a newline when necessary. + + + .. attribute:: exc_msg + + The exception message generated by the example, if the example is expected to + generate an exception; or ``None`` if it is not expected to generate an + exception. This exception message is compared against the return value of + :func:`traceback.format_exception_only`. :attr:`exc_msg` ends with a newline + unless it's ``None``. The constructor adds a newline if needed. + + + .. attribute:: lineno + + The line number within the string containing this example where the example + begins. This line number is zero-based with respect to the beginning of the + containing string. + + + .. attribute:: indent + + The example's indentation in the containing string, i.e., the number of space + characters that precede the example's first prompt. + + + .. attribute:: options + + A dictionary mapping from option flags to ``True`` or ``False``, which is used + to override default options for this example. Any option flags not contained + in this dictionary are left at their default value (as specified by the + :class:`DocTestRunner`'s :attr:`optionflags`). By default, no options are set. + + +.. _doctest-doctestfinder: + +DocTestFinder objects +^^^^^^^^^^^^^^^^^^^^^ + + +.. class:: DocTestFinder(verbose=False, parser=DocTestParser(), recurse=True, exclude_empty=True) + + A processing class used to extract the :class:`DocTest`\ s that are relevant to + a given object, from its docstring and the docstrings of its contained objects. + :class:`DocTest`\ s can be extracted from modules, classes, functions, + methods, staticmethods, classmethods, and properties. + + The optional argument *verbose* can be used to display the objects searched by + the finder. It defaults to ``False`` (no output). + + The optional argument *parser* specifies the :class:`DocTestParser` object (or a + drop-in replacement) that is used to extract doctests from docstrings. + + If the optional argument *recurse* is false, then :meth:`DocTestFinder.find` + will only examine the given object, and not any contained objects. + + If the optional argument *exclude_empty* is false, then + :meth:`DocTestFinder.find` will include tests for objects with empty docstrings. + + + :class:`DocTestFinder` defines the following method: + + + .. method:: find(obj[, name][, module][, globs][, extraglobs]) + + Return a list of the :class:`DocTest`\ s that are defined by *obj*'s + docstring, or by any of its contained objects' docstrings. + + The optional argument *name* specifies the object's name; this name will be + used to construct names for the returned :class:`DocTest`\ s. If *name* is + not specified, then ``obj.__name__`` is used. + + The optional parameter *module* is the module that contains the given object. + If the module is not specified or is ``None``, then the test finder will attempt + to automatically determine the correct module. The object's module is used: + + * As a default namespace, if *globs* is not specified. + + * To prevent the DocTestFinder from extracting DocTests from objects that are + imported from other modules. (Contained objects with modules other than + *module* are ignored.) + + * To find the name of the file containing the object. + + * To help find the line number of the object within its file. + + If *module* is ``False``, no attempt to find the module will be made. This is + obscure, of use mostly in testing doctest itself: if *module* is ``False``, or + is ``None`` but cannot be found automatically, then all objects are considered + to belong to the (non-existent) module, so all contained objects will + (recursively) be searched for doctests. + + The globals for each :class:`DocTest` is formed by combining *globs* and + *extraglobs* (bindings in *extraglobs* override bindings in *globs*). A new + shallow copy of the globals dictionary is created for each :class:`DocTest`. + If *globs* is not specified, then it defaults to the module's *__dict__*, if + specified, or ``{}`` otherwise. If *extraglobs* is not specified, then it + defaults to ``{}``. + + +.. _doctest-doctestparser: + +DocTestParser objects +^^^^^^^^^^^^^^^^^^^^^ + + +.. class:: DocTestParser() + + A processing class used to extract interactive examples from a string, and use + them to create a :class:`DocTest` object. + + + :class:`DocTestParser` defines the following methods: + + + .. method:: get_doctest(string, globs, name, filename, lineno) + + Extract all doctest examples from the given string, and collect them into a + :class:`DocTest` object. + + *globs*, *name*, *filename*, and *lineno* are attributes for the new + :class:`DocTest` object. See the documentation for :class:`DocTest` for more + information. + + + .. method:: get_examples(string, name='') + + Extract all doctest examples from the given string, and return them as a list + of :class:`Example` objects. Line numbers are 0-based. The optional argument + *name* is a name identifying this string, and is only used for error messages. + + + .. method:: parse(string, name='') + + Divide the given string into examples and intervening text, and return them as + a list of alternating :class:`Example`\ s and strings. Line numbers for the + :class:`Example`\ s are 0-based. The optional argument *name* is a name + identifying this string, and is only used for error messages. + + +.. _doctest-doctestrunner: + +DocTestRunner objects +^^^^^^^^^^^^^^^^^^^^^ + + +.. class:: DocTestRunner(checker=None, verbose=None, optionflags=0) + + A processing class used to execute and verify the interactive examples in a + :class:`DocTest`. + + The comparison between expected outputs and actual outputs is done by an + :class:`OutputChecker`. This comparison may be customized with a number of + option flags; see section :ref:`doctest-options` for more information. If the + option flags are insufficient, then the comparison may also be customized by + passing a subclass of :class:`OutputChecker` to the constructor. + + The test runner's display output can be controlled in two ways. First, an output + function can be passed to :meth:`TestRunner.run`; this function will be called + with strings that should be displayed. It defaults to ``sys.stdout.write``. If + capturing the output is not sufficient, then the display output can be also + customized by subclassing DocTestRunner, and overriding the methods + :meth:`report_start`, :meth:`report_success`, + :meth:`report_unexpected_exception`, and :meth:`report_failure`. + + The optional keyword argument *checker* specifies the :class:`OutputChecker` + object (or drop-in replacement) that should be used to compare the expected + outputs to the actual outputs of doctest examples. + + The optional keyword argument *verbose* controls the :class:`DocTestRunner`'s + verbosity. If *verbose* is ``True``, then information is printed about each + example, as it is run. If *verbose* is ``False``, then only failures are + printed. If *verbose* is unspecified, or ``None``, then verbose output is used + iff the command-line switch ``-v`` is used. + + The optional keyword argument *optionflags* can be used to control how the test + runner compares expected output to actual output, and how it displays failures. + For more information, see section :ref:`doctest-options`. + + + :class:`DocTestParser` defines the following methods: + + + .. method:: report_start(out, test, example) + + Report that the test runner is about to process the given example. This method + is provided to allow subclasses of :class:`DocTestRunner` to customize their + output; it should not be called directly. + + *example* is the example about to be processed. *test* is the test + *containing example*. *out* is the output function that was passed to + :meth:`DocTestRunner.run`. + + + .. method:: report_success(out, test, example, got) + + Report that the given example ran successfully. This method is provided to + allow subclasses of :class:`DocTestRunner` to customize their output; it + should not be called directly. + + *example* is the example about to be processed. *got* is the actual output + from the example. *test* is the test containing *example*. *out* is the + output function that was passed to :meth:`DocTestRunner.run`. + + + .. method:: report_failure(out, test, example, got) + + Report that the given example failed. This method is provided to allow + subclasses of :class:`DocTestRunner` to customize their output; it should not + be called directly. + + *example* is the example about to be processed. *got* is the actual output + from the example. *test* is the test containing *example*. *out* is the + output function that was passed to :meth:`DocTestRunner.run`. + + + .. method:: report_unexpected_exception(out, test, example, exc_info) + + Report that the given example raised an unexpected exception. This method is + provided to allow subclasses of :class:`DocTestRunner` to customize their + output; it should not be called directly. + + *example* is the example about to be processed. *exc_info* is a tuple + containing information about the unexpected exception (as returned by + :func:`sys.exc_info`). *test* is the test containing *example*. *out* is the + output function that was passed to :meth:`DocTestRunner.run`. + + + .. method:: run(test, compileflags=None, out=None, clear_globs=True) + + Run the examples in *test* (a :class:`DocTest` object), and display the + results using the writer function *out*. + + The examples are run in the namespace ``test.globs``. If *clear_globs* is + true (the default), then this namespace will be cleared after the test runs, + to help with garbage collection. If you would like to examine the namespace + after the test completes, then use *clear_globs=False*. + + *compileflags* gives the set of flags that should be used by the Python + compiler when running the examples. If not specified, then it will default to + the set of future-import flags that apply to *globs*. + + The output of each example is checked using the :class:`DocTestRunner`'s + output checker, and the results are formatted by the + :meth:`DocTestRunner.report_\*` methods. + + + .. method:: summarize(verbose=None) + + Print a summary of all the test cases that have been run by this DocTestRunner, + and return a :term:`named tuple` ``TestResults(failed, attempted)``. + + The optional *verbose* argument controls how detailed the summary is. If the + verbosity is not specified, then the :class:`DocTestRunner`'s verbosity is + used. + +.. _doctest-outputchecker: + +OutputChecker objects +^^^^^^^^^^^^^^^^^^^^^ + + +.. class:: OutputChecker() + + A class used to check the whether the actual output from a doctest example + matches the expected output. :class:`OutputChecker` defines two methods: + :meth:`check_output`, which compares a given pair of outputs, and returns ``True`` + if they match; and :meth:`output_difference`, which returns a string describing + the differences between two outputs. + + + :class:`OutputChecker` defines the following methods: + + .. method:: check_output(want, got, optionflags) + + Return ``True`` iff the actual output from an example (*got*) matches the + expected output (*want*). These strings are always considered to match if + they are identical; but depending on what option flags the test runner is + using, several non-exact match types are also possible. See section + :ref:`doctest-options` for more information about option flags. + + + .. method:: output_difference(example, got, optionflags) + + Return a string describing the differences between the expected output for a + given example (*example*) and the actual output (*got*). *optionflags* is the + set of option flags used to compare *want* and *got*. + + +.. _doctest-debugging: + +Debugging +--------- + +Doctest provides several mechanisms for debugging doctest examples: + +* Several functions convert doctests to executable Python programs, which can be + run under the Python debugger, :mod:`pdb`. + +* The :class:`DebugRunner` class is a subclass of :class:`DocTestRunner` that + raises an exception for the first failing example, containing information about + that example. This information can be used to perform post-mortem debugging on + the example. + +* The :mod:`unittest` cases generated by :func:`DocTestSuite` support the + :meth:`debug` method defined by :class:`unittest.TestCase`. + +* You can add a call to :func:`pdb.set_trace` in a doctest example, and you'll + drop into the Python debugger when that line is executed. Then you can inspect + current values of variables, and so on. For example, suppose :file:`a.py` + contains just this module docstring:: + + """ + >>> def f(x): + ... g(x*2) + >>> def g(x): + ... print(x+3) + ... import pdb; pdb.set_trace() + >>> f(3) + 9 + """ + + Then an interactive Python session may look like this:: + + >>> import a, doctest + >>> doctest.testmod(a) + --Return-- + > (3)g()->None + -> import pdb; pdb.set_trace() + (Pdb) list + 1 def g(x): + 2 print(x+3) + 3 -> import pdb; pdb.set_trace() + [EOF] + (Pdb) p x + 6 + (Pdb) step + --Return-- + > (2)f()->None + -> g(x*2) + (Pdb) list + 1 def f(x): + 2 -> g(x*2) + [EOF] + (Pdb) p x + 3 + (Pdb) step + --Return-- + > (1)?()->None + -> f(3) + (Pdb) cont + (0, 3) + >>> + + +Functions that convert doctests to Python code, and possibly run the synthesized +code under the debugger: + + +.. function:: script_from_examples(s) + + Convert text with examples to a script. + + Argument *s* is a string containing doctest examples. The string is converted + to a Python script, where doctest examples in *s* are converted to regular code, + and everything else is converted to Python comments. The generated script is + returned as a string. For example, :: + + import doctest + print(doctest.script_from_examples(r""" + Set x and y to 1 and 2. + >>> x, y = 1, 2 + + Print their sum: + >>> print(x+y) + 3 + """)) + + displays:: + + # Set x and y to 1 and 2. + x, y = 1, 2 + # + # Print their sum: + print(x+y) + # Expected: + ## 3 + + This function is used internally by other functions (see below), but can also be + useful when you want to transform an interactive Python session into a Python + script. + + +.. function:: testsource(module, name) + + Convert the doctest for an object to a script. + + Argument *module* is a module object, or dotted name of a module, containing the + object whose doctests are of interest. Argument *name* is the name (within the + module) of the object with the doctests of interest. The result is a string, + containing the object's docstring converted to a Python script, as described for + :func:`script_from_examples` above. For example, if module :file:`a.py` + contains a top-level function :func:`f`, then :: + + import a, doctest + print(doctest.testsource(a, "a.f")) + + prints a script version of function :func:`f`'s docstring, with doctests + converted to code, and the rest placed in comments. + + +.. function:: debug(module, name, pm=False) + + Debug the doctests for an object. + + The *module* and *name* arguments are the same as for function + :func:`testsource` above. The synthesized Python script for the named object's + docstring is written to a temporary file, and then that file is run under the + control of the Python debugger, :mod:`pdb`. + + A shallow copy of ``module.__dict__`` is used for both local and global + execution context. + + Optional argument *pm* controls whether post-mortem debugging is used. If *pm* + has a true value, the script file is run directly, and the debugger gets + involved only if the script terminates via raising an unhandled exception. If + it does, then post-mortem debugging is invoked, via :func:`pdb.post_mortem`, + passing the traceback object from the unhandled exception. If *pm* is not + specified, or is false, the script is run under the debugger from the start, via + passing an appropriate :func:`exec` call to :func:`pdb.run`. + + +.. function:: debug_src(src, pm=False, globs=None) + + Debug the doctests in a string. + + This is like function :func:`debug` above, except that a string containing + doctest examples is specified directly, via the *src* argument. + + Optional argument *pm* has the same meaning as in function :func:`debug` above. + + Optional argument *globs* gives a dictionary to use as both local and global + execution context. If not specified, or ``None``, an empty dictionary is used. + If specified, a shallow copy of the dictionary is used. + + +The :class:`DebugRunner` class, and the special exceptions it may raise, are of +most interest to testing framework authors, and will only be sketched here. See +the source code, and especially :class:`DebugRunner`'s docstring (which is a +doctest!) for more details: + + +.. class:: DebugRunner(checker=None, verbose=None, optionflags=0) + + A subclass of :class:`DocTestRunner` that raises an exception as soon as a + failure is encountered. If an unexpected exception occurs, an + :exc:`UnexpectedException` exception is raised, containing the test, the + example, and the original exception. If the output doesn't match, then a + :exc:`DocTestFailure` exception is raised, containing the test, the example, and + the actual output. + + For information about the constructor parameters and methods, see the + documentation for :class:`DocTestRunner` in section :ref:`doctest-advanced-api`. + +There are two exceptions that may be raised by :class:`DebugRunner` instances: + + +.. exception:: DocTestFailure(test, example, got) + + An exception raised by :class:`DocTestRunner` to signal that a doctest example's + actual output did not match its expected output. The constructor arguments are + used to initialize the attributes of the same names. + +:exc:`DocTestFailure` defines the following attributes: + + +.. attribute:: DocTestFailure.test + + The :class:`DocTest` object that was being run when the example failed. + + +.. attribute:: DocTestFailure.example + + The :class:`Example` that failed. + + +.. attribute:: DocTestFailure.got + + The example's actual output. + + +.. exception:: UnexpectedException(test, example, exc_info) + + An exception raised by :class:`DocTestRunner` to signal that a doctest + example raised an unexpected exception. The constructor arguments are used + to initialize the attributes of the same names. + +:exc:`UnexpectedException` defines the following attributes: + + +.. attribute:: UnexpectedException.test + + The :class:`DocTest` object that was being run when the example failed. + + +.. attribute:: UnexpectedException.example + + The :class:`Example` that failed. + + +.. attribute:: UnexpectedException.exc_info + + A tuple containing information about the unexpected exception, as returned by + :func:`sys.exc_info`. + + +.. _doctest-soapbox: + +Soapbox +------- + +As mentioned in the introduction, :mod:`doctest` has grown to have three primary +uses: + +#. Checking examples in docstrings. + +#. Regression testing. + +#. Executable documentation / literate testing. + +These uses have different requirements, and it is important to distinguish them. +In particular, filling your docstrings with obscure test cases makes for bad +documentation. + +When writing a docstring, choose docstring examples with care. There's an art to +this that needs to be learned---it may not be natural at first. Examples should +add genuine value to the documentation. A good example can often be worth many +words. If done with care, the examples will be invaluable for your users, and +will pay back the time it takes to collect them many times over as the years go +by and things change. I'm still amazed at how often one of my :mod:`doctest` +examples stops working after a "harmless" change. + +Doctest also makes an excellent tool for regression testing, especially if you +don't skimp on explanatory text. By interleaving prose and examples, it becomes +much easier to keep track of what's actually being tested, and why. When a test +fails, good prose can make it much easier to figure out what the problem is, and +how it should be fixed. It's true that you could write extensive comments in +code-based testing, but few programmers do. Many have found that using doctest +approaches instead leads to much clearer tests. Perhaps this is simply because +doctest makes writing prose a little easier than writing code, while writing +comments in code is a little harder. I think it goes deeper than just that: +the natural attitude when writing a doctest-based test is that you want to +explain the fine points of your software, and illustrate them with examples. +This in turn naturally leads to test files that start with the simplest +features, and logically progress to complications and edge cases. A coherent +narrative is the result, instead of a collection of isolated functions that test +isolated bits of functionality seemingly at random. It's a different attitude, +and produces different results, blurring the distinction between testing and +explaining. + +Regression testing is best confined to dedicated objects or files. There are +several options for organizing tests: + +* Write text files containing test cases as interactive examples, and test the + files using :func:`testfile` or :func:`DocFileSuite`. This is recommended, + although is easiest to do for new projects, designed from the start to use + doctest. + +* Define functions named ``_regrtest_topic`` that consist of single docstrings, + containing test cases for the named topics. These functions can be included in + the same file as the module, or separated out into a separate test file. + +* Define a ``__test__`` dictionary mapping from regression test topics to + docstrings containing test cases. + +When you have placed your tests in a module, the module can itself be the test +runner. When a test fails, you can arrange for your test runner to re-run only +the failing doctest while you debug the problem. Here is a minimal example of +such a test runner:: + + if __name__ == '__main__': + import doctest + flags = doctest.REPORT_NDIFF|doctest.FAIL_FAST + if len(sys.argv) > 1: + name = sys.argv[1] + if name in globals(): + obj = globals()[name] + else: + obj = __test__[name] + doctest.run_docstring_examples(obj, globals(), name=name, + optionflags=flags) + else: + fail, total = doctest.testmod(optionflags=flags) + print("{} failures out of {} tests".format(fail, total)) + + +.. rubric:: Footnotes + +.. [#] Examples containing both expected output and an exception are not supported. + Trying to guess where one ends and the other begins is too error-prone, and that + also makes for a confusing test. diff --git a/cpython_2/environment/repo/Doc/library/email.charset.rst b/cpython_2/environment/repo/Doc/library/email.charset.rst new file mode 100644 index 0000000000000000000000000000000000000000..38fda23bd8237f1c3b68a936ab3b2d9d911f6613 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/email.charset.rst @@ -0,0 +1,214 @@ +:mod:`email.charset`: Representing character sets +------------------------------------------------- + +.. module:: email.charset + :synopsis: Character Sets + +**Source code:** :source:`Lib/email/charset.py` + +-------------- + +This module is part of the legacy (``Compat32``) email API. In the new +API only the aliases table is used. + +The remaining text in this section is the original documentation of the module. + +This module provides a class :class:`Charset` for representing character sets +and character set conversions in email messages, as well as a character set +registry and several convenience methods for manipulating this registry. +Instances of :class:`Charset` are used in several other modules within the +:mod:`email` package. + +Import this class from the :mod:`email.charset` module. + + +.. class:: Charset(input_charset=DEFAULT_CHARSET) + + Map character sets to their email properties. + + This class provides information about the requirements imposed on email for a + specific character set. It also provides convenience routines for converting + between character sets, given the availability of the applicable codecs. Given + a character set, it will do its best to provide information on how to use that + character set in an email message in an RFC-compliant way. + + Certain character sets must be encoded with quoted-printable or base64 when used + in email headers or bodies. Certain character sets must be converted outright, + and are not allowed in email. + + Optional *input_charset* is as described below; it is always coerced to lower + case. After being alias normalized it is also used as a lookup into the + registry of character sets to find out the header encoding, body encoding, and + output conversion codec to be used for the character set. For example, if + *input_charset* is ``iso-8859-1``, then headers and bodies will be encoded using + quoted-printable and no output conversion codec is necessary. If + *input_charset* is ``euc-jp``, then headers will be encoded with base64, bodies + will not be encoded, but output text will be converted from the ``euc-jp`` + character set to the ``iso-2022-jp`` character set. + + :class:`Charset` instances have the following data attributes: + + .. attribute:: input_charset + + The initial character set specified. Common aliases are converted to + their *official* email names (e.g. ``latin_1`` is converted to + ``iso-8859-1``). Defaults to 7-bit ``us-ascii``. + + + .. attribute:: header_encoding + + If the character set must be encoded before it can be used in an email + header, this attribute will be set to ``Charset.QP`` (for + quoted-printable), ``Charset.BASE64`` (for base64 encoding), or + ``Charset.SHORTEST`` for the shortest of QP or BASE64 encoding. Otherwise, + it will be ``None``. + + + .. attribute:: body_encoding + + Same as *header_encoding*, but describes the encoding for the mail + message's body, which indeed may be different than the header encoding. + ``Charset.SHORTEST`` is not allowed for *body_encoding*. + + + .. attribute:: output_charset + + Some character sets must be converted before they can be used in email + headers or bodies. If the *input_charset* is one of them, this attribute + will contain the name of the character set output will be converted to. + Otherwise, it will be ``None``. + + + .. attribute:: input_codec + + The name of the Python codec used to convert the *input_charset* to + Unicode. If no conversion codec is necessary, this attribute will be + ``None``. + + + .. attribute:: output_codec + + The name of the Python codec used to convert Unicode to the + *output_charset*. If no conversion codec is necessary, this attribute + will have the same value as the *input_codec*. + + + :class:`Charset` instances also have the following methods: + + .. method:: get_body_encoding() + + Return the content transfer encoding used for body encoding. + + This is either the string ``quoted-printable`` or ``base64`` depending on + the encoding used, or it is a function, in which case you should call the + function with a single argument, the Message object being encoded. The + function should then set the :mailheader:`Content-Transfer-Encoding` + header itself to whatever is appropriate. + + Returns the string ``quoted-printable`` if *body_encoding* is ``QP``, + returns the string ``base64`` if *body_encoding* is ``BASE64``, and + returns the string ``7bit`` otherwise. + + + .. method:: get_output_charset() + + Return the output character set. + + This is the *output_charset* attribute if that is not ``None``, otherwise + it is *input_charset*. + + + .. method:: header_encode(string) + + Header-encode the string *string*. + + The type of encoding (base64 or quoted-printable) will be based on the + *header_encoding* attribute. + + + .. method:: header_encode_lines(string, maxlengths) + + Header-encode a *string* by converting it first to bytes. + + This is similar to :meth:`header_encode` except that the string is fit + into maximum line lengths as given by the argument *maxlengths*, which + must be an iterator: each element returned from this iterator will provide + the next maximum line length. + + + .. method:: body_encode(string) + + Body-encode the string *string*. + + The type of encoding (base64 or quoted-printable) will be based on the + *body_encoding* attribute. + + The :class:`Charset` class also provides a number of methods to support + standard operations and built-in functions. + + + .. method:: __str__() + + Returns *input_charset* as a string coerced to lower + case. :meth:`__repr__` is an alias for :meth:`__str__`. + + + .. method:: __eq__(other) + + This method allows you to compare two :class:`Charset` instances for + equality. + + + .. method:: __ne__(other) + + This method allows you to compare two :class:`Charset` instances for + inequality. + +The :mod:`email.charset` module also provides the following functions for adding +new entries to the global character set, alias, and codec registries: + + +.. function:: add_charset(charset, header_enc=None, body_enc=None, output_charset=None) + + Add character properties to the global registry. + + *charset* is the input character set, and must be the canonical name of a + character set. + + Optional *header_enc* and *body_enc* is either ``Charset.QP`` for + quoted-printable, ``Charset.BASE64`` for base64 encoding, + ``Charset.SHORTEST`` for the shortest of quoted-printable or base64 encoding, + or ``None`` for no encoding. ``SHORTEST`` is only valid for + *header_enc*. The default is ``None`` for no encoding. + + Optional *output_charset* is the character set that the output should be in. + Conversions will proceed from input charset, to Unicode, to the output charset + when the method :meth:`Charset.convert` is called. The default is to output in + the same character set as the input. + + Both *input_charset* and *output_charset* must have Unicode codec entries in the + module's character set-to-codec mapping; use :func:`add_codec` to add codecs the + module does not know about. See the :mod:`codecs` module's documentation for + more information. + + The global character set registry is kept in the module global dictionary + ``CHARSETS``. + + +.. function:: add_alias(alias, canonical) + + Add a character set alias. *alias* is the alias name, e.g. ``latin-1``. + *canonical* is the character set's canonical name, e.g. ``iso-8859-1``. + + The global charset alias registry is kept in the module global dictionary + ``ALIASES``. + + +.. function:: add_codec(charset, codecname) + + Add a codec that map characters in the given character set to and from Unicode. + + *charset* is the canonical name of a character set. *codecname* is the name of a + Python codec, as appropriate for the second argument to the :class:`str`'s + :meth:`~str.encode` method. + diff --git a/cpython_2/environment/repo/Doc/library/email.compat32-message.rst b/cpython_2/environment/repo/Doc/library/email.compat32-message.rst new file mode 100644 index 0000000000000000000000000000000000000000..745b3a6a3ad42a73b3c54108f4a0111437ea5093 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/email.compat32-message.rst @@ -0,0 +1,759 @@ +.. _compat32_message: + +:mod:`email.message.Message`: Representing an email message using the :data:`~email.policy.compat32` API +-------------------------------------------------------------------------------------------------------- + +.. module:: email.message + :synopsis: The base class representing email messages in a fashion + backward compatible with Python 3.2 + :noindex: + + +The :class:`Message` class is very similar to the +:class:`~email.message.EmailMessage` class, without the methods added by that +class, and with the default behavior of certain other methods being slightly +different. We also document here some methods that, while supported by the +:class:`~email.message.EmailMessage` class, are not recommended unless you are +dealing with legacy code. + +The philosophy and structure of the two classes is otherwise the same. + +This document describes the behavior under the default (for :class:`Message`) +policy :attr:`~email.policy.Compat32`. If you are going to use another policy, +you should be using the :class:`~email.message.EmailMessage` class instead. + +An email message consists of *headers* and a *payload*. Headers must be +:rfc:`5233` style names and values, where the field name and value are +separated by a colon. The colon is not part of either the field name or the +field value. The payload may be a simple text message, or a binary object, or +a structured sequence of sub-messages each with their own set of headers and +their own payload. The latter type of payload is indicated by the message +having a MIME type such as :mimetype:`multipart/\*` or +:mimetype:`message/rfc822`. + +The conceptual model provided by a :class:`Message` object is that of an +ordered dictionary of headers with additional methods for accessing both +specialized information from the headers, for accessing the payload, for +generating a serialized version of the message, and for recursively walking +over the object tree. Note that duplicate headers are supported but special +methods must be used to access them. + +The :class:`Message` pseudo-dictionary is indexed by the header names, which +must be ASCII values. The values of the dictionary are strings that are +supposed to contain only ASCII characters; there is some special handling for +non-ASCII input, but it doesn't always produce the correct results. Headers +are stored and returned in case-preserving form, but field names are matched +case-insensitively. There may also be a single envelope header, also known as +the *Unix-From* header or the ``From_`` header. The *payload* is either a +string or bytes, in the case of simple message objects, or a list of +:class:`Message` objects, for MIME container documents (e.g. +:mimetype:`multipart/\*` and :mimetype:`message/rfc822`). + +Here are the methods of the :class:`Message` class: + + +.. class:: Message(policy=compat32) + + If *policy* is specified (it must be an instance of a :mod:`~email.policy` + class) use the rules it specifies to update and serialize the representation + of the message. If *policy* is not set, use the :class:`compat32 + ` policy, which maintains backward compatibility with + the Python 3.2 version of the email package. For more information see the + :mod:`~email.policy` documentation. + + .. versionchanged:: 3.3 The *policy* keyword argument was added. + + + .. method:: as_string(unixfrom=False, maxheaderlen=0, policy=None) + + Return the entire message flattened as a string. When optional *unixfrom* + is true, the envelope header is included in the returned string. + *unixfrom* defaults to ``False``. For backward compatibility reasons, + *maxheaderlen* defaults to ``0``, so if you want a different value you + must override it explicitly (the value specified for *max_line_length* in + the policy will be ignored by this method). The *policy* argument may be + used to override the default policy obtained from the message instance. + This can be used to control some of the formatting produced by the + method, since the specified *policy* will be passed to the ``Generator``. + + Flattening the message may trigger changes to the :class:`Message` if + defaults need to be filled in to complete the transformation to a string + (for example, MIME boundaries may be generated or modified). + + Note that this method is provided as a convenience and may not always + format the message the way you want. For example, by default it does + not do the mangling of lines that begin with ``From`` that is + required by the unix mbox format. For more flexibility, instantiate a + :class:`~email.generator.Generator` instance and use its + :meth:`~email.generator.Generator.flatten` method directly. For example:: + + from io import StringIO + from email.generator import Generator + fp = StringIO() + g = Generator(fp, mangle_from_=True, maxheaderlen=60) + g.flatten(msg) + text = fp.getvalue() + + If the message object contains binary data that is not encoded according + to RFC standards, the non-compliant data will be replaced by unicode + "unknown character" code points. (See also :meth:`.as_bytes` and + :class:`~email.generator.BytesGenerator`.) + + .. versionchanged:: 3.4 the *policy* keyword argument was added. + + + .. method:: __str__() + + Equivalent to :meth:`.as_string()`. Allows ``str(msg)`` to produce a + string containing the formatted message. + + + .. method:: as_bytes(unixfrom=False, policy=None) + + Return the entire message flattened as a bytes object. When optional + *unixfrom* is true, the envelope header is included in the returned + string. *unixfrom* defaults to ``False``. The *policy* argument may be + used to override the default policy obtained from the message instance. + This can be used to control some of the formatting produced by the + method, since the specified *policy* will be passed to the + ``BytesGenerator``. + + Flattening the message may trigger changes to the :class:`Message` if + defaults need to be filled in to complete the transformation to a string + (for example, MIME boundaries may be generated or modified). + + Note that this method is provided as a convenience and may not always + format the message the way you want. For example, by default it does + not do the mangling of lines that begin with ``From`` that is + required by the unix mbox format. For more flexibility, instantiate a + :class:`~email.generator.BytesGenerator` instance and use its + :meth:`~email.generator.BytesGenerator.flatten` method directly. + For example:: + + from io import BytesIO + from email.generator import BytesGenerator + fp = BytesIO() + g = BytesGenerator(fp, mangle_from_=True, maxheaderlen=60) + g.flatten(msg) + text = fp.getvalue() + + .. versionadded:: 3.4 + + + .. method:: __bytes__() + + Equivalent to :meth:`.as_bytes()`. Allows ``bytes(msg)`` to produce a + bytes object containing the formatted message. + + .. versionadded:: 3.4 + + + .. method:: is_multipart() + + Return ``True`` if the message's payload is a list of + sub-\ :class:`Message` objects, otherwise return ``False``. When + :meth:`is_multipart` returns ``False``, the payload should be a string + object (which might be a CTE encoded binary payload). (Note that + :meth:`is_multipart` returning ``True`` does not necessarily mean that + "msg.get_content_maintype() == 'multipart'" will return the ``True``. + For example, ``is_multipart`` will return ``True`` when the + :class:`Message` is of type ``message/rfc822``.) + + + .. method:: set_unixfrom(unixfrom) + + Set the message's envelope header to *unixfrom*, which should be a string. + + + .. method:: get_unixfrom() + + Return the message's envelope header. Defaults to ``None`` if the + envelope header was never set. + + + .. method:: attach(payload) + + Add the given *payload* to the current payload, which must be ``None`` or + a list of :class:`Message` objects before the call. After the call, the + payload will always be a list of :class:`Message` objects. If you want to + set the payload to a scalar object (e.g. a string), use + :meth:`set_payload` instead. + + This is a legacy method. On the + :class:`~email.emailmessage.EmailMessage` class its functionality is + replaced by :meth:`~email.message.EmailMessage.set_content` and the + related ``make`` and ``add`` methods. + + + .. method:: get_payload(i=None, decode=False) + + Return the current payload, which will be a list of + :class:`Message` objects when :meth:`is_multipart` is ``True``, or a + string when :meth:`is_multipart` is ``False``. If the payload is a list + and you mutate the list object, you modify the message's payload in place. + + With optional argument *i*, :meth:`get_payload` will return the *i*-th + element of the payload, counting from zero, if :meth:`is_multipart` is + ``True``. An :exc:`IndexError` will be raised if *i* is less than 0 or + greater than or equal to the number of items in the payload. If the + payload is a string (i.e. :meth:`is_multipart` is ``False``) and *i* is + given, a :exc:`TypeError` is raised. + + Optional *decode* is a flag indicating whether the payload should be + decoded or not, according to the :mailheader:`Content-Transfer-Encoding` + header. When ``True`` and the message is not a multipart, the payload will + be decoded if this header's value is ``quoted-printable`` or ``base64``. + If some other encoding is used, or :mailheader:`Content-Transfer-Encoding` + header is missing, the payload is + returned as-is (undecoded). In all cases the returned value is binary + data. If the message is a multipart and the *decode* flag is ``True``, + then ``None`` is returned. If the payload is base64 and it was not + perfectly formed (missing padding, characters outside the base64 + alphabet), then an appropriate defect will be added to the message's + defect property (:class:`~email.errors.InvalidBase64PaddingDefect` or + :class:`~email.errors.InvalidBase64CharactersDefect`, respectively). + + When *decode* is ``False`` (the default) the body is returned as a string + without decoding the :mailheader:`Content-Transfer-Encoding`. However, + for a :mailheader:`Content-Transfer-Encoding` of 8bit, an attempt is made + to decode the original bytes using the ``charset`` specified by the + :mailheader:`Content-Type` header, using the ``replace`` error handler. + If no ``charset`` is specified, or if the ``charset`` given is not + recognized by the email package, the body is decoded using the default + ASCII charset. + + This is a legacy method. On the + :class:`~email.emailmessage.EmailMessage` class its functionality is + replaced by :meth:`~email.message.EmailMessage.get_content` and + :meth:`~email.message.EmailMessage.iter_parts`. + + + .. method:: set_payload(payload, charset=None) + + Set the entire message object's payload to *payload*. It is the client's + responsibility to ensure the payload invariants. Optional *charset* sets + the message's default character set; see :meth:`set_charset` for details. + + This is a legacy method. On the + :class:`~email.emailmessage.EmailMessage` class its functionality is + replaced by :meth:`~email.message.EmailMessage.set_content`. + + + .. method:: set_charset(charset) + + Set the character set of the payload to *charset*, which can either be a + :class:`~email.charset.Charset` instance (see :mod:`email.charset`), a + string naming a character set, or ``None``. If it is a string, it will + be converted to a :class:`~email.charset.Charset` instance. If *charset* + is ``None``, the ``charset`` parameter will be removed from the + :mailheader:`Content-Type` header (the message will not be otherwise + modified). Anything else will generate a :exc:`TypeError`. + + If there is no existing :mailheader:`MIME-Version` header one will be + added. If there is no existing :mailheader:`Content-Type` header, one + will be added with a value of :mimetype:`text/plain`. Whether the + :mailheader:`Content-Type` header already exists or not, its ``charset`` + parameter will be set to *charset.output_charset*. If + *charset.input_charset* and *charset.output_charset* differ, the payload + will be re-encoded to the *output_charset*. If there is no existing + :mailheader:`Content-Transfer-Encoding` header, then the payload will be + transfer-encoded, if needed, using the specified + :class:`~email.charset.Charset`, and a header with the appropriate value + will be added. If a :mailheader:`Content-Transfer-Encoding` header + already exists, the payload is assumed to already be correctly encoded + using that :mailheader:`Content-Transfer-Encoding` and is not modified. + + This is a legacy method. On the + :class:`~email.emailmessage.EmailMessage` class its functionality is + replaced by the *charset* parameter of the + :meth:`email.emailmessage.EmailMessage.set_content` method. + + + .. method:: get_charset() + + Return the :class:`~email.charset.Charset` instance associated with the + message's payload. + + This is a legacy method. On the + :class:`~email.emailmessage.EmailMessage` class it always returns + ``None``. + + + The following methods implement a mapping-like interface for accessing the + message's :rfc:`2822` headers. Note that there are some semantic differences + between these methods and a normal mapping (i.e. dictionary) interface. For + example, in a dictionary there are no duplicate keys, but here there may be + duplicate message headers. Also, in dictionaries there is no guaranteed + order to the keys returned by :meth:`keys`, but in a :class:`Message` object, + headers are always returned in the order they appeared in the original + message, or were added to the message later. Any header deleted and then + re-added are always appended to the end of the header list. + + These semantic differences are intentional and are biased toward maximal + convenience. + + Note that in all cases, any envelope header present in the message is not + included in the mapping interface. + + In a model generated from bytes, any header values that (in contravention of + the RFCs) contain non-ASCII bytes will, when retrieved through this + interface, be represented as :class:`~email.header.Header` objects with + a charset of `unknown-8bit`. + + + .. method:: __len__() + + Return the total number of headers, including duplicates. + + + .. method:: __contains__(name) + + Return ``True`` if the message object has a field named *name*. Matching is + done case-insensitively and *name* should not include the trailing colon. + Used for the ``in`` operator, e.g.:: + + if 'message-id' in myMessage: + print('Message-ID:', myMessage['message-id']) + + + .. method:: __getitem__(name) + + Return the value of the named header field. *name* should not include the + colon field separator. If the header is missing, ``None`` is returned; a + :exc:`KeyError` is never raised. + + Note that if the named field appears more than once in the message's + headers, exactly which of those field values will be returned is + undefined. Use the :meth:`get_all` method to get the values of all the + extant named headers. + + + .. method:: __setitem__(name, val) + + Add a header to the message with field name *name* and value *val*. The + field is appended to the end of the message's existing fields. + + Note that this does *not* overwrite or delete any existing header with the same + name. If you want to ensure that the new header is the only one present in the + message with field name *name*, delete the field first, e.g.:: + + del msg['subject'] + msg['subject'] = 'Python roolz!' + + + .. method:: __delitem__(name) + + Delete all occurrences of the field with name *name* from the message's + headers. No exception is raised if the named field isn't present in the + headers. + + + .. method:: keys() + + Return a list of all the message's header field names. + + + .. method:: values() + + Return a list of all the message's field values. + + + .. method:: items() + + Return a list of 2-tuples containing all the message's field headers and + values. + + + .. method:: get(name, failobj=None) + + Return the value of the named header field. This is identical to + :meth:`__getitem__` except that optional *failobj* is returned if the + named header is missing (defaults to ``None``). + + Here are some additional useful methods: + + + .. method:: get_all(name, failobj=None) + + Return a list of all the values for the field named *name*. If there are + no such named headers in the message, *failobj* is returned (defaults to + ``None``). + + + .. method:: add_header(_name, _value, **_params) + + Extended header setting. This method is similar to :meth:`__setitem__` + except that additional header parameters can be provided as keyword + arguments. *_name* is the header field to add and *_value* is the + *primary* value for the header. + + For each item in the keyword argument dictionary *_params*, the key is + taken as the parameter name, with underscores converted to dashes (since + dashes are illegal in Python identifiers). Normally, the parameter will + be added as ``key="value"`` unless the value is ``None``, in which case + only the key will be added. If the value contains non-ASCII characters, + it can be specified as a three tuple in the format + ``(CHARSET, LANGUAGE, VALUE)``, where ``CHARSET`` is a string naming the + charset to be used to encode the value, ``LANGUAGE`` can usually be set + to ``None`` or the empty string (see :rfc:`2231` for other possibilities), + and ``VALUE`` is the string value containing non-ASCII code points. If + a three tuple is not passed and the value contains non-ASCII characters, + it is automatically encoded in :rfc:`2231` format using a ``CHARSET`` + of ``utf-8`` and a ``LANGUAGE`` of ``None``. + + Here's an example:: + + msg.add_header('Content-Disposition', 'attachment', filename='bud.gif') + + This will add a header that looks like :: + + Content-Disposition: attachment; filename="bud.gif" + + An example with non-ASCII characters:: + + msg.add_header('Content-Disposition', 'attachment', + filename=('iso-8859-1', '', 'Fußballer.ppt')) + + Which produces :: + + Content-Disposition: attachment; filename*="iso-8859-1''Fu%DFballer.ppt" + + + .. method:: replace_header(_name, _value) + + Replace a header. Replace the first header found in the message that + matches *_name*, retaining header order and field name case. If no + matching header was found, a :exc:`KeyError` is raised. + + + .. method:: get_content_type() + + Return the message's content type. The returned string is coerced to + lower case of the form :mimetype:`maintype/subtype`. If there was no + :mailheader:`Content-Type` header in the message the default type as given + by :meth:`get_default_type` will be returned. Since according to + :rfc:`2045`, messages always have a default type, :meth:`get_content_type` + will always return a value. + + :rfc:`2045` defines a message's default type to be :mimetype:`text/plain` + unless it appears inside a :mimetype:`multipart/digest` container, in + which case it would be :mimetype:`message/rfc822`. If the + :mailheader:`Content-Type` header has an invalid type specification, + :rfc:`2045` mandates that the default type be :mimetype:`text/plain`. + + + .. method:: get_content_maintype() + + Return the message's main content type. This is the :mimetype:`maintype` + part of the string returned by :meth:`get_content_type`. + + + .. method:: get_content_subtype() + + Return the message's sub-content type. This is the :mimetype:`subtype` + part of the string returned by :meth:`get_content_type`. + + + .. method:: get_default_type() + + Return the default content type. Most messages have a default content + type of :mimetype:`text/plain`, except for messages that are subparts of + :mimetype:`multipart/digest` containers. Such subparts have a default + content type of :mimetype:`message/rfc822`. + + + .. method:: set_default_type(ctype) + + Set the default content type. *ctype* should either be + :mimetype:`text/plain` or :mimetype:`message/rfc822`, although this is not + enforced. The default content type is not stored in the + :mailheader:`Content-Type` header. + + + .. method:: get_params(failobj=None, header='content-type', unquote=True) + + Return the message's :mailheader:`Content-Type` parameters, as a list. + The elements of the returned list are 2-tuples of key/value pairs, as + split on the ``'='`` sign. The left hand side of the ``'='`` is the key, + while the right hand side is the value. If there is no ``'='`` sign in + the parameter the value is the empty string, otherwise the value is as + described in :meth:`get_param` and is unquoted if optional *unquote* is + ``True`` (the default). + + Optional *failobj* is the object to return if there is no + :mailheader:`Content-Type` header. Optional *header* is the header to + search instead of :mailheader:`Content-Type`. + + This is a legacy method. On the + :class:`~email.emailmessage.EmailMessage` class its functionality is + replaced by the *params* property of the individual header objects + returned by the header access methods. + + + .. method:: get_param(param, failobj=None, header='content-type', unquote=True) + + Return the value of the :mailheader:`Content-Type` header's parameter + *param* as a string. If the message has no :mailheader:`Content-Type` + header or if there is no such parameter, then *failobj* is returned + (defaults to ``None``). + + Optional *header* if given, specifies the message header to use instead of + :mailheader:`Content-Type`. + + Parameter keys are always compared case insensitively. The return value + can either be a string, or a 3-tuple if the parameter was :rfc:`2231` + encoded. When it's a 3-tuple, the elements of the value are of the form + ``(CHARSET, LANGUAGE, VALUE)``. Note that both ``CHARSET`` and + ``LANGUAGE`` can be ``None``, in which case you should consider ``VALUE`` + to be encoded in the ``us-ascii`` charset. You can usually ignore + ``LANGUAGE``. + + If your application doesn't care whether the parameter was encoded as in + :rfc:`2231`, you can collapse the parameter value by calling + :func:`email.utils.collapse_rfc2231_value`, passing in the return value + from :meth:`get_param`. This will return a suitably decoded Unicode + string when the value is a tuple, or the original string unquoted if it + isn't. For example:: + + rawparam = msg.get_param('foo') + param = email.utils.collapse_rfc2231_value(rawparam) + + In any case, the parameter value (either the returned string, or the + ``VALUE`` item in the 3-tuple) is always unquoted, unless *unquote* is set + to ``False``. + + This is a legacy method. On the + :class:`~email.emailmessage.EmailMessage` class its functionality is + replaced by the *params* property of the individual header objects + returned by the header access methods. + + + .. method:: set_param(param, value, header='Content-Type', requote=True, \ + charset=None, language='', replace=False) + + Set a parameter in the :mailheader:`Content-Type` header. If the + parameter already exists in the header, its value will be replaced with + *value*. If the :mailheader:`Content-Type` header as not yet been defined + for this message, it will be set to :mimetype:`text/plain` and the new + parameter value will be appended as per :rfc:`2045`. + + Optional *header* specifies an alternative header to + :mailheader:`Content-Type`, and all parameters will be quoted as necessary + unless optional *requote* is ``False`` (the default is ``True``). + + If optional *charset* is specified, the parameter will be encoded + according to :rfc:`2231`. Optional *language* specifies the RFC 2231 + language, defaulting to the empty string. Both *charset* and *language* + should be strings. + + If *replace* is ``False`` (the default) the header is moved to the + end of the list of headers. If *replace* is ``True``, the header + will be updated in place. + + .. versionchanged:: 3.4 ``replace`` keyword was added. + + + .. method:: del_param(param, header='content-type', requote=True) + + Remove the given parameter completely from the :mailheader:`Content-Type` + header. The header will be re-written in place without the parameter or + its value. All values will be quoted as necessary unless *requote* is + ``False`` (the default is ``True``). Optional *header* specifies an + alternative to :mailheader:`Content-Type`. + + + .. method:: set_type(type, header='Content-Type', requote=True) + + Set the main type and subtype for the :mailheader:`Content-Type` + header. *type* must be a string in the form :mimetype:`maintype/subtype`, + otherwise a :exc:`ValueError` is raised. + + This method replaces the :mailheader:`Content-Type` header, keeping all + the parameters in place. If *requote* is ``False``, this leaves the + existing header's quoting as is, otherwise the parameters will be quoted + (the default). + + An alternative header can be specified in the *header* argument. When the + :mailheader:`Content-Type` header is set a :mailheader:`MIME-Version` + header is also added. + + This is a legacy method. On the + :class:`~email.emailmessage.EmailMessage` class its functionality is + replaced by the ``make_`` and ``add_`` methods. + + + .. method:: get_filename(failobj=None) + + Return the value of the ``filename`` parameter of the + :mailheader:`Content-Disposition` header of the message. If the header + does not have a ``filename`` parameter, this method falls back to looking + for the ``name`` parameter on the :mailheader:`Content-Type` header. If + neither is found, or the header is missing, then *failobj* is returned. + The returned string will always be unquoted as per + :func:`email.utils.unquote`. + + + .. method:: get_boundary(failobj=None) + + Return the value of the ``boundary`` parameter of the + :mailheader:`Content-Type` header of the message, or *failobj* if either + the header is missing, or has no ``boundary`` parameter. The returned + string will always be unquoted as per :func:`email.utils.unquote`. + + + .. method:: set_boundary(boundary) + + Set the ``boundary`` parameter of the :mailheader:`Content-Type` header to + *boundary*. :meth:`set_boundary` will always quote *boundary* if + necessary. A :exc:`~email.errors.HeaderParseError` is raised if the + message object has no :mailheader:`Content-Type` header. + + Note that using this method is subtly different than deleting the old + :mailheader:`Content-Type` header and adding a new one with the new + boundary via :meth:`add_header`, because :meth:`set_boundary` preserves + the order of the :mailheader:`Content-Type` header in the list of + headers. However, it does *not* preserve any continuation lines which may + have been present in the original :mailheader:`Content-Type` header. + + + .. method:: get_content_charset(failobj=None) + + Return the ``charset`` parameter of the :mailheader:`Content-Type` header, + coerced to lower case. If there is no :mailheader:`Content-Type` header, or if + that header has no ``charset`` parameter, *failobj* is returned. + + Note that this method differs from :meth:`get_charset` which returns the + :class:`~email.charset.Charset` instance for the default encoding of the message body. + + + .. method:: get_charsets(failobj=None) + + Return a list containing the character set names in the message. If the + message is a :mimetype:`multipart`, then the list will contain one element + for each subpart in the payload, otherwise, it will be a list of length 1. + + Each item in the list will be a string which is the value of the + ``charset`` parameter in the :mailheader:`Content-Type` header for the + represented subpart. However, if the subpart has no + :mailheader:`Content-Type` header, no ``charset`` parameter, or is not of + the :mimetype:`text` main MIME type, then that item in the returned list + will be *failobj*. + + + .. method:: get_content_disposition() + + Return the lowercased value (without parameters) of the message's + :mailheader:`Content-Disposition` header if it has one, or ``None``. The + possible values for this method are *inline*, *attachment* or ``None`` + if the message follows :rfc:`2183`. + + .. versionadded:: 3.5 + + .. method:: walk() + + The :meth:`walk` method is an all-purpose generator which can be used to + iterate over all the parts and subparts of a message object tree, in + depth-first traversal order. You will typically use :meth:`walk` as the + iterator in a ``for`` loop; each iteration returns the next subpart. + + Here's an example that prints the MIME type of every part of a multipart + message structure: + + .. testsetup:: + + import email + from email import message_from_binary_file + from os.path import join, dirname + lib_dir = dirname(dirname(email.__file__)) + file_path = join(lib_dir, 'test/test_email/data/msg_16.txt') + with open(file_path, 'rb') as f: + msg = message_from_binary_file(f) + from email.iterators import _structure + + .. doctest:: + + >>> for part in msg.walk(): + ... print(part.get_content_type()) + multipart/report + text/plain + message/delivery-status + text/plain + text/plain + message/rfc822 + text/plain + + ``walk`` iterates over the subparts of any part where + :meth:`is_multipart` returns ``True``, even though + ``msg.get_content_maintype() == 'multipart'`` may return ``False``. We + can see this in our example by making use of the ``_structure`` debug + helper function: + + .. doctest:: + + >>> for part in msg.walk(): + ... print(part.get_content_maintype() == 'multipart', + ... part.is_multipart()) + True True + False False + False True + False False + False False + False True + False False + >>> _structure(msg) + multipart/report + text/plain + message/delivery-status + text/plain + text/plain + message/rfc822 + text/plain + + Here the ``message`` parts are not ``multiparts``, but they do contain + subparts. ``is_multipart()`` returns ``True`` and ``walk`` descends + into the subparts. + + + :class:`Message` objects can also optionally contain two instance attributes, + which can be used when generating the plain text of a MIME message. + + + .. attribute:: preamble + + The format of a MIME document allows for some text between the blank line + following the headers, and the first multipart boundary string. Normally, + this text is never visible in a MIME-aware mail reader because it falls + outside the standard MIME armor. However, when viewing the raw text of + the message, or when viewing the message in a non-MIME aware reader, this + text can become visible. + + The *preamble* attribute contains this leading extra-armor text for MIME + documents. When the :class:`~email.parser.Parser` discovers some text + after the headers but before the first boundary string, it assigns this + text to the message's *preamble* attribute. When the + :class:`~email.generator.Generator` is writing out the plain text + representation of a MIME message, and it finds the + message has a *preamble* attribute, it will write this text in the area + between the headers and the first boundary. See :mod:`email.parser` and + :mod:`email.generator` for details. + + Note that if the message object has no preamble, the *preamble* attribute + will be ``None``. + + + .. attribute:: epilogue + + The *epilogue* attribute acts the same way as the *preamble* attribute, + except that it contains text that appears between the last boundary and + the end of the message. + + You do not need to set the epilogue to the empty string in order for the + :class:`~email.generator.Generator` to print a newline at the end of the + file. + + + .. attribute:: defects + + The *defects* attribute contains a list of all the problems found when + parsing this message. See :mod:`email.errors` for a detailed description + of the possible parsing defects. diff --git a/cpython_2/environment/repo/Doc/library/email.contentmanager.rst b/cpython_2/environment/repo/Doc/library/email.contentmanager.rst new file mode 100644 index 0000000000000000000000000000000000000000..e09c7c0e402bbcbebc8c9c941ca889c8ca43416b --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/email.contentmanager.rst @@ -0,0 +1,198 @@ +:mod:`email.contentmanager`: Managing MIME Content +-------------------------------------------------- + +.. module:: email.contentmanager + :synopsis: Storing and Retrieving Content from MIME Parts + +.. moduleauthor:: R. David Murray +.. sectionauthor:: R. David Murray + +**Source code:** :source:`Lib/email/contentmanager.py` + +------------ + +.. versionadded:: 3.6 [1]_ + + +.. class:: ContentManager() + + Base class for content managers. Provides the standard registry mechanisms + to register converters between MIME content and other representations, as + well as the ``get_content`` and ``set_content`` dispatch methods. + + + .. method:: get_content(msg, *args, **kw) + + Look up a handler function based on the ``mimetype`` of *msg* (see next + paragraph), call it, passing through all arguments, and return the result + of the call. The expectation is that the handler will extract the + payload from *msg* and return an object that encodes information about + the extracted data. + + To find the handler, look for the following keys in the registry, + stopping with the first one found: + + * the string representing the full MIME type (``maintype/subtype``) + * the string representing the ``maintype`` + * the empty string + + If none of these keys produce a handler, raise a :exc:`KeyError` for the + full MIME type. + + + .. method:: set_content(msg, obj, *args, **kw) + + If the ``maintype`` is ``multipart``, raise a :exc:`TypeError`; otherwise + look up a handler function based on the type of *obj* (see next + paragraph), call :meth:`~email.message.EmailMessage.clear_content` on the + *msg*, and call the handler function, passing through all arguments. The + expectation is that the handler will transform and store *obj* into + *msg*, possibly making other changes to *msg* as well, such as adding + various MIME headers to encode information needed to interpret the stored + data. + + To find the handler, obtain the type of *obj* (``typ = type(obj)``), and + look for the following keys in the registry, stopping with the first one + found: + + * the type itself (``typ``) + * the type's fully qualified name (``typ.__module__ + '.' + + typ.__qualname__``). + * the type's qualname (``typ.__qualname__``) + * the type's name (``typ.__name__``). + + If none of the above match, repeat all of the checks above for each of + the types in the :term:`MRO` (``typ.__mro__``). Finally, if no other key + yields a handler, check for a handler for the key ``None``. If there is + no handler for ``None``, raise a :exc:`KeyError` for the fully + qualified name of the type. + + Also add a :mailheader:`MIME-Version` header if one is not present (see + also :class:`.MIMEPart`). + + + .. method:: add_get_handler(key, handler) + + Record the function *handler* as the handler for *key*. For the possible + values of *key*, see :meth:`get_content`. + + + .. method:: add_set_handler(typekey, handler) + + Record *handler* as the function to call when an object of a type + matching *typekey* is passed to :meth:`set_content`. For the possible + values of *typekey*, see :meth:`set_content`. + + +Content Manager Instances +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Currently the email package provides only one concrete content manager, +:data:`raw_data_manager`, although more may be added in the future. +:data:`raw_data_manager` is the +:attr:`~email.policy.EmailPolicy.content_manager` provided by +:attr:`~email.policy.EmailPolicy` and its derivatives. + + +.. data:: raw_data_manager + + This content manager provides only a minimum interface beyond that provided + by :class:`~email.message.Message` itself: it deals only with text, raw + byte strings, and :class:`~email.message.Message` objects. Nevertheless, it + provides significant advantages compared to the base API: ``get_content`` on + a text part will return a unicode string without the application needing to + manually decode it, ``set_content`` provides a rich set of options for + controlling the headers added to a part and controlling the content transfer + encoding, and it enables the use of the various ``add_`` methods, thereby + simplifying the creation of multipart messages. + + .. method:: get_content(msg, errors='replace') + + Return the payload of the part as either a string (for ``text`` parts), an + :class:`~email.message.EmailMessage` object (for ``message/rfc822`` + parts), or a ``bytes`` object (for all other non-multipart types). Raise + a :exc:`KeyError` if called on a ``multipart``. If the part is a + ``text`` part and *errors* is specified, use it as the error handler when + decoding the payload to unicode. The default error handler is + ``replace``. + + .. method:: set_content(msg, <'str'>, subtype="plain", charset='utf-8' \ + cte=None, \ + disposition=None, filename=None, cid=None, \ + params=None, headers=None) + set_content(msg, <'bytes'>, maintype, subtype, cte="base64", \ + disposition=None, filename=None, cid=None, \ + params=None, headers=None) + set_content(msg, <'EmailMessage'>, cte=None, \ + disposition=None, filename=None, cid=None, \ + params=None, headers=None) + + Add headers and payload to *msg*: + + Add a :mailheader:`Content-Type` header with a ``maintype/subtype`` + value. + + * For ``str``, set the MIME ``maintype`` to ``text``, and set the + subtype to *subtype* if it is specified, or ``plain`` if it is not. + * For ``bytes``, use the specified *maintype* and *subtype*, or + raise a :exc:`TypeError` if they are not specified. + * For :class:`~email.message.EmailMessage` objects, set the maintype + to ``message``, and set the subtype to *subtype* if it is + specified or ``rfc822`` if it is not. If *subtype* is + ``partial``, raise an error (``bytes`` objects must be used to + construct ``message/partial`` parts). + + If *charset* is provided (which is valid only for ``str``), encode the + string to bytes using the specified character set. The default is + ``utf-8``. If the specified *charset* is a known alias for a standard + MIME charset name, use the standard charset instead. + + If *cte* is set, encode the payload using the specified content transfer + encoding, and set the :mailheader:`Content-Transfer-Encoding` header to + that value. Possible values for *cte* are ``quoted-printable``, + ``base64``, ``7bit``, ``8bit``, and ``binary``. If the input cannot be + encoded in the specified encoding (for example, specifying a *cte* of + ``7bit`` for an input that contains non-ASCII values), raise a + :exc:`ValueError`. + + * For ``str`` objects, if *cte* is not set use heuristics to + determine the most compact encoding. + * For :class:`~email.message.EmailMessage`, per :rfc:`2046`, raise + an error if a *cte* of ``quoted-printable`` or ``base64`` is + requested for *subtype* ``rfc822``, and for any *cte* other than + ``7bit`` for *subtype* ``external-body``. For + ``message/rfc822``, use ``8bit`` if *cte* is not specified. For + all other values of *subtype*, use ``7bit``. + + .. note:: A *cte* of ``binary`` does not actually work correctly yet. + The ``EmailMessage`` object as modified by ``set_content`` is + correct, but :class:`~email.generator.BytesGenerator` does not + serialize it correctly. + + If *disposition* is set, use it as the value of the + :mailheader:`Content-Disposition` header. If not specified, and + *filename* is specified, add the header with the value ``attachment``. + If *disposition* is not specified and *filename* is also not specified, + do not add the header. The only valid values for *disposition* are + ``attachment`` and ``inline``. + + If *filename* is specified, use it as the value of the ``filename`` + parameter of the :mailheader:`Content-Disposition` header. + + If *cid* is specified, add a :mailheader:`Content-ID` header with + *cid* as its value. + + If *params* is specified, iterate its ``items`` method and use the + resulting ``(key, value)`` pairs to set additional parameters on the + :mailheader:`Content-Type` header. + + If *headers* is specified and is a list of strings of the form + ``headername: headervalue`` or a list of ``header`` objects + (distinguished from strings by having a ``name`` attribute), add the + headers to *msg*. + + +.. rubric:: Footnotes + +.. [1] Originally added in 3.4 as a :term:`provisional module ` diff --git a/cpython_2/environment/repo/Doc/library/email.encoders.rst b/cpython_2/environment/repo/Doc/library/email.encoders.rst new file mode 100644 index 0000000000000000000000000000000000000000..5d68b104f3a45c60660e78f467caf5103de08ef0 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/email.encoders.rst @@ -0,0 +1,75 @@ +:mod:`email.encoders`: Encoders +------------------------------- + +.. module:: email.encoders + :synopsis: Encoders for email message payloads. + +**Source code:** :source:`Lib/email/encoders.py` + +-------------- + +This module is part of the legacy (``Compat32``) email API. In the +new API the functionality is provided by the *cte* parameter of +the :meth:`~email.message.EmailMessage.set_content` method. + +This module is deprecated in Python 3. The functions provided here +should not be called explicitly since the :class:`~email.mime.text.MIMEText` +class sets the content type and CTE header using the *_subtype* and *_charset* +values passed during the instantiation of that class. + +The remaining text in this section is the original documentation of the module. + +When creating :class:`~email.message.Message` objects from scratch, you often +need to encode the payloads for transport through compliant mail servers. This +is especially true for :mimetype:`image/\*` and :mimetype:`text/\*` type messages +containing binary data. + +The :mod:`email` package provides some convenient encoders in its +:mod:`encoders` module. These encoders are actually used by the +:class:`~email.mime.audio.MIMEAudio` and :class:`~email.mime.image.MIMEImage` +class constructors to provide default encodings. All encoder functions take +exactly one argument, the message object to encode. They usually extract the +payload, encode it, and reset the payload to this newly encoded value. They +should also set the :mailheader:`Content-Transfer-Encoding` header as appropriate. + +Note that these functions are not meaningful for a multipart message. They +must be applied to individual subparts instead, and will raise a +:exc:`TypeError` if passed a message whose type is multipart. + +Here are the encoding functions provided: + + +.. function:: encode_quopri(msg) + + Encodes the payload into quoted-printable form and sets the + :mailheader:`Content-Transfer-Encoding` header to ``quoted-printable`` [#]_. + This is a good encoding to use when most of your payload is normal printable + data, but contains a few unprintable characters. + + +.. function:: encode_base64(msg) + + Encodes the payload into base64 form and sets the + :mailheader:`Content-Transfer-Encoding` header to ``base64``. This is a good + encoding to use when most of your payload is unprintable data since it is a more + compact form than quoted-printable. The drawback of base64 encoding is that it + renders the text non-human readable. + + +.. function:: encode_7or8bit(msg) + + This doesn't actually modify the message's payload, but it does set the + :mailheader:`Content-Transfer-Encoding` header to either ``7bit`` or ``8bit`` as + appropriate, based on the payload data. + + +.. function:: encode_noop(msg) + + This does nothing; it doesn't even set the + :mailheader:`Content-Transfer-Encoding` header. + +.. rubric:: Footnotes + +.. [#] Note that encoding with :meth:`encode_quopri` also encodes all tabs and space + characters in the data. + diff --git a/cpython_2/environment/repo/Doc/library/email.errors.rst b/cpython_2/environment/repo/Doc/library/email.errors.rst new file mode 100644 index 0000000000000000000000000000000000000000..f4b9f52509689ea2fd7ac0b5b512edd0836623bc --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/email.errors.rst @@ -0,0 +1,114 @@ +:mod:`email.errors`: Exception and Defect classes +------------------------------------------------- + +.. module:: email.errors + :synopsis: The exception classes used by the email package. + +**Source code:** :source:`Lib/email/errors.py` + +-------------- + +The following exception classes are defined in the :mod:`email.errors` module: + + +.. exception:: MessageError() + + This is the base class for all exceptions that the :mod:`email` package can + raise. It is derived from the standard :exc:`Exception` class and defines no + additional methods. + + +.. exception:: MessageParseError() + + This is the base class for exceptions raised by the + :class:`~email.parser.Parser` class. It is derived from + :exc:`MessageError`. This class is also used internally by the parser used + by :mod:`~email.headerregistry`. + + +.. exception:: HeaderParseError() + + Raised under some error conditions when parsing the :rfc:`5322` headers of a + message, this class is derived from :exc:`MessageParseError`. The + :meth:`~email.message.EmailMessage.set_boundary` method will raise this + error if the content type is unknown when the method is called. + :class:`~email.header.Header` may raise this error for certain base64 + decoding errors, and when an attempt is made to create a header that appears + to contain an embedded header (that is, there is what is supposed to be a + continuation line that has no leading whitespace and looks like a header). + + +.. exception:: BoundaryError() + + Deprecated and no longer used. + + +.. exception:: MultipartConversionError() + + Raised when a payload is added to a :class:`~email.message.Message` object + using :meth:`add_payload`, but the payload is already a scalar and the + message's :mailheader:`Content-Type` main type is not either + :mimetype:`multipart` or missing. :exc:`MultipartConversionError` multiply + inherits from :exc:`MessageError` and the built-in :exc:`TypeError`. + + Since :meth:`Message.add_payload` is deprecated, this exception is rarely + raised in practice. However the exception may also be raised if the + :meth:`~email.message.Message.attach` + method is called on an instance of a class derived from + :class:`~email.mime.nonmultipart.MIMENonMultipart` (e.g. + :class:`~email.mime.image.MIMEImage`). + + +Here is the list of the defects that the :class:`~email.parser.FeedParser` +can find while parsing messages. Note that the defects are added to the message +where the problem was found, so for example, if a message nested inside a +:mimetype:`multipart/alternative` had a malformed header, that nested message +object would have a defect, but the containing messages would not. + +All defect classes are subclassed from :class:`email.errors.MessageDefect`. + +* :class:`NoBoundaryInMultipartDefect` -- A message claimed to be a multipart, + but had no :mimetype:`boundary` parameter. + +* :class:`StartBoundaryNotFoundDefect` -- The start boundary claimed in the + :mailheader:`Content-Type` header was never found. + +* :class:`CloseBoundaryNotFoundDefect` -- A start boundary was found, but + no corresponding close boundary was ever found. + + .. versionadded:: 3.3 + +* :class:`FirstHeaderLineIsContinuationDefect` -- The message had a continuation + line as its first header line. + +* :class:`MisplacedEnvelopeHeaderDefect` - A "Unix From" header was found in the + middle of a header block. + +* :class:`MissingHeaderBodySeparatorDefect` - A line was found while parsing + headers that had no leading white space but contained no ':'. Parsing + continues assuming that the line represents the first line of the body. + + .. versionadded:: 3.3 + +* :class:`MalformedHeaderDefect` -- A header was found that was missing a colon, + or was otherwise malformed. + + .. deprecated:: 3.3 + This defect has not been used for several Python versions. + +* :class:`MultipartInvariantViolationDefect` -- A message claimed to be a + :mimetype:`multipart`, but no subparts were found. Note that when a message + has this defect, its :meth:`~email.message.Message.is_multipart` method may + return ``False`` even though its content type claims to be :mimetype:`multipart`. + +* :class:`InvalidBase64PaddingDefect` -- When decoding a block of base64 + encoded bytes, the padding was not correct. Enough padding is added to + perform the decode, but the resulting decoded bytes may be invalid. + +* :class:`InvalidBase64CharactersDefect` -- When decoding a block of base64 + encoded bytes, characters outside the base64 alphabet were encountered. + The characters are ignored, but the resulting decoded bytes may be invalid. + +* :class:`InvalidBase64LengthDefect` -- When decoding a block of base64 encoded + bytes, the number of non-padding base64 characters was invalid (1 more than + a multiple of 4). The encoded block was kept as-is. diff --git a/cpython_2/environment/repo/Doc/library/email.examples.rst b/cpython_2/environment/repo/Doc/library/email.examples.rst new file mode 100644 index 0000000000000000000000000000000000000000..fc964622809d0e89ae93d5545bf2bab51ac363cc --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/email.examples.rst @@ -0,0 +1,67 @@ +.. _email-examples: + +:mod:`email`: Examples +---------------------- + +Here are a few examples of how to use the :mod:`email` package to read, write, +and send simple email messages, as well as more complex MIME messages. + +First, let's see how to create and send a simple text message (both the +text content and the addresses may contain unicode characters): + +.. literalinclude:: ../includes/email-simple.py + + +Parsing :rfc:`822` headers can easily be done by the using the classes +from the :mod:`~email.parser` module: + +.. literalinclude:: ../includes/email-headers.py + + +Here's an example of how to send a MIME message containing a bunch of family +pictures that may be residing in a directory: + +.. literalinclude:: ../includes/email-mime.py + + +Here's an example of how to send the entire contents of a directory as an email +message: [1]_ + +.. literalinclude:: ../includes/email-dir.py + + +Here's an example of how to unpack a MIME message like the one +above, into a directory of files: + +.. literalinclude:: ../includes/email-unpack.py + + +Here's an example of how to create an HTML message with an alternative plain +text version. To make things a bit more interesting, we include a related +image in the html part, and we save a copy of what we are going to send to +disk, as well as sending it. + +.. literalinclude:: ../includes/email-alternative.py + + +If we were sent the message from the last example, here is one way we could +process it: + +.. literalinclude:: ../includes/email-read-alternative.py + +Up to the prompt, the output from the above is: + +.. code-block:: none + + To: Penelope Pussycat , Fabrette Pussycat + From: Pepé Le Pew + Subject: Ayons asperges pour le déjeuner + + Salut! + + Cela ressemble à un excellent recipie[1] déjeuner. + + +.. rubric:: Footnotes + +.. [1] Thanks to Matthew Dixon Cowles for the original inspiration and examples. diff --git a/cpython_2/environment/repo/Doc/library/email.generator.rst b/cpython_2/environment/repo/Doc/library/email.generator.rst new file mode 100644 index 0000000000000000000000000000000000000000..2d9bae6a7ee57b1ed789a80b11d7eea6a313a3c2 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/email.generator.rst @@ -0,0 +1,283 @@ +:mod:`email.generator`: Generating MIME documents +------------------------------------------------- + +.. module:: email.generator + :synopsis: Generate flat text email messages from a message structure. + +**Source code:** :source:`Lib/email/generator.py` + +-------------- + +One of the most common tasks is to generate the flat (serialized) version of +the email message represented by a message object structure. You will need to +do this if you want to send your message via :meth:`smtplib.SMTP.sendmail` or +the :mod:`nntplib` module, or print the message on the console. Taking a +message object structure and producing a serialized representation is the job +of the generator classes. + +As with the :mod:`email.parser` module, you aren't limited to the functionality +of the bundled generator; you could write one from scratch yourself. However +the bundled generator knows how to generate most email in a standards-compliant +way, should handle MIME and non-MIME email messages just fine, and is designed +so that the bytes-oriented parsing and generation operations are inverses, +assuming the same non-transforming :mod:`~email.policy` is used for both. That +is, parsing the serialized byte stream via the +:class:`~email.parser.BytesParser` class and then regenerating the serialized +byte stream using :class:`BytesGenerator` should produce output identical to +the input [#]_. (On the other hand, using the generator on an +:class:`~email.message.EmailMessage` constructed by program may result in +changes to the :class:`~email.message.EmailMessage` object as defaults are +filled in.) + +The :class:`Generator` class can be used to flatten a message into a text (as +opposed to binary) serialized representation, but since Unicode cannot +represent binary data directly, the message is of necessity transformed into +something that contains only ASCII characters, using the standard email RFC +Content Transfer Encoding techniques for encoding email messages for transport +over channels that are not "8 bit clean". + +To accommodate reproducible processing of SMIME-signed messages +:class:`Generator` disables header folding for message parts of type +``multipart/signed`` and all subparts. + + +.. class:: BytesGenerator(outfp, mangle_from_=None, maxheaderlen=None, *, \ + policy=None) + + Return a :class:`BytesGenerator` object that will write any message provided + to the :meth:`flatten` method, or any surrogateescape encoded text provided + to the :meth:`write` method, to the :term:`file-like object` *outfp*. + *outfp* must support a ``write`` method that accepts binary data. + + If optional *mangle_from_* is ``True``, put a ``>`` character in front of + any line in the body that starts with the exact string ``"From "``, that is + ``From`` followed by a space at the beginning of a line. *mangle_from_* + defaults to the value of the :attr:`~email.policy.Policy.mangle_from_` + setting of the *policy* (which is ``True`` for the + :data:`~email.policy.compat32` policy and ``False`` for all others). + *mangle_from_* is intended for use when messages are stored in unix mbox + format (see :mod:`mailbox` and `WHY THE CONTENT-LENGTH FORMAT IS BAD + `_). + + If *maxheaderlen* is not ``None``, refold any header lines that are longer + than *maxheaderlen*, or if ``0``, do not rewrap any headers. If + *manheaderlen* is ``None`` (the default), wrap headers and other message + lines according to the *policy* settings. + + If *policy* is specified, use that policy to control message generation. If + *policy* is ``None`` (the default), use the policy associated with the + :class:`~email.message.Message` or :class:`~email.message.EmailMessage` + object passed to ``flatten`` to control the message generation. See + :mod:`email.policy` for details on what *policy* controls. + + .. versionadded:: 3.2 + + .. versionchanged:: 3.3 Added the *policy* keyword. + + .. versionchanged:: 3.6 The default behavior of the *mangle_from_* + and *maxheaderlen* parameters is to follow the policy. + + + .. method:: flatten(msg, unixfrom=False, linesep=None) + + Print the textual representation of the message object structure rooted + at *msg* to the output file specified when the :class:`BytesGenerator` + instance was created. + + If the :mod:`~email.policy` option :attr:`~email.policy.Policy.cte_type` + is ``8bit`` (the default), copy any headers in the original parsed + message that have not been modified to the output with any bytes with the + high bit set reproduced as in the original, and preserve the non-ASCII + :mailheader:`Content-Transfer-Encoding` of any body parts that have them. + If ``cte_type`` is ``7bit``, convert the bytes with the high bit set as + needed using an ASCII-compatible :mailheader:`Content-Transfer-Encoding`. + That is, transform parts with non-ASCII + :mailheader:`Content-Transfer-Encoding` + (:mailheader:`Content-Transfer-Encoding: 8bit`) to an ASCII compatible + :mailheader:`Content-Transfer-Encoding`, and encode RFC-invalid non-ASCII + bytes in headers using the MIME ``unknown-8bit`` character set, thus + rendering them RFC-compliant. + + .. XXX: There should be an option that just does the RFC + compliance transformation on headers but leaves CTE 8bit parts alone. + + If *unixfrom* is ``True``, print the envelope header delimiter used by + the Unix mailbox format (see :mod:`mailbox`) before the first of the + :rfc:`5322` headers of the root message object. If the root object has + no envelope header, craft a standard one. The default is ``False``. + Note that for subparts, no envelope header is ever printed. + + If *linesep* is not ``None``, use it as the separator character between + all the lines of the flattened message. If *linesep* is ``None`` (the + default), use the value specified in the *policy*. + + .. XXX: flatten should take a *policy* keyword. + + + .. method:: clone(fp) + + Return an independent clone of this :class:`BytesGenerator` instance with + the exact same option settings, and *fp* as the new *outfp*. + + + .. method:: write(s) + + Encode *s* using the ``ASCII`` codec and the ``surrogateescape`` error + handler, and pass it to the *write* method of the *outfp* passed to the + :class:`BytesGenerator`'s constructor. + + +As a convenience, :class:`~email.message.EmailMessage` provides the methods +:meth:`~email.message.EmailMessage.as_bytes` and ``bytes(aMessage)`` (a.k.a. +:meth:`~email.message.EmailMessage.__bytes__`), which simplify the generation of +a serialized binary representation of a message object. For more detail, see +:mod:`email.message`. + + +Because strings cannot represent binary data, the :class:`Generator` class must +convert any binary data in any message it flattens to an ASCII compatible +format, by converting them to an ASCII compatible +:mailheader:`Content-Transfer_Encoding`. Using the terminology of the email +RFCs, you can think of this as :class:`Generator` serializing to an I/O stream +that is not "8 bit clean". In other words, most applications will want +to be using :class:`BytesGenerator`, and not :class:`Generator`. + +.. class:: Generator(outfp, mangle_from_=None, maxheaderlen=None, *, \ + policy=None) + + Return a :class:`Generator` object that will write any message provided + to the :meth:`flatten` method, or any text provided to the :meth:`write` + method, to the :term:`file-like object` *outfp*. *outfp* must support a + ``write`` method that accepts string data. + + If optional *mangle_from_* is ``True``, put a ``>`` character in front of + any line in the body that starts with the exact string ``"From "``, that is + ``From`` followed by a space at the beginning of a line. *mangle_from_* + defaults to the value of the :attr:`~email.policy.Policy.mangle_from_` + setting of the *policy* (which is ``True`` for the + :data:`~email.policy.compat32` policy and ``False`` for all others). + *mangle_from_* is intended for use when messages are stored in unix mbox + format (see :mod:`mailbox` and `WHY THE CONTENT-LENGTH FORMAT IS BAD + `_). + + If *maxheaderlen* is not ``None``, refold any header lines that are longer + than *maxheaderlen*, or if ``0``, do not rewrap any headers. If + *manheaderlen* is ``None`` (the default), wrap headers and other message + lines according to the *policy* settings. + + If *policy* is specified, use that policy to control message generation. If + *policy* is ``None`` (the default), use the policy associated with the + :class:`~email.message.Message` or :class:`~email.message.EmailMessage` + object passed to ``flatten`` to control the message generation. See + :mod:`email.policy` for details on what *policy* controls. + + .. versionchanged:: 3.3 Added the *policy* keyword. + + .. versionchanged:: 3.6 The default behavior of the *mangle_from_* + and *maxheaderlen* parameters is to follow the policy. + + + .. method:: flatten(msg, unixfrom=False, linesep=None) + + Print the textual representation of the message object structure rooted + at *msg* to the output file specified when the :class:`Generator` + instance was created. + + If the :mod:`~email.policy` option :attr:`~email.policy.Policy.cte_type` + is ``8bit``, generate the message as if the option were set to ``7bit``. + (This is required because strings cannot represent non-ASCII bytes.) + Convert any bytes with the high bit set as needed using an + ASCII-compatible :mailheader:`Content-Transfer-Encoding`. That is, + transform parts with non-ASCII :mailheader:`Content-Transfer-Encoding` + (:mailheader:`Content-Transfer-Encoding: 8bit`) to an ASCII compatible + :mailheader:`Content-Transfer-Encoding`, and encode RFC-invalid non-ASCII + bytes in headers using the MIME ``unknown-8bit`` character set, thus + rendering them RFC-compliant. + + If *unixfrom* is ``True``, print the envelope header delimiter used by + the Unix mailbox format (see :mod:`mailbox`) before the first of the + :rfc:`5322` headers of the root message object. If the root object has + no envelope header, craft a standard one. The default is ``False``. + Note that for subparts, no envelope header is ever printed. + + If *linesep* is not ``None``, use it as the separator character between + all the lines of the flattened message. If *linesep* is ``None`` (the + default), use the value specified in the *policy*. + + .. XXX: flatten should take a *policy* keyword. + + .. versionchanged:: 3.2 + Added support for re-encoding ``8bit`` message bodies, and the + *linesep* argument. + + + .. method:: clone(fp) + + Return an independent clone of this :class:`Generator` instance with the + exact same options, and *fp* as the new *outfp*. + + + .. method:: write(s) + + Write *s* to the *write* method of the *outfp* passed to the + :class:`Generator`'s constructor. This provides just enough file-like + API for :class:`Generator` instances to be used in the :func:`print` + function. + + +As a convenience, :class:`~email.message.EmailMessage` provides the methods +:meth:`~email.message.EmailMessage.as_string` and ``str(aMessage)`` (a.k.a. +:meth:`~email.message.EmailMessage.__str__`), which simplify the generation of +a formatted string representation of a message object. For more detail, see +:mod:`email.message`. + + +The :mod:`email.generator` module also provides a derived class, +:class:`DecodedGenerator`, which is like the :class:`Generator` base class, +except that non-\ :mimetype:`text` parts are not serialized, but are instead +represented in the output stream by a string derived from a template filled +in with information about the part. + +.. class:: DecodedGenerator(outfp, mangle_from_=None, maxheaderlen=None, \ + fmt=None, *, policy=None) + + Act like :class:`Generator`, except that for any subpart of the message + passed to :meth:`Generator.flatten`, if the subpart is of main type + :mimetype:`text`, print the decoded payload of the subpart, and if the main + type is not :mimetype:`text`, instead of printing it fill in the string + *fmt* using information from the part and print the resulting + filled-in string. + + To fill in *fmt*, execute ``fmt % part_info``, where ``part_info`` + is a dictionary composed of the following keys and values: + + * ``type`` -- Full MIME type of the non-\ :mimetype:`text` part + + * ``maintype`` -- Main MIME type of the non-\ :mimetype:`text` part + + * ``subtype`` -- Sub-MIME type of the non-\ :mimetype:`text` part + + * ``filename`` -- Filename of the non-\ :mimetype:`text` part + + * ``description`` -- Description associated with the non-\ :mimetype:`text` part + + * ``encoding`` -- Content transfer encoding of the non-\ :mimetype:`text` part + + If *fmt* is ``None``, use the following default *fmt*: + + "[Non-text (%(type)s) part of message omitted, filename %(filename)s]" + + Optional *_mangle_from_* and *maxheaderlen* are as with the + :class:`Generator` base class. + + +.. rubric:: Footnotes + +.. [#] This statement assumes that you use the appropriate setting for + ``unixfrom``, and that there are no :mod:`policy` settings calling for + automatic adjustments (for example, + :attr:`~email.policy.Policy.refold_source` must be ``none``, which is + *not* the default). It is also not 100% true, since if the message + does not conform to the RFC standards occasionally information about the + exact original text is lost during parsing error recovery. It is a goal + to fix these latter edge cases when possible. diff --git a/cpython_2/environment/repo/Doc/library/email.header.rst b/cpython_2/environment/repo/Doc/library/email.header.rst new file mode 100644 index 0000000000000000000000000000000000000000..07152c224f2ff0865aee9561757733f69c5e2d80 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/email.header.rst @@ -0,0 +1,205 @@ +:mod:`email.header`: Internationalized headers +---------------------------------------------- + +.. module:: email.header + :synopsis: Representing non-ASCII headers + +**Source code:** :source:`Lib/email/header.py` + +-------------- + +This module is part of the legacy (``Compat32``) email API. In the current API +encoding and decoding of headers is handled transparently by the +dictionary-like API of the :class:`~email.message.EmailMessage` class. In +addition to uses in legacy code, this module can be useful in applications that +need to completely control the character sets used when encoding headers. + +The remaining text in this section is the original documentation of the module. + +:rfc:`2822` is the base standard that describes the format of email messages. +It derives from the older :rfc:`822` standard which came into widespread use at +a time when most email was composed of ASCII characters only. :rfc:`2822` is a +specification written assuming email contains only 7-bit ASCII characters. + +Of course, as email has been deployed worldwide, it has become +internationalized, such that language specific character sets can now be used in +email messages. The base standard still requires email messages to be +transferred using only 7-bit ASCII characters, so a slew of RFCs have been +written describing how to encode email containing non-ASCII characters into +:rfc:`2822`\ -compliant format. These RFCs include :rfc:`2045`, :rfc:`2046`, +:rfc:`2047`, and :rfc:`2231`. The :mod:`email` package supports these standards +in its :mod:`email.header` and :mod:`email.charset` modules. + +If you want to include non-ASCII characters in your email headers, say in the +:mailheader:`Subject` or :mailheader:`To` fields, you should use the +:class:`Header` class and assign the field in the :class:`~email.message.Message` +object to an instance of :class:`Header` instead of using a string for the header +value. Import the :class:`Header` class from the :mod:`email.header` module. +For example:: + + >>> from email.message import Message + >>> from email.header import Header + >>> msg = Message() + >>> h = Header('p\xf6stal', 'iso-8859-1') + >>> msg['Subject'] = h + >>> msg.as_string() + 'Subject: =?iso-8859-1?q?p=F6stal?=\n\n' + + + +Notice here how we wanted the :mailheader:`Subject` field to contain a non-ASCII +character? We did this by creating a :class:`Header` instance and passing in +the character set that the byte string was encoded in. When the subsequent +:class:`~email.message.Message` instance was flattened, the :mailheader:`Subject` +field was properly :rfc:`2047` encoded. MIME-aware mail readers would show this +header using the embedded ISO-8859-1 character. + +Here is the :class:`Header` class description: + + +.. class:: Header(s=None, charset=None, maxlinelen=None, header_name=None, continuation_ws=' ', errors='strict') + + Create a MIME-compliant header that can contain strings in different character + sets. + + Optional *s* is the initial header value. If ``None`` (the default), the + initial header value is not set. You can later append to the header with + :meth:`append` method calls. *s* may be an instance of :class:`bytes` or + :class:`str`, but see the :meth:`append` documentation for semantics. + + Optional *charset* serves two purposes: it has the same meaning as the *charset* + argument to the :meth:`append` method. It also sets the default character set + for all subsequent :meth:`append` calls that omit the *charset* argument. If + *charset* is not provided in the constructor (the default), the ``us-ascii`` + character set is used both as *s*'s initial charset and as the default for + subsequent :meth:`append` calls. + + The maximum line length can be specified explicitly via *maxlinelen*. For + splitting the first line to a shorter value (to account for the field header + which isn't included in *s*, e.g. :mailheader:`Subject`) pass in the name of the + field in *header_name*. The default *maxlinelen* is 76, and the default value + for *header_name* is ``None``, meaning it is not taken into account for the + first line of a long, split header. + + Optional *continuation_ws* must be :rfc:`2822`\ -compliant folding + whitespace, and is usually either a space or a hard tab character. This + character will be prepended to continuation lines. *continuation_ws* + defaults to a single space character. + + Optional *errors* is passed straight through to the :meth:`append` method. + + + .. method:: append(s, charset=None, errors='strict') + + Append the string *s* to the MIME header. + + Optional *charset*, if given, should be a :class:`~email.charset.Charset` + instance (see :mod:`email.charset`) or the name of a character set, which + will be converted to a :class:`~email.charset.Charset` instance. A value + of ``None`` (the default) means that the *charset* given in the constructor + is used. + + *s* may be an instance of :class:`bytes` or :class:`str`. If it is an + instance of :class:`bytes`, then *charset* is the encoding of that byte + string, and a :exc:`UnicodeError` will be raised if the string cannot be + decoded with that character set. + + If *s* is an instance of :class:`str`, then *charset* is a hint specifying + the character set of the characters in the string. + + In either case, when producing an :rfc:`2822`\ -compliant header using + :rfc:`2047` rules, the string will be encoded using the output codec of + the charset. If the string cannot be encoded using the output codec, a + UnicodeError will be raised. + + Optional *errors* is passed as the errors argument to the decode call + if *s* is a byte string. + + + .. method:: encode(splitchars=';, \\t', maxlinelen=None, linesep='\\n') + + Encode a message header into an RFC-compliant format, possibly wrapping + long lines and encapsulating non-ASCII parts in base64 or quoted-printable + encodings. + + Optional *splitchars* is a string containing characters which should be + given extra weight by the splitting algorithm during normal header + wrapping. This is in very rough support of :RFC:`2822`\'s 'higher level + syntactic breaks': split points preceded by a splitchar are preferred + during line splitting, with the characters preferred in the order in + which they appear in the string. Space and tab may be included in the + string to indicate whether preference should be given to one over the + other as a split point when other split chars do not appear in the line + being split. Splitchars does not affect :RFC:`2047` encoded lines. + + *maxlinelen*, if given, overrides the instance's value for the maximum + line length. + + *linesep* specifies the characters used to separate the lines of the + folded header. It defaults to the most useful value for Python + application code (``\n``), but ``\r\n`` can be specified in order + to produce headers with RFC-compliant line separators. + + .. versionchanged:: 3.2 + Added the *linesep* argument. + + + The :class:`Header` class also provides a number of methods to support + standard operators and built-in functions. + + .. method:: __str__() + + Returns an approximation of the :class:`Header` as a string, using an + unlimited line length. All pieces are converted to unicode using the + specified encoding and joined together appropriately. Any pieces with a + charset of ``'unknown-8bit'`` are decoded as ASCII using the ``'replace'`` + error handler. + + .. versionchanged:: 3.2 + Added handling for the ``'unknown-8bit'`` charset. + + + .. method:: __eq__(other) + + This method allows you to compare two :class:`Header` instances for + equality. + + + .. method:: __ne__(other) + + This method allows you to compare two :class:`Header` instances for + inequality. + +The :mod:`email.header` module also provides the following convenient functions. + + +.. function:: decode_header(header) + + Decode a message header value without converting the character set. The header + value is in *header*. + + This function returns a list of ``(decoded_string, charset)`` pairs containing + each of the decoded parts of the header. *charset* is ``None`` for non-encoded + parts of the header, otherwise a lower case string containing the name of the + character set specified in the encoded string. + + Here's an example:: + + >>> from email.header import decode_header + >>> decode_header('=?iso-8859-1?q?p=F6stal?=') + [(b'p\xf6stal', 'iso-8859-1')] + + +.. function:: make_header(decoded_seq, maxlinelen=None, header_name=None, continuation_ws=' ') + + Create a :class:`Header` instance from a sequence of pairs as returned by + :func:`decode_header`. + + :func:`decode_header` takes a header value string and returns a sequence of + pairs of the format ``(decoded_string, charset)`` where *charset* is the name of + the character set. + + This function takes one of those sequence of pairs and returns a + :class:`Header` instance. Optional *maxlinelen*, *header_name*, and + *continuation_ws* are as in the :class:`Header` constructor. + diff --git a/cpython_2/environment/repo/Doc/library/email.headerregistry.rst b/cpython_2/environment/repo/Doc/library/email.headerregistry.rst new file mode 100644 index 0000000000000000000000000000000000000000..9376da2b8d39ce78eec59ba70005457b85c65f6d --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/email.headerregistry.rst @@ -0,0 +1,462 @@ +:mod:`email.headerregistry`: Custom Header Objects +-------------------------------------------------- + +.. module:: email.headerregistry + :synopsis: Automatic Parsing of headers based on the field name + +.. moduleauthor:: R. David Murray +.. sectionauthor:: R. David Murray + +**Source code:** :source:`Lib/email/headerregistry.py` + +-------------- + +.. versionadded:: 3.6 [1]_ + +Headers are represented by customized subclasses of :class:`str`. The +particular class used to represent a given header is determined by the +:attr:`~email.policy.EmailPolicy.header_factory` of the :mod:`~email.policy` in +effect when the headers are created. This section documents the particular +``header_factory`` implemented by the email package for handling :RFC:`5322` +compliant email messages, which not only provides customized header objects for +various header types, but also provides an extension mechanism for applications +to add their own custom header types. + +When using any of the policy objects derived from +:data:`~email.policy.EmailPolicy`, all headers are produced by +:class:`.HeaderRegistry` and have :class:`.BaseHeader` as their last base +class. Each header class has an additional base class that is determined by +the type of the header. For example, many headers have the class +:class:`.UnstructuredHeader` as their other base class. The specialized second +class for a header is determined by the name of the header, using a lookup +table stored in the :class:`.HeaderRegistry`. All of this is managed +transparently for the typical application program, but interfaces are provided +for modifying the default behavior for use by more complex applications. + +The sections below first document the header base classes and their attributes, +followed by the API for modifying the behavior of :class:`.HeaderRegistry`, and +finally the support classes used to represent the data parsed from structured +headers. + + +.. class:: BaseHeader(name, value) + + *name* and *value* are passed to ``BaseHeader`` from the + :attr:`~email.policy.EmailPolicy.header_factory` call. The string value of + any header object is the *value* fully decoded to unicode. + + This base class defines the following read-only properties: + + + .. attribute:: name + + The name of the header (the portion of the field before the ':'). This + is exactly the value passed in the + :attr:`~email.policy.EmailPolicy.header_factory` call for *name*; that + is, case is preserved. + + + .. attribute:: defects + + A tuple of :exc:`~email.errors.HeaderDefect` instances reporting any + RFC compliance problems found during parsing. The email package tries to + be complete about detecting compliance issues. See the :mod:`~email.errors` + module for a discussion of the types of defects that may be reported. + + + .. attribute:: max_count + + The maximum number of headers of this type that can have the same + ``name``. A value of ``None`` means unlimited. The ``BaseHeader`` value + for this attribute is ``None``; it is expected that specialized header + classes will override this value as needed. + + ``BaseHeader`` also provides the following method, which is called by the + email library code and should not in general be called by application + programs: + + .. method:: fold(*, policy) + + Return a string containing :attr:`~email.policy.Policy.linesep` + characters as required to correctly fold the header according to + *policy*. A :attr:`~email.policy.Policy.cte_type` of ``8bit`` will be + treated as if it were ``7bit``, since headers may not contain arbitrary + binary data. If :attr:`~email.policy.EmailPolicy.utf8` is ``False``, + non-ASCII data will be :rfc:`2047` encoded. + + + ``BaseHeader`` by itself cannot be used to create a header object. It + defines a protocol that each specialized header cooperates with in order to + produce the header object. Specifically, ``BaseHeader`` requires that + the specialized class provide a :func:`classmethod` named ``parse``. This + method is called as follows:: + + parse(string, kwds) + + ``kwds`` is a dictionary containing one pre-initialized key, ``defects``. + ``defects`` is an empty list. The parse method should append any detected + defects to this list. On return, the ``kwds`` dictionary *must* contain + values for at least the keys ``decoded`` and ``defects``. ``decoded`` + should be the string value for the header (that is, the header value fully + decoded to unicode). The parse method should assume that *string* may + contain content-transfer-encoded parts, but should correctly handle all valid + unicode characters as well so that it can parse un-encoded header values. + + ``BaseHeader``'s ``__new__`` then creates the header instance, and calls its + ``init`` method. The specialized class only needs to provide an ``init`` + method if it wishes to set additional attributes beyond those provided by + ``BaseHeader`` itself. Such an ``init`` method should look like this:: + + def init(self, /, *args, **kw): + self._myattr = kw.pop('myattr') + super().init(*args, **kw) + + That is, anything extra that the specialized class puts in to the ``kwds`` + dictionary should be removed and handled, and the remaining contents of + ``kw`` (and ``args``) passed to the ``BaseHeader`` ``init`` method. + + +.. class:: UnstructuredHeader + + An "unstructured" header is the default type of header in :rfc:`5322`. + Any header that does not have a specified syntax is treated as + unstructured. The classic example of an unstructured header is the + :mailheader:`Subject` header. + + In :rfc:`5322`, an unstructured header is a run of arbitrary text in the + ASCII character set. :rfc:`2047`, however, has an :rfc:`5322` compatible + mechanism for encoding non-ASCII text as ASCII characters within a header + value. When a *value* containing encoded words is passed to the + constructor, the ``UnstructuredHeader`` parser converts such encoded words + into unicode, following the :rfc:`2047` rules for unstructured text. The + parser uses heuristics to attempt to decode certain non-compliant encoded + words. Defects are registered in such cases, as well as defects for issues + such as invalid characters within the encoded words or the non-encoded text. + + This header type provides no additional attributes. + + +.. class:: DateHeader + + :rfc:`5322` specifies a very specific format for dates within email headers. + The ``DateHeader`` parser recognizes that date format, as well as + recognizing a number of variant forms that are sometimes found "in the + wild". + + This header type provides the following additional attributes: + + .. attribute:: datetime + + If the header value can be recognized as a valid date of one form or + another, this attribute will contain a :class:`~datetime.datetime` + instance representing that date. If the timezone of the input date is + specified as ``-0000`` (indicating it is in UTC but contains no + information about the source timezone), then :attr:`.datetime` will be a + naive :class:`~datetime.datetime`. If a specific timezone offset is + found (including `+0000`), then :attr:`.datetime` will contain an aware + ``datetime`` that uses :class:`datetime.timezone` to record the timezone + offset. + + The ``decoded`` value of the header is determined by formatting the + ``datetime`` according to the :rfc:`5322` rules; that is, it is set to:: + + email.utils.format_datetime(self.datetime) + + When creating a ``DateHeader``, *value* may be + :class:`~datetime.datetime` instance. This means, for example, that + the following code is valid and does what one would expect:: + + msg['Date'] = datetime(2011, 7, 15, 21) + + Because this is a naive ``datetime`` it will be interpreted as a UTC + timestamp, and the resulting value will have a timezone of ``-0000``. Much + more useful is to use the :func:`~email.utils.localtime` function from the + :mod:`~email.utils` module:: + + msg['Date'] = utils.localtime() + + This example sets the date header to the current time and date using + the current timezone offset. + + +.. class:: AddressHeader + + Address headers are one of the most complex structured header types. + The ``AddressHeader`` class provides a generic interface to any address + header. + + This header type provides the following additional attributes: + + + .. attribute:: groups + + A tuple of :class:`.Group` objects encoding the + addresses and groups found in the header value. Addresses that are + not part of a group are represented in this list as single-address + ``Groups`` whose :attr:`~.Group.display_name` is ``None``. + + + .. attribute:: addresses + + A tuple of :class:`.Address` objects encoding all + of the individual addresses from the header value. If the header value + contains any groups, the individual addresses from the group are included + in the list at the point where the group occurs in the value (that is, + the list of addresses is "flattened" into a one dimensional list). + + The ``decoded`` value of the header will have all encoded words decoded to + unicode. :class:`~encodings.idna` encoded domain names are also decoded to + unicode. The ``decoded`` value is set by :attr:`~str.join`\ ing the + :class:`str` value of the elements of the ``groups`` attribute with ``', + '``. + + A list of :class:`.Address` and :class:`.Group` objects in any combination + may be used to set the value of an address header. ``Group`` objects whose + ``display_name`` is ``None`` will be interpreted as single addresses, which + allows an address list to be copied with groups intact by using the list + obtained from the ``groups`` attribute of the source header. + + +.. class:: SingleAddressHeader + + A subclass of :class:`.AddressHeader` that adds one + additional attribute: + + + .. attribute:: address + + The single address encoded by the header value. If the header value + actually contains more than one address (which would be a violation of + the RFC under the default :mod:`~email.policy`), accessing this attribute + will result in a :exc:`ValueError`. + + +Many of the above classes also have a ``Unique`` variant (for example, +``UniqueUnstructuredHeader``). The only difference is that in the ``Unique`` +variant, :attr:`~.BaseHeader.max_count` is set to 1. + + +.. class:: MIMEVersionHeader + + There is really only one valid value for the :mailheader:`MIME-Version` + header, and that is ``1.0``. For future proofing, this header class + supports other valid version numbers. If a version number has a valid value + per :rfc:`2045`, then the header object will have non-``None`` values for + the following attributes: + + .. attribute:: version + + The version number as a string, with any whitespace and/or comments + removed. + + .. attribute:: major + + The major version number as an integer + + .. attribute:: minor + + The minor version number as an integer + + +.. class:: ParameterizedMIMEHeader + + MIME headers all start with the prefix 'Content-'. Each specific header has + a certain value, described under the class for that header. Some can + also take a list of supplemental parameters, which have a common format. + This class serves as a base for all the MIME headers that take parameters. + + .. attribute:: params + + A dictionary mapping parameter names to parameter values. + + +.. class:: ContentTypeHeader + + A :class:`ParameterizedMIMEHeader` class that handles the + :mailheader:`Content-Type` header. + + .. attribute:: content_type + + The content type string, in the form ``maintype/subtype``. + + .. attribute:: maintype + + .. attribute:: subtype + + +.. class:: ContentDispositionHeader + + A :class:`ParameterizedMIMEHeader` class that handles the + :mailheader:`Content-Disposition` header. + + .. attribute:: content-disposition + + ``inline`` and ``attachment`` are the only valid values in common use. + + +.. class:: ContentTransferEncoding + + Handles the :mailheader:`Content-Transfer-Encoding` header. + + .. attribute:: cte + + Valid values are ``7bit``, ``8bit``, ``base64``, and + ``quoted-printable``. See :rfc:`2045` for more information. + + + +.. class:: HeaderRegistry(base_class=BaseHeader, \ + default_class=UnstructuredHeader, \ + use_default_map=True) + + This is the factory used by :class:`~email.policy.EmailPolicy` by default. + ``HeaderRegistry`` builds the class used to create a header instance + dynamically, using *base_class* and a specialized class retrieved from a + registry that it holds. When a given header name does not appear in the + registry, the class specified by *default_class* is used as the specialized + class. When *use_default_map* is ``True`` (the default), the standard + mapping of header names to classes is copied in to the registry during + initialization. *base_class* is always the last class in the generated + class's ``__bases__`` list. + + The default mappings are: + + :subject: UniqueUnstructuredHeader + :date: UniqueDateHeader + :resent-date: DateHeader + :orig-date: UniqueDateHeader + :sender: UniqueSingleAddressHeader + :resent-sender: SingleAddressHeader + :to: UniqueAddressHeader + :resent-to: AddressHeader + :cc: UniqueAddressHeader + :resent-cc: AddressHeader + :bcc: UniqueAddressHeader + :resent-bcc: AddressHeader + :from: UniqueAddressHeader + :resent-from: AddressHeader + :reply-to: UniqueAddressHeader + :mime-version: MIMEVersionHeader + :content-type: ContentTypeHeader + :content-disposition: ContentDispositionHeader + :content-transfer-encoding: ContentTransferEncodingHeader + :message-id: MessageIDHeader + + ``HeaderRegistry`` has the following methods: + + + .. method:: map_to_type(self, name, cls) + + *name* is the name of the header to be mapped. It will be converted to + lower case in the registry. *cls* is the specialized class to be used, + along with *base_class*, to create the class used to instantiate headers + that match *name*. + + + .. method:: __getitem__(name) + + Construct and return a class to handle creating a *name* header. + + + .. method:: __call__(name, value) + + Retrieves the specialized header associated with *name* from the + registry (using *default_class* if *name* does not appear in the + registry) and composes it with *base_class* to produce a class, + calls the constructed class's constructor, passing it the same + argument list, and finally returns the class instance created thereby. + + +The following classes are the classes used to represent data parsed from +structured headers and can, in general, be used by an application program to +construct structured values to assign to specific headers. + + +.. class:: Address(display_name='', username='', domain='', addr_spec=None) + + The class used to represent an email address. The general form of an + address is:: + + [display_name] + + or:: + + username@domain + + where each part must conform to specific syntax rules spelled out in + :rfc:`5322`. + + As a convenience *addr_spec* can be specified instead of *username* and + *domain*, in which case *username* and *domain* will be parsed from the + *addr_spec*. An *addr_spec* must be a properly RFC quoted string; if it is + not ``Address`` will raise an error. Unicode characters are allowed and + will be property encoded when serialized. However, per the RFCs, unicode is + *not* allowed in the username portion of the address. + + .. attribute:: display_name + + The display name portion of the address, if any, with all quoting + removed. If the address does not have a display name, this attribute + will be an empty string. + + .. attribute:: username + + The ``username`` portion of the address, with all quoting removed. + + .. attribute:: domain + + The ``domain`` portion of the address. + + .. attribute:: addr_spec + + The ``username@domain`` portion of the address, correctly quoted + for use as a bare address (the second form shown above). This + attribute is not mutable. + + .. method:: __str__() + + The ``str`` value of the object is the address quoted according to + :rfc:`5322` rules, but with no Content Transfer Encoding of any non-ASCII + characters. + + To support SMTP (:rfc:`5321`), ``Address`` handles one special case: if + ``username`` and ``domain`` are both the empty string (or ``None``), then + the string value of the ``Address`` is ``<>``. + + +.. class:: Group(display_name=None, addresses=None) + + The class used to represent an address group. The general form of an + address group is:: + + display_name: [address-list]; + + As a convenience for processing lists of addresses that consist of a mixture + of groups and single addresses, a ``Group`` may also be used to represent + single addresses that are not part of a group by setting *display_name* to + ``None`` and providing a list of the single address as *addresses*. + + .. attribute:: display_name + + The ``display_name`` of the group. If it is ``None`` and there is + exactly one ``Address`` in ``addresses``, then the ``Group`` represents a + single address that is not in a group. + + .. attribute:: addresses + + A possibly empty tuple of :class:`.Address` objects representing the + addresses in the group. + + .. method:: __str__() + + The ``str`` value of a ``Group`` is formatted according to :rfc:`5322`, + but with no Content Transfer Encoding of any non-ASCII characters. If + ``display_name`` is none and there is a single ``Address`` in the + ``addresses`` list, the ``str`` value will be the same as the ``str`` of + that single ``Address``. + + +.. rubric:: Footnotes + +.. [1] Originally added in 3.3 as a :term:`provisional module ` diff --git a/cpython_2/environment/repo/Doc/library/email.iterators.rst b/cpython_2/environment/repo/Doc/library/email.iterators.rst new file mode 100644 index 0000000000000000000000000000000000000000..d53ab33b8904a7a1584ea7ff175ea45aa2ce268d --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/email.iterators.rst @@ -0,0 +1,83 @@ +:mod:`email.iterators`: Iterators +--------------------------------- + +.. module:: email.iterators + :synopsis: Iterate over a message object tree. + +**Source code:** :source:`Lib/email/iterators.py` + +-------------- + +Iterating over a message object tree is fairly easy with the +:meth:`Message.walk ` method. The +:mod:`email.iterators` module provides some useful higher level iterations over +message object trees. + + +.. function:: body_line_iterator(msg, decode=False) + + This iterates over all the payloads in all the subparts of *msg*, returning the + string payloads line-by-line. It skips over all the subpart headers, and it + skips over any subpart with a payload that isn't a Python string. This is + somewhat equivalent to reading the flat text representation of the message from + a file using :meth:`~io.TextIOBase.readline`, skipping over all the + intervening headers. + + Optional *decode* is passed through to :meth:`Message.get_payload + `. + + +.. function:: typed_subpart_iterator(msg, maintype='text', subtype=None) + + This iterates over all the subparts of *msg*, returning only those subparts that + match the MIME type specified by *maintype* and *subtype*. + + Note that *subtype* is optional; if omitted, then subpart MIME type matching is + done only with the main type. *maintype* is optional too; it defaults to + :mimetype:`text`. + + Thus, by default :func:`typed_subpart_iterator` returns each subpart that has a + MIME type of :mimetype:`text/\*`. + + +The following function has been added as a useful debugging tool. It should +*not* be considered part of the supported public interface for the package. + +.. function:: _structure(msg, fp=None, level=0, include_default=False) + + Prints an indented representation of the content types of the message object + structure. For example: + + .. testsetup:: + + import email + from email.iterators import _structure + somefile = open('../Lib/test/test_email/data/msg_02.txt') + + .. doctest:: + + >>> msg = email.message_from_file(somefile) + >>> _structure(msg) + multipart/mixed + text/plain + text/plain + multipart/digest + message/rfc822 + text/plain + message/rfc822 + text/plain + message/rfc822 + text/plain + message/rfc822 + text/plain + message/rfc822 + text/plain + text/plain + + .. testcleanup:: + + somefile.close() + + Optional *fp* is a file-like object to print the output to. It must be + suitable for Python's :func:`print` function. *level* is used internally. + *include_default*, if true, prints the default type as well. diff --git a/cpython_2/environment/repo/Doc/library/email.message.rst b/cpython_2/environment/repo/Doc/library/email.message.rst new file mode 100644 index 0000000000000000000000000000000000000000..5e0509f4181199b7b5113ff01a38dc43a7c5d8f3 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/email.message.rst @@ -0,0 +1,751 @@ +:mod:`email.message`: Representing an email message +--------------------------------------------------- + +.. module:: email.message + :synopsis: The base class representing email messages. +.. moduleauthor:: R. David Murray +.. sectionauthor:: R. David Murray , + Barry A. Warsaw + +**Source code:** :source:`Lib/email/message.py` + +-------------- + +.. versionadded:: 3.6 [1]_ + +The central class in the :mod:`email` package is the :class:`EmailMessage` +class, imported from the :mod:`email.message` module. It is the base class for +the :mod:`email` object model. :class:`EmailMessage` provides the core +functionality for setting and querying header fields, for accessing message +bodies, and for creating or modifying structured messages. + +An email message consists of *headers* and a *payload* (which is also referred +to as the *content*). Headers are :rfc:`5322` or :rfc:`6532` style field names +and values, where the field name and value are separated by a colon. The colon +is not part of either the field name or the field value. The payload may be a +simple text message, or a binary object, or a structured sequence of +sub-messages each with their own set of headers and their own payload. The +latter type of payload is indicated by the message having a MIME type such as +:mimetype:`multipart/\*` or :mimetype:`message/rfc822`. + +The conceptual model provided by an :class:`EmailMessage` object is that of an +ordered dictionary of headers coupled with a *payload* that represents the +:rfc:`5322` body of the message, which might be a list of sub-``EmailMessage`` +objects. In addition to the normal dictionary methods for accessing the header +names and values, there are methods for accessing specialized information from +the headers (for example the MIME content type), for operating on the payload, +for generating a serialized version of the message, and for recursively walking +over the object tree. + +The :class:`EmailMessage` dictionary-like interface is indexed by the header +names, which must be ASCII values. The values of the dictionary are strings +with some extra methods. Headers are stored and returned in case-preserving +form, but field names are matched case-insensitively. Unlike a real dict, +there is an ordering to the keys, and there can be duplicate keys. Additional +methods are provided for working with headers that have duplicate keys. + +The *payload* is either a string or bytes object, in the case of simple message +objects, or a list of :class:`EmailMessage` objects, for MIME container +documents such as :mimetype:`multipart/\*` and :mimetype:`message/rfc822` +message objects. + + +.. class:: EmailMessage(policy=default) + + If *policy* is specified use the rules it specifies to update and serialize + the representation of the message. If *policy* is not set, use the + :class:`~email.policy.default` policy, which follows the rules of the email + RFCs except for line endings (instead of the RFC mandated ``\r\n``, it uses + the Python standard ``\n`` line endings). For more information see the + :mod:`~email.policy` documentation. + + .. method:: as_string(unixfrom=False, maxheaderlen=None, policy=None) + + Return the entire message flattened as a string. When optional + *unixfrom* is true, the envelope header is included in the returned + string. *unixfrom* defaults to ``False``. For backward compatibility + with the base :class:`~email.message.Message` class *maxheaderlen* is + accepted, but defaults to ``None``, which means that by default the line + length is controlled by the + :attr:`~email.policy.EmailPolicy.max_line_length` of the policy. The + *policy* argument may be used to override the default policy obtained + from the message instance. This can be used to control some of the + formatting produced by the method, since the specified *policy* will be + passed to the :class:`~email.generator.Generator`. + + Flattening the message may trigger changes to the :class:`EmailMessage` + if defaults need to be filled in to complete the transformation to a + string (for example, MIME boundaries may be generated or modified). + + Note that this method is provided as a convenience and may not be the + most useful way to serialize messages in your application, especially if + you are dealing with multiple messages. See + :class:`email.generator.Generator` for a more flexible API for + serializing messages. Note also that this method is restricted to + producing messages serialized as "7 bit clean" when + :attr:`~email.policy.EmailPolicy.utf8` is ``False``, which is the default. + + .. versionchanged:: 3.6 the default behavior when *maxheaderlen* + is not specified was changed from defaulting to 0 to defaulting + to the value of *max_line_length* from the policy. + + + .. method:: __str__() + + Equivalent to ``as_string(policy=self.policy.clone(utf8=True))``. Allows + ``str(msg)`` to produce a string containing the serialized message in a + readable format. + + .. versionchanged:: 3.4 the method was changed to use ``utf8=True``, + thus producing an :rfc:`6531`-like message representation, instead of + being a direct alias for :meth:`as_string`. + + + .. method:: as_bytes(unixfrom=False, policy=None) + + Return the entire message flattened as a bytes object. When optional + *unixfrom* is true, the envelope header is included in the returned + string. *unixfrom* defaults to ``False``. The *policy* argument may be + used to override the default policy obtained from the message instance. + This can be used to control some of the formatting produced by the + method, since the specified *policy* will be passed to the + :class:`~email.generator.BytesGenerator`. + + Flattening the message may trigger changes to the :class:`EmailMessage` + if defaults need to be filled in to complete the transformation to a + string (for example, MIME boundaries may be generated or modified). + + Note that this method is provided as a convenience and may not be the + most useful way to serialize messages in your application, especially if + you are dealing with multiple messages. See + :class:`email.generator.BytesGenerator` for a more flexible API for + serializing messages. + + + .. method:: __bytes__() + + Equivalent to :meth:`.as_bytes()`. Allows ``bytes(msg)`` to produce a + bytes object containing the serialized message. + + + .. method:: is_multipart() + + Return ``True`` if the message's payload is a list of + sub-\ :class:`EmailMessage` objects, otherwise return ``False``. When + :meth:`is_multipart` returns ``False``, the payload should be a string + object (which might be a CTE encoded binary payload). Note that + :meth:`is_multipart` returning ``True`` does not necessarily mean that + "msg.get_content_maintype() == 'multipart'" will return the ``True``. + For example, ``is_multipart`` will return ``True`` when the + :class:`EmailMessage` is of type ``message/rfc822``. + + + .. method:: set_unixfrom(unixfrom) + + Set the message's envelope header to *unixfrom*, which should be a + string. (See :class:`~mailbox.mboxMessage` for a brief description of + this header.) + + + .. method:: get_unixfrom() + + Return the message's envelope header. Defaults to ``None`` if the + envelope header was never set. + + + The following methods implement the mapping-like interface for accessing the + message's headers. Note that there are some semantic differences + between these methods and a normal mapping (i.e. dictionary) interface. For + example, in a dictionary there are no duplicate keys, but here there may be + duplicate message headers. Also, in dictionaries there is no guaranteed + order to the keys returned by :meth:`keys`, but in an :class:`EmailMessage` + object, headers are always returned in the order they appeared in the + original message, or in which they were added to the message later. Any + header deleted and then re-added is always appended to the end of the + header list. + + These semantic differences are intentional and are biased toward + convenience in the most common use cases. + + Note that in all cases, any envelope header present in the message is not + included in the mapping interface. + + + .. method:: __len__() + + Return the total number of headers, including duplicates. + + + .. method:: __contains__(name) + + Return ``True`` if the message object has a field named *name*. Matching is + done without regard to case and *name* does not include the trailing + colon. Used for the ``in`` operator. For example:: + + if 'message-id' in myMessage: + print('Message-ID:', myMessage['message-id']) + + + .. method:: __getitem__(name) + + Return the value of the named header field. *name* does not include the + colon field separator. If the header is missing, ``None`` is returned; a + :exc:`KeyError` is never raised. + + Note that if the named field appears more than once in the message's + headers, exactly which of those field values will be returned is + undefined. Use the :meth:`get_all` method to get the values of all the + extant headers named *name*. + + Using the standard (non-``compat32``) policies, the returned value is an + instance of a subclass of :class:`email.headerregistry.BaseHeader`. + + + .. method:: __setitem__(name, val) + + Add a header to the message with field name *name* and value *val*. The + field is appended to the end of the message's existing headers. + + Note that this does *not* overwrite or delete any existing header with the same + name. If you want to ensure that the new header is the only one present in the + message with field name *name*, delete the field first, e.g.:: + + del msg['subject'] + msg['subject'] = 'Python roolz!' + + If the :mod:`policy` defines certain headers to be unique (as the standard + policies do), this method may raise a :exc:`ValueError` when an attempt + is made to assign a value to such a header when one already exists. This + behavior is intentional for consistency's sake, but do not depend on it + as we may choose to make such assignments do an automatic deletion of the + existing header in the future. + + + .. method:: __delitem__(name) + + Delete all occurrences of the field with name *name* from the message's + headers. No exception is raised if the named field isn't present in the + headers. + + + .. method:: keys() + + Return a list of all the message's header field names. + + + .. method:: values() + + Return a list of all the message's field values. + + + .. method:: items() + + Return a list of 2-tuples containing all the message's field headers and + values. + + + .. method:: get(name, failobj=None) + + Return the value of the named header field. This is identical to + :meth:`__getitem__` except that optional *failobj* is returned if the + named header is missing (*failobj* defaults to ``None``). + + + Here are some additional useful header related methods: + + + .. method:: get_all(name, failobj=None) + + Return a list of all the values for the field named *name*. If there are + no such named headers in the message, *failobj* is returned (defaults to + ``None``). + + + .. method:: add_header(_name, _value, **_params) + + Extended header setting. This method is similar to :meth:`__setitem__` + except that additional header parameters can be provided as keyword + arguments. *_name* is the header field to add and *_value* is the + *primary* value for the header. + + For each item in the keyword argument dictionary *_params*, the key is + taken as the parameter name, with underscores converted to dashes (since + dashes are illegal in Python identifiers). Normally, the parameter will + be added as ``key="value"`` unless the value is ``None``, in which case + only the key will be added. + + If the value contains non-ASCII characters, the charset and language may + be explicitly controlled by specifying the value as a three tuple in the + format ``(CHARSET, LANGUAGE, VALUE)``, where ``CHARSET`` is a string + naming the charset to be used to encode the value, ``LANGUAGE`` can + usually be set to ``None`` or the empty string (see :rfc:`2231` for other + possibilities), and ``VALUE`` is the string value containing non-ASCII + code points. If a three tuple is not passed and the value contains + non-ASCII characters, it is automatically encoded in :rfc:`2231` format + using a ``CHARSET`` of ``utf-8`` and a ``LANGUAGE`` of ``None``. + + Here is an example:: + + msg.add_header('Content-Disposition', 'attachment', filename='bud.gif') + + This will add a header that looks like :: + + Content-Disposition: attachment; filename="bud.gif" + + An example of the extended interface with non-ASCII characters:: + + msg.add_header('Content-Disposition', 'attachment', + filename=('iso-8859-1', '', 'Fußballer.ppt')) + + + .. method:: replace_header(_name, _value) + + Replace a header. Replace the first header found in the message that + matches *_name*, retaining header order and field name case of the + original header. If no matching header is found, raise a + :exc:`KeyError`. + + + .. method:: get_content_type() + + Return the message's content type, coerced to lower case of the form + :mimetype:`maintype/subtype`. If there is no :mailheader:`Content-Type` + header in the message return the value returned by + :meth:`get_default_type`. If the :mailheader:`Content-Type` header is + invalid, return ``text/plain``. + + (According to :rfc:`2045`, messages always have a default type, + :meth:`get_content_type` will always return a value. :rfc:`2045` defines + a message's default type to be :mimetype:`text/plain` unless it appears + inside a :mimetype:`multipart/digest` container, in which case it would + be :mimetype:`message/rfc822`. If the :mailheader:`Content-Type` header + has an invalid type specification, :rfc:`2045` mandates that the default + type be :mimetype:`text/plain`.) + + + .. method:: get_content_maintype() + + Return the message's main content type. This is the :mimetype:`maintype` + part of the string returned by :meth:`get_content_type`. + + + .. method:: get_content_subtype() + + Return the message's sub-content type. This is the :mimetype:`subtype` + part of the string returned by :meth:`get_content_type`. + + + .. method:: get_default_type() + + Return the default content type. Most messages have a default content + type of :mimetype:`text/plain`, except for messages that are subparts of + :mimetype:`multipart/digest` containers. Such subparts have a default + content type of :mimetype:`message/rfc822`. + + + .. method:: set_default_type(ctype) + + Set the default content type. *ctype* should either be + :mimetype:`text/plain` or :mimetype:`message/rfc822`, although this is + not enforced. The default content type is not stored in the + :mailheader:`Content-Type` header, so it only affects the return value of + the ``get_content_type`` methods when no :mailheader:`Content-Type` + header is present in the message. + + + .. method:: set_param(param, value, header='Content-Type', requote=True, \ + charset=None, language='', replace=False) + + Set a parameter in the :mailheader:`Content-Type` header. If the + parameter already exists in the header, replace its value with *value*. + When *header* is ``Content-Type`` (the default) and the header does not + yet exist in the message, add it, set its value to + :mimetype:`text/plain`, and append the new parameter value. Optional + *header* specifies an alternative header to :mailheader:`Content-Type`. + + If the value contains non-ASCII characters, the charset and language may + be explicitly specified using the optional *charset* and *language* + parameters. Optional *language* specifies the :rfc:`2231` language, + defaulting to the empty string. Both *charset* and *language* should be + strings. The default is to use the ``utf8`` *charset* and ``None`` for + the *language*. + + If *replace* is ``False`` (the default) the header is moved to the + end of the list of headers. If *replace* is ``True``, the header + will be updated in place. + + Use of the *requote* parameter with :class:`EmailMessage` objects is + deprecated. + + Note that existing parameter values of headers may be accessed through + the :attr:`~email.headerregistry.BaseHeader.params` attribute of the + header value (for example, ``msg['Content-Type'].params['charset']``). + + .. versionchanged:: 3.4 ``replace`` keyword was added. + + + .. method:: del_param(param, header='content-type', requote=True) + + Remove the given parameter completely from the :mailheader:`Content-Type` + header. The header will be re-written in place without the parameter or + its value. Optional *header* specifies an alternative to + :mailheader:`Content-Type`. + + Use of the *requote* parameter with :class:`EmailMessage` objects is + deprecated. + + + .. method:: get_filename(failobj=None) + + Return the value of the ``filename`` parameter of the + :mailheader:`Content-Disposition` header of the message. If the header + does not have a ``filename`` parameter, this method falls back to looking + for the ``name`` parameter on the :mailheader:`Content-Type` header. If + neither is found, or the header is missing, then *failobj* is returned. + The returned string will always be unquoted as per + :func:`email.utils.unquote`. + + + .. method:: get_boundary(failobj=None) + + Return the value of the ``boundary`` parameter of the + :mailheader:`Content-Type` header of the message, or *failobj* if either + the header is missing, or has no ``boundary`` parameter. The returned + string will always be unquoted as per :func:`email.utils.unquote`. + + + .. method:: set_boundary(boundary) + + Set the ``boundary`` parameter of the :mailheader:`Content-Type` header to + *boundary*. :meth:`set_boundary` will always quote *boundary* if + necessary. A :exc:`~email.errors.HeaderParseError` is raised if the + message object has no :mailheader:`Content-Type` header. + + Note that using this method is subtly different from deleting the old + :mailheader:`Content-Type` header and adding a new one with the new + boundary via :meth:`add_header`, because :meth:`set_boundary` preserves + the order of the :mailheader:`Content-Type` header in the list of + headers. + + + .. method:: get_content_charset(failobj=None) + + Return the ``charset`` parameter of the :mailheader:`Content-Type` header, + coerced to lower case. If there is no :mailheader:`Content-Type` header, or if + that header has no ``charset`` parameter, *failobj* is returned. + + + .. method:: get_charsets(failobj=None) + + Return a list containing the character set names in the message. If the + message is a :mimetype:`multipart`, then the list will contain one element + for each subpart in the payload, otherwise, it will be a list of length 1. + + Each item in the list will be a string which is the value of the + ``charset`` parameter in the :mailheader:`Content-Type` header for the + represented subpart. If the subpart has no :mailheader:`Content-Type` + header, no ``charset`` parameter, or is not of the :mimetype:`text` main + MIME type, then that item in the returned list will be *failobj*. + + + .. method:: is_attachment + + Return ``True`` if there is a :mailheader:`Content-Disposition` header + and its (case insensitive) value is ``attachment``, ``False`` otherwise. + + .. versionchanged:: 3.4.2 + is_attachment is now a method instead of a property, for consistency + with :meth:`~email.message.Message.is_multipart`. + + + .. method:: get_content_disposition() + + Return the lowercased value (without parameters) of the message's + :mailheader:`Content-Disposition` header if it has one, or ``None``. The + possible values for this method are *inline*, *attachment* or ``None`` + if the message follows :rfc:`2183`. + + .. versionadded:: 3.5 + + + The following methods relate to interrogating and manipulating the content + (payload) of the message. + + + .. method:: walk() + + The :meth:`walk` method is an all-purpose generator which can be used to + iterate over all the parts and subparts of a message object tree, in + depth-first traversal order. You will typically use :meth:`walk` as the + iterator in a ``for`` loop; each iteration returns the next subpart. + + Here's an example that prints the MIME type of every part of a multipart + message structure: + + .. testsetup:: + + from email import message_from_binary_file + with open('../Lib/test/test_email/data/msg_16.txt', 'rb') as f: + msg = message_from_binary_file(f) + + .. doctest:: + + >>> for part in msg.walk(): + ... print(part.get_content_type()) + multipart/report + text/plain + message/delivery-status + text/plain + text/plain + message/rfc822 + text/plain + + ``walk`` iterates over the subparts of any part where + :meth:`is_multipart` returns ``True``, even though + ``msg.get_content_maintype() == 'multipart'`` may return ``False``. We + can see this in our example by making use of the ``_structure`` debug + helper function: + + .. doctest:: + + >>> from email.iterators import _structure + >>> for part in msg.walk(): + ... print(part.get_content_maintype() == 'multipart', + ... part.is_multipart()) + True True + False False + False True + False False + False False + False True + False False + >>> _structure(msg) + multipart/report + text/plain + message/delivery-status + text/plain + text/plain + message/rfc822 + text/plain + + Here the ``message`` parts are not ``multiparts``, but they do contain + subparts. ``is_multipart()`` returns ``True`` and ``walk`` descends + into the subparts. + + + .. method:: get_body(preferencelist=('related', 'html', 'plain')) + + Return the MIME part that is the best candidate to be the "body" of the + message. + + *preferencelist* must be a sequence of strings from the set ``related``, + ``html``, and ``plain``, and indicates the order of preference for the + content type of the part returned. + + Start looking for candidate matches with the object on which the + ``get_body`` method is called. + + If ``related`` is not included in *preferencelist*, consider the root + part (or subpart of the root part) of any related encountered as a + candidate if the (sub-)part matches a preference. + + When encountering a ``multipart/related``, check the ``start`` parameter + and if a part with a matching :mailheader:`Content-ID` is found, consider + only it when looking for candidate matches. Otherwise consider only the + first (default root) part of the ``multipart/related``. + + If a part has a :mailheader:`Content-Disposition` header, only consider + the part a candidate match if the value of the header is ``inline``. + + If none of the candidates matches any of the preferences in + *preferencelist*, return ``None``. + + Notes: (1) For most applications the only *preferencelist* combinations + that really make sense are ``('plain',)``, ``('html', 'plain')``, and the + default ``('related', 'html', 'plain')``. (2) Because matching starts + with the object on which ``get_body`` is called, calling ``get_body`` on + a ``multipart/related`` will return the object itself unless + *preferencelist* has a non-default value. (3) Messages (or message parts) + that do not specify a :mailheader:`Content-Type` or whose + :mailheader:`Content-Type` header is invalid will be treated as if they + are of type ``text/plain``, which may occasionally cause ``get_body`` to + return unexpected results. + + + .. method:: iter_attachments() + + Return an iterator over all of the immediate sub-parts of the message + that are not candidate "body" parts. That is, skip the first occurrence + of each of ``text/plain``, ``text/html``, ``multipart/related``, or + ``multipart/alternative`` (unless they are explicitly marked as + attachments via :mailheader:`Content-Disposition: attachment`), and + return all remaining parts. When applied directly to a + ``multipart/related``, return an iterator over the all the related parts + except the root part (ie: the part pointed to by the ``start`` parameter, + or the first part if there is no ``start`` parameter or the ``start`` + parameter doesn't match the :mailheader:`Content-ID` of any of the + parts). When applied directly to a ``multipart/alternative`` or a + non-``multipart``, return an empty iterator. + + + .. method:: iter_parts() + + Return an iterator over all of the immediate sub-parts of the message, + which will be empty for a non-``multipart``. (See also + :meth:`~email.message.EmailMessage.walk`.) + + + .. method:: get_content(*args, content_manager=None, **kw) + + Call the :meth:`~email.contentmanager.ContentManager.get_content` method + of the *content_manager*, passing self as the message object, and passing + along any other arguments or keywords as additional arguments. If + *content_manager* is not specified, use the ``content_manager`` specified + by the current :mod:`~email.policy`. + + + .. method:: set_content(*args, content_manager=None, **kw) + + Call the :meth:`~email.contentmanager.ContentManager.set_content` method + of the *content_manager*, passing self as the message object, and passing + along any other arguments or keywords as additional arguments. If + *content_manager* is not specified, use the ``content_manager`` specified + by the current :mod:`~email.policy`. + + + .. method:: make_related(boundary=None) + + Convert a non-``multipart`` message into a ``multipart/related`` message, + moving any existing :mailheader:`Content-` headers and payload into a + (new) first part of the ``multipart``. If *boundary* is specified, use + it as the boundary string in the multipart, otherwise leave the boundary + to be automatically created when it is needed (for example, when the + message is serialized). + + + .. method:: make_alternative(boundary=None) + + Convert a non-``multipart`` or a ``multipart/related`` into a + ``multipart/alternative``, moving any existing :mailheader:`Content-` + headers and payload into a (new) first part of the ``multipart``. If + *boundary* is specified, use it as the boundary string in the multipart, + otherwise leave the boundary to be automatically created when it is + needed (for example, when the message is serialized). + + + .. method:: make_mixed(boundary=None) + + Convert a non-``multipart``, a ``multipart/related``, or a + ``multipart-alternative`` into a ``multipart/mixed``, moving any existing + :mailheader:`Content-` headers and payload into a (new) first part of the + ``multipart``. If *boundary* is specified, use it as the boundary string + in the multipart, otherwise leave the boundary to be automatically + created when it is needed (for example, when the message is serialized). + + + .. method:: add_related(*args, content_manager=None, **kw) + + If the message is a ``multipart/related``, create a new message + object, pass all of the arguments to its :meth:`set_content` method, + and :meth:`~email.message.Message.attach` it to the ``multipart``. If + the message is a non-``multipart``, call :meth:`make_related` and then + proceed as above. If the message is any other type of ``multipart``, + raise a :exc:`TypeError`. If *content_manager* is not specified, use + the ``content_manager`` specified by the current :mod:`~email.policy`. + If the added part has no :mailheader:`Content-Disposition` header, + add one with the value ``inline``. + + + .. method:: add_alternative(*args, content_manager=None, **kw) + + If the message is a ``multipart/alternative``, create a new message + object, pass all of the arguments to its :meth:`set_content` method, and + :meth:`~email.message.Message.attach` it to the ``multipart``. If the + message is a non-``multipart`` or ``multipart/related``, call + :meth:`make_alternative` and then proceed as above. If the message is + any other type of ``multipart``, raise a :exc:`TypeError`. If + *content_manager* is not specified, use the ``content_manager`` specified + by the current :mod:`~email.policy`. + + + .. method:: add_attachment(*args, content_manager=None, **kw) + + If the message is a ``multipart/mixed``, create a new message object, + pass all of the arguments to its :meth:`set_content` method, and + :meth:`~email.message.Message.attach` it to the ``multipart``. If the + message is a non-``multipart``, ``multipart/related``, or + ``multipart/alternative``, call :meth:`make_mixed` and then proceed as + above. If *content_manager* is not specified, use the ``content_manager`` + specified by the current :mod:`~email.policy`. If the added part + has no :mailheader:`Content-Disposition` header, add one with the value + ``attachment``. This method can be used both for explicit attachments + (:mailheader:`Content-Disposition: attachment`) and ``inline`` attachments + (:mailheader:`Content-Disposition: inline`), by passing appropriate + options to the ``content_manager``. + + + .. method:: clear() + + Remove the payload and all of the headers. + + + .. method:: clear_content() + + Remove the payload and all of the :exc:`Content-` headers, leaving + all other headers intact and in their original order. + + + :class:`EmailMessage` objects have the following instance attributes: + + + .. attribute:: preamble + + The format of a MIME document allows for some text between the blank line + following the headers, and the first multipart boundary string. Normally, + this text is never visible in a MIME-aware mail reader because it falls + outside the standard MIME armor. However, when viewing the raw text of + the message, or when viewing the message in a non-MIME aware reader, this + text can become visible. + + The *preamble* attribute contains this leading extra-armor text for MIME + documents. When the :class:`~email.parser.Parser` discovers some text + after the headers but before the first boundary string, it assigns this + text to the message's *preamble* attribute. When the + :class:`~email.generator.Generator` is writing out the plain text + representation of a MIME message, and it finds the + message has a *preamble* attribute, it will write this text in the area + between the headers and the first boundary. See :mod:`email.parser` and + :mod:`email.generator` for details. + + Note that if the message object has no preamble, the *preamble* attribute + will be ``None``. + + + .. attribute:: epilogue + + The *epilogue* attribute acts the same way as the *preamble* attribute, + except that it contains text that appears between the last boundary and + the end of the message. As with the :attr:`~EmailMessage.preamble`, + if there is no epilog text this attribute will be ``None``. + + + .. attribute:: defects + + The *defects* attribute contains a list of all the problems found when + parsing this message. See :mod:`email.errors` for a detailed description + of the possible parsing defects. + + +.. class:: MIMEPart(policy=default) + + This class represents a subpart of a MIME message. It is identical to + :class:`EmailMessage`, except that no :mailheader:`MIME-Version` headers are + added when :meth:`~EmailMessage.set_content` is called, since sub-parts do + not need their own :mailheader:`MIME-Version` headers. + + +.. rubric:: Footnotes + +.. [1] Originally added in 3.4 as a :term:`provisional module `. Docs for legacy message class moved to + :ref:`compat32_message`. diff --git a/cpython_2/environment/repo/Doc/library/email.mime.rst b/cpython_2/environment/repo/Doc/library/email.mime.rst new file mode 100644 index 0000000000000000000000000000000000000000..f37f6aa28dec7d9fe0bd4c2b5e082326e82f38fa --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/email.mime.rst @@ -0,0 +1,259 @@ +:mod:`email.mime`: Creating email and MIME objects from scratch +--------------------------------------------------------------- + +.. module:: email.mime + :synopsis: Build MIME messages. + +**Source code:** :source:`Lib/email/mime/` + +-------------- + +This module is part of the legacy (``Compat32``) email API. Its functionality +is partially replaced by the :mod:`~email.contentmanager` in the new API, but +in certain applications these classes may still be useful, even in non-legacy +code. + +Ordinarily, you get a message object structure by passing a file or some text to +a parser, which parses the text and returns the root message object. However +you can also build a complete message structure from scratch, or even individual +:class:`~email.message.Message` objects by hand. In fact, you can also take an +existing structure and add new :class:`~email.message.Message` objects, move them +around, etc. This makes a very convenient interface for slicing-and-dicing MIME +messages. + +You can create a new object structure by creating :class:`~email.message.Message` +instances, adding attachments and all the appropriate headers manually. For MIME +messages though, the :mod:`email` package provides some convenient subclasses to +make things easier. + +Here are the classes: + +.. currentmodule:: email.mime.base + +.. class:: MIMEBase(_maintype, _subtype, *, policy=compat32, **_params) + + Module: :mod:`email.mime.base` + + This is the base class for all the MIME-specific subclasses of + :class:`~email.message.Message`. Ordinarily you won't create instances + specifically of :class:`MIMEBase`, although you could. :class:`MIMEBase` + is provided primarily as a convenient base class for more specific + MIME-aware subclasses. + + *_maintype* is the :mailheader:`Content-Type` major type (e.g. :mimetype:`text` + or :mimetype:`image`), and *_subtype* is the :mailheader:`Content-Type` minor + type (e.g. :mimetype:`plain` or :mimetype:`gif`). *_params* is a parameter + key/value dictionary and is passed directly to :meth:`Message.add_header + `. + + If *policy* is specified, (defaults to the + :class:`compat32 ` policy) it will be passed to + :class:`~email.message.Message`. + + The :class:`MIMEBase` class always adds a :mailheader:`Content-Type` header + (based on *_maintype*, *_subtype*, and *_params*), and a + :mailheader:`MIME-Version` header (always set to ``1.0``). + + .. versionchanged:: 3.6 + Added *policy* keyword-only parameter. + + +.. currentmodule:: email.mime.nonmultipart + +.. class:: MIMENonMultipart() + + Module: :mod:`email.mime.nonmultipart` + + A subclass of :class:`~email.mime.base.MIMEBase`, this is an intermediate base + class for MIME messages that are not :mimetype:`multipart`. The primary + purpose of this class is to prevent the use of the + :meth:`~email.message.Message.attach` method, which only makes sense for + :mimetype:`multipart` messages. If :meth:`~email.message.Message.attach` + is called, a :exc:`~email.errors.MultipartConversionError` exception is raised. + + +.. currentmodule:: email.mime.multipart + +.. class:: MIMEMultipart(_subtype='mixed', boundary=None, _subparts=None, \ + *, policy=compat32, **_params) + + Module: :mod:`email.mime.multipart` + + A subclass of :class:`~email.mime.base.MIMEBase`, this is an intermediate base + class for MIME messages that are :mimetype:`multipart`. Optional *_subtype* + defaults to :mimetype:`mixed`, but can be used to specify the subtype of the + message. A :mailheader:`Content-Type` header of :mimetype:`multipart/_subtype` + will be added to the message object. A :mailheader:`MIME-Version` header will + also be added. + + Optional *boundary* is the multipart boundary string. When ``None`` (the + default), the boundary is calculated when needed (for example, when the + message is serialized). + + *_subparts* is a sequence of initial subparts for the payload. It must be + possible to convert this sequence to a list. You can always attach new subparts + to the message by using the :meth:`Message.attach + ` method. + + Optional *policy* argument defaults to :class:`compat32 `. + + Additional parameters for the :mailheader:`Content-Type` header are taken from + the keyword arguments, or passed into the *_params* argument, which is a keyword + dictionary. + + .. versionchanged:: 3.6 + Added *policy* keyword-only parameter. + +.. currentmodule:: email.mime.application + +.. class:: MIMEApplication(_data, _subtype='octet-stream', \ + _encoder=email.encoders.encode_base64, \ + *, policy=compat32, **_params) + + Module: :mod:`email.mime.application` + + A subclass of :class:`~email.mime.nonmultipart.MIMENonMultipart`, the + :class:`MIMEApplication` class is used to represent MIME message objects of + major type :mimetype:`application`. *_data* is a string containing the raw + byte data. Optional *_subtype* specifies the MIME subtype and defaults to + :mimetype:`octet-stream`. + + Optional *_encoder* is a callable (i.e. function) which will perform the actual + encoding of the data for transport. This callable takes one argument, which is + the :class:`MIMEApplication` instance. It should use + :meth:`~email.message.Message.get_payload` and + :meth:`~email.message.Message.set_payload` to change the payload to encoded + form. It should also add + any :mailheader:`Content-Transfer-Encoding` or other headers to the message + object as necessary. The default encoding is base64. See the + :mod:`email.encoders` module for a list of the built-in encoders. + + Optional *policy* argument defaults to :class:`compat32 `. + + *_params* are passed straight through to the base class constructor. + + .. versionchanged:: 3.6 + Added *policy* keyword-only parameter. + +.. currentmodule:: email.mime.audio + +.. class:: MIMEAudio(_audiodata, _subtype=None, \ + _encoder=email.encoders.encode_base64, \ + *, policy=compat32, **_params) + + Module: :mod:`email.mime.audio` + + A subclass of :class:`~email.mime.nonmultipart.MIMENonMultipart`, the + :class:`MIMEAudio` class is used to create MIME message objects of major type + :mimetype:`audio`. *_audiodata* is a string containing the raw audio data. If + this data can be decoded by the standard Python module :mod:`sndhdr`, then the + subtype will be automatically included in the :mailheader:`Content-Type` header. + Otherwise you can explicitly specify the audio subtype via the *_subtype* + argument. If the minor type could not be guessed and *_subtype* was not given, + then :exc:`TypeError` is raised. + + Optional *_encoder* is a callable (i.e. function) which will perform the actual + encoding of the audio data for transport. This callable takes one argument, + which is the :class:`MIMEAudio` instance. It should use + :meth:`~email.message.Message.get_payload` and + :meth:`~email.message.Message.set_payload` to change the payload to encoded + form. It should also add + any :mailheader:`Content-Transfer-Encoding` or other headers to the message + object as necessary. The default encoding is base64. See the + :mod:`email.encoders` module for a list of the built-in encoders. + + Optional *policy* argument defaults to :class:`compat32 `. + + *_params* are passed straight through to the base class constructor. + + .. versionchanged:: 3.6 + Added *policy* keyword-only parameter. + +.. currentmodule:: email.mime.image + +.. class:: MIMEImage(_imagedata, _subtype=None, \ + _encoder=email.encoders.encode_base64, \ + *, policy=compat32, **_params) + + Module: :mod:`email.mime.image` + + A subclass of :class:`~email.mime.nonmultipart.MIMENonMultipart`, the + :class:`MIMEImage` class is used to create MIME message objects of major type + :mimetype:`image`. *_imagedata* is a string containing the raw image data. If + this data can be decoded by the standard Python module :mod:`imghdr`, then the + subtype will be automatically included in the :mailheader:`Content-Type` header. + Otherwise you can explicitly specify the image subtype via the *_subtype* + argument. If the minor type could not be guessed and *_subtype* was not given, + then :exc:`TypeError` is raised. + + Optional *_encoder* is a callable (i.e. function) which will perform the actual + encoding of the image data for transport. This callable takes one argument, + which is the :class:`MIMEImage` instance. It should use + :meth:`~email.message.Message.get_payload` and + :meth:`~email.message.Message.set_payload` to change the payload to encoded + form. It should also add + any :mailheader:`Content-Transfer-Encoding` or other headers to the message + object as necessary. The default encoding is base64. See the + :mod:`email.encoders` module for a list of the built-in encoders. + + Optional *policy* argument defaults to :class:`compat32 `. + + *_params* are passed straight through to the :class:`~email.mime.base.MIMEBase` + constructor. + + .. versionchanged:: 3.6 + Added *policy* keyword-only parameter. + +.. currentmodule:: email.mime.message + +.. class:: MIMEMessage(_msg, _subtype='rfc822', *, policy=compat32) + + Module: :mod:`email.mime.message` + + A subclass of :class:`~email.mime.nonmultipart.MIMENonMultipart`, the + :class:`MIMEMessage` class is used to create MIME objects of main type + :mimetype:`message`. *_msg* is used as the payload, and must be an instance + of class :class:`~email.message.Message` (or a subclass thereof), otherwise + a :exc:`TypeError` is raised. + + Optional *_subtype* sets the subtype of the message; it defaults to + :mimetype:`rfc822`. + + Optional *policy* argument defaults to :class:`compat32 `. + + .. versionchanged:: 3.6 + Added *policy* keyword-only parameter. + +.. currentmodule:: email.mime.text + +.. class:: MIMEText(_text, _subtype='plain', _charset=None, *, policy=compat32) + + Module: :mod:`email.mime.text` + + A subclass of :class:`~email.mime.nonmultipart.MIMENonMultipart`, the + :class:`MIMEText` class is used to create MIME objects of major type + :mimetype:`text`. *_text* is the string for the payload. *_subtype* is the + minor type and defaults to :mimetype:`plain`. *_charset* is the character + set of the text and is passed as an argument to the + :class:`~email.mime.nonmultipart.MIMENonMultipart` constructor; it defaults + to ``us-ascii`` if the string contains only ``ascii`` code points, and + ``utf-8`` otherwise. The *_charset* parameter accepts either a string or a + :class:`~email.charset.Charset` instance. + + Unless the *_charset* argument is explicitly set to ``None``, the + MIMEText object created will have both a :mailheader:`Content-Type` header + with a ``charset`` parameter, and a :mailheader:`Content-Transfer-Encoding` + header. This means that a subsequent ``set_payload`` call will not result + in an encoded payload, even if a charset is passed in the ``set_payload`` + command. You can "reset" this behavior by deleting the + ``Content-Transfer-Encoding`` header, after which a ``set_payload`` call + will automatically encode the new payload (and add a new + :mailheader:`Content-Transfer-Encoding` header). + + Optional *policy* argument defaults to :class:`compat32 `. + + .. versionchanged:: 3.5 + *_charset* also accepts :class:`~email.charset.Charset` instances. + + .. versionchanged:: 3.6 + Added *policy* keyword-only parameter. diff --git a/cpython_2/environment/repo/Doc/library/email.parser.rst b/cpython_2/environment/repo/Doc/library/email.parser.rst new file mode 100644 index 0000000000000000000000000000000000000000..d9a61616bbbdfbde9a79cfb4626a47c1b1e340ae --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/email.parser.rst @@ -0,0 +1,320 @@ +:mod:`email.parser`: Parsing email messages +------------------------------------------- + +.. module:: email.parser + :synopsis: Parse flat text email messages to produce a message object structure. + +**Source code:** :source:`Lib/email/parser.py` + +-------------- + +Message object structures can be created in one of two ways: they can be +created from whole cloth by creating an :class:`~email.message.EmailMessage` +object, adding headers using the dictionary interface, and adding payload(s) +using :meth:`~email.message.EmailMessage.set_content` and related methods, or +they can be created by parsing a serialized representation of the email +message. + +The :mod:`email` package provides a standard parser that understands most email +document structures, including MIME documents. You can pass the parser a +bytes, string or file object, and the parser will return to you the root +:class:`~email.message.EmailMessage` instance of the object structure. For +simple, non-MIME messages the payload of this root object will likely be a +string containing the text of the message. For MIME messages, the root object +will return ``True`` from its :meth:`~email.message.EmailMessage.is_multipart` +method, and the subparts can be accessed via the payload manipulation methods, +such as :meth:`~email.message.EmailMessage.get_body`, +:meth:`~email.message.EmailMessage.iter_parts`, and +:meth:`~email.message.EmailMessage.walk`. + +There are actually two parser interfaces available for use, the :class:`Parser` +API and the incremental :class:`FeedParser` API. The :class:`Parser` API is +most useful if you have the entire text of the message in memory, or if the +entire message lives in a file on the file system. :class:`FeedParser` is more +appropriate when you are reading the message from a stream which might block +waiting for more input (such as reading an email message from a socket). The +:class:`FeedParser` can consume and parse the message incrementally, and only +returns the root object when you close the parser. + +Note that the parser can be extended in limited ways, and of course you can +implement your own parser completely from scratch. All of the logic that +connects the :mod:`email` package's bundled parser and the +:class:`~email.message.EmailMessage` class is embodied in the :mod:`policy` +class, so a custom parser can create message object trees any way it finds +necessary by implementing custom versions of the appropriate :mod:`policy` +methods. + + +FeedParser API +^^^^^^^^^^^^^^ + +The :class:`BytesFeedParser`, imported from the :mod:`email.feedparser` module, +provides an API that is conducive to incremental parsing of email messages, +such as would be necessary when reading the text of an email message from a +source that can block (such as a socket). The :class:`BytesFeedParser` can of +course be used to parse an email message fully contained in a :term:`bytes-like +object`, string, or file, but the :class:`BytesParser` API may be more +convenient for such use cases. The semantics and results of the two parser +APIs are identical. + +The :class:`BytesFeedParser`'s API is simple; you create an instance, feed it a +bunch of bytes until there's no more to feed it, then close the parser to +retrieve the root message object. The :class:`BytesFeedParser` is extremely +accurate when parsing standards-compliant messages, and it does a very good job +of parsing non-compliant messages, providing information about how a message +was deemed broken. It will populate a message object's +:attr:`~email.message.EmailMessage.defects` attribute with a list of any +problems it found in a message. See the :mod:`email.errors` module for the +list of defects that it can find. + +Here is the API for the :class:`BytesFeedParser`: + + +.. class:: BytesFeedParser(_factory=None, *, policy=policy.compat32) + + Create a :class:`BytesFeedParser` instance. Optional *_factory* is a + no-argument callable; if not specified use the + :attr:`~email.policy.Policy.message_factory` from the *policy*. Call + *_factory* whenever a new message object is needed. + + If *policy* is specified use the rules it specifies to update the + representation of the message. If *policy* is not set, use the + :class:`compat32 ` policy, which maintains backward + compatibility with the Python 3.2 version of the email package and provides + :class:`~email.message.Message` as the default factory. All other policies + provide :class:`~email.message.EmailMessage` as the default *_factory*. For + more information on what else *policy* controls, see the + :mod:`~email.policy` documentation. + + Note: **The policy keyword should always be specified**; The default will + change to :data:`email.policy.default` in a future version of Python. + + .. versionadded:: 3.2 + + .. versionchanged:: 3.3 Added the *policy* keyword. + .. versionchanged:: 3.6 *_factory* defaults to the policy ``message_factory``. + + + .. method:: feed(data) + + Feed the parser some more data. *data* should be a :term:`bytes-like + object` containing one or more lines. The lines can be partial and the + parser will stitch such partial lines together properly. The lines can + have any of the three common line endings: carriage return, newline, or + carriage return and newline (they can even be mixed). + + + .. method:: close() + + Complete the parsing of all previously fed data and return the root + message object. It is undefined what happens if :meth:`~feed` is called + after this method has been called. + + +.. class:: FeedParser(_factory=None, *, policy=policy.compat32) + + Works like :class:`BytesFeedParser` except that the input to the + :meth:`~BytesFeedParser.feed` method must be a string. This is of limited + utility, since the only way for such a message to be valid is for it to + contain only ASCII text or, if :attr:`~email.policy.Policy.utf8` is + ``True``, no binary attachments. + + .. versionchanged:: 3.3 Added the *policy* keyword. + + +Parser API +^^^^^^^^^^ + +The :class:`BytesParser` class, imported from the :mod:`email.parser` module, +provides an API that can be used to parse a message when the complete contents +of the message are available in a :term:`bytes-like object` or file. The +:mod:`email.parser` module also provides :class:`Parser` for parsing strings, +and header-only parsers, :class:`BytesHeaderParser` and +:class:`HeaderParser`, which can be used if you're only interested in the +headers of the message. :class:`BytesHeaderParser` and :class:`HeaderParser` +can be much faster in these situations, since they do not attempt to parse the +message body, instead setting the payload to the raw body. + + +.. class:: BytesParser(_class=None, *, policy=policy.compat32) + + Create a :class:`BytesParser` instance. The *_class* and *policy* + arguments have the same meaning and semantics as the *_factory* + and *policy* arguments of :class:`BytesFeedParser`. + + Note: **The policy keyword should always be specified**; The default will + change to :data:`email.policy.default` in a future version of Python. + + .. versionchanged:: 3.3 + Removed the *strict* argument that was deprecated in 2.4. Added the + *policy* keyword. + .. versionchanged:: 3.6 *_class* defaults to the policy ``message_factory``. + + + .. method:: parse(fp, headersonly=False) + + Read all the data from the binary file-like object *fp*, parse the + resulting bytes, and return the message object. *fp* must support + both the :meth:`~io.IOBase.readline` and the :meth:`~io.IOBase.read` + methods. + + The bytes contained in *fp* must be formatted as a block of :rfc:`5322` + (or, if :attr:`~email.policy.Policy.utf8` is ``True``, :rfc:`6532`) + style headers and header continuation lines, optionally preceded by an + envelope header. The header block is terminated either by the end of the + data or by a blank line. Following the header block is the body of the + message (which may contain MIME-encoded subparts, including subparts + with a :mailheader:`Content-Transfer-Encoding` of ``8bit``). + + Optional *headersonly* is a flag specifying whether to stop parsing after + reading the headers or not. The default is ``False``, meaning it parses + the entire contents of the file. + + + .. method:: parsebytes(bytes, headersonly=False) + + Similar to the :meth:`parse` method, except it takes a :term:`bytes-like + object` instead of a file-like object. Calling this method on a + :term:`bytes-like object` is equivalent to wrapping *bytes* in a + :class:`~io.BytesIO` instance first and calling :meth:`parse`. + + Optional *headersonly* is as with the :meth:`parse` method. + + .. versionadded:: 3.2 + + +.. class:: BytesHeaderParser(_class=None, *, policy=policy.compat32) + + Exactly like :class:`BytesParser`, except that *headersonly* + defaults to ``True``. + + .. versionadded:: 3.3 + + +.. class:: Parser(_class=None, *, policy=policy.compat32) + + This class is parallel to :class:`BytesParser`, but handles string input. + + .. versionchanged:: 3.3 + Removed the *strict* argument. Added the *policy* keyword. + .. versionchanged:: 3.6 *_class* defaults to the policy ``message_factory``. + + + .. method:: parse(fp, headersonly=False) + + Read all the data from the text-mode file-like object *fp*, parse the + resulting text, and return the root message object. *fp* must support + both the :meth:`~io.TextIOBase.readline` and the + :meth:`~io.TextIOBase.read` methods on file-like objects. + + Other than the text mode requirement, this method operates like + :meth:`BytesParser.parse`. + + + .. method:: parsestr(text, headersonly=False) + + Similar to the :meth:`parse` method, except it takes a string object + instead of a file-like object. Calling this method on a string is + equivalent to wrapping *text* in a :class:`~io.StringIO` instance first + and calling :meth:`parse`. + + Optional *headersonly* is as with the :meth:`parse` method. + + +.. class:: HeaderParser(_class=None, *, policy=policy.compat32) + + Exactly like :class:`Parser`, except that *headersonly* + defaults to ``True``. + + +Since creating a message object structure from a string or a file object is such +a common task, four functions are provided as a convenience. They are available +in the top-level :mod:`email` package namespace. + +.. currentmodule:: email + + +.. function:: message_from_bytes(s, _class=None, *, policy=policy.compat32) + + Return a message object structure from a :term:`bytes-like object`. This is + equivalent to ``BytesParser().parsebytes(s)``. Optional *_class* and + *policy* are interpreted as with the :class:`~email.parser.BytesParser` class + constructor. + + .. versionadded:: 3.2 + .. versionchanged:: 3.3 + Removed the *strict* argument. Added the *policy* keyword. + + +.. function:: message_from_binary_file(fp, _class=None, *, \ + policy=policy.compat32) + + Return a message object structure tree from an open binary :term:`file + object`. This is equivalent to ``BytesParser().parse(fp)``. *_class* and + *policy* are interpreted as with the :class:`~email.parser.BytesParser` class + constructor. + + .. versionadded:: 3.2 + .. versionchanged:: 3.3 + Removed the *strict* argument. Added the *policy* keyword. + + +.. function:: message_from_string(s, _class=None, *, policy=policy.compat32) + + Return a message object structure from a string. This is equivalent to + ``Parser().parsestr(s)``. *_class* and *policy* are interpreted as + with the :class:`~email.parser.Parser` class constructor. + + .. versionchanged:: 3.3 + Removed the *strict* argument. Added the *policy* keyword. + + +.. function:: message_from_file(fp, _class=None, *, policy=policy.compat32) + + Return a message object structure tree from an open :term:`file object`. + This is equivalent to ``Parser().parse(fp)``. *_class* and *policy* are + interpreted as with the :class:`~email.parser.Parser` class constructor. + + .. versionchanged:: 3.3 + Removed the *strict* argument. Added the *policy* keyword. + .. versionchanged:: 3.6 *_class* defaults to the policy ``message_factory``. + + +Here's an example of how you might use :func:`message_from_bytes` at an +interactive Python prompt:: + + >>> import email + >>> msg = email.message_from_bytes(myBytes) # doctest: +SKIP + + +Additional notes +^^^^^^^^^^^^^^^^ + +Here are some notes on the parsing semantics: + +* Most non-\ :mimetype:`multipart` type messages are parsed as a single message + object with a string payload. These objects will return ``False`` for + :meth:`~email.message.EmailMessage.is_multipart`, and + :meth:`~email.message.EmailMessage.iter_parts` will yield an empty list. + +* All :mimetype:`multipart` type messages will be parsed as a container message + object with a list of sub-message objects for their payload. The outer + container message will return ``True`` for + :meth:`~email.message.EmailMessage.is_multipart`, and + :meth:`~email.message.EmailMessage.iter_parts` will yield a list of subparts. + +* Most messages with a content type of :mimetype:`message/\*` (such as + :mimetype:`message/delivery-status` and :mimetype:`message/rfc822`) will also + be parsed as container object containing a list payload of length 1. Their + :meth:`~email.message.EmailMessage.is_multipart` method will return ``True``. + The single element yielded by :meth:`~email.message.EmailMessage.iter_parts` + will be a sub-message object. + +* Some non-standards-compliant messages may not be internally consistent about + their :mimetype:`multipart`\ -edness. Such messages may have a + :mailheader:`Content-Type` header of type :mimetype:`multipart`, but their + :meth:`~email.message.EmailMessage.is_multipart` method may return ``False``. + If such messages were parsed with the :class:`~email.parser.FeedParser`, + they will have an instance of the + :class:`~email.errors.MultipartInvariantViolationDefect` class in their + *defects* attribute list. See :mod:`email.errors` for details. diff --git a/cpython_2/environment/repo/Doc/library/email.policy.rst b/cpython_2/environment/repo/Doc/library/email.policy.rst new file mode 100644 index 0000000000000000000000000000000000000000..8e7076259810f55bb75727fb67f0cb0e1447cb3c --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/email.policy.rst @@ -0,0 +1,651 @@ +:mod:`email.policy`: Policy Objects +----------------------------------- + +.. module:: email.policy + :synopsis: Controlling the parsing and generating of messages + +.. moduleauthor:: R. David Murray +.. sectionauthor:: R. David Murray + +.. versionadded:: 3.3 + +**Source code:** :source:`Lib/email/policy.py` + +-------------- + +The :mod:`email` package's prime focus is the handling of email messages as +described by the various email and MIME RFCs. However, the general format of +email messages (a block of header fields each consisting of a name followed by +a colon followed by a value, the whole block followed by a blank line and an +arbitrary 'body'), is a format that has found utility outside of the realm of +email. Some of these uses conform fairly closely to the main email RFCs, some +do not. Even when working with email, there are times when it is desirable to +break strict compliance with the RFCs, such as generating emails that +interoperate with email servers that do not themselves follow the standards, or +that implement extensions you want to use in ways that violate the +standards. + +Policy objects give the email package the flexibility to handle all these +disparate use cases. + +A :class:`Policy` object encapsulates a set of attributes and methods that +control the behavior of various components of the email package during use. +:class:`Policy` instances can be passed to various classes and methods in the +email package to alter the default behavior. The settable values and their +defaults are described below. + +There is a default policy used by all classes in the email package. For all of +the :mod:`~email.parser` classes and the related convenience functions, and for +the :class:`~email.message.Message` class, this is the :class:`Compat32` +policy, via its corresponding pre-defined instance :const:`compat32`. This +policy provides for complete backward compatibility (in some cases, including +bug compatibility) with the pre-Python3.3 version of the email package. + +This default value for the *policy* keyword to +:class:`~email.message.EmailMessage` is the :class:`EmailPolicy` policy, via +its pre-defined instance :data:`~default`. + +When a :class:`~email.message.Message` or :class:`~email.message.EmailMessage` +object is created, it acquires a policy. If the message is created by a +:mod:`~email.parser`, a policy passed to the parser will be the policy used by +the message it creates. If the message is created by the program, then the +policy can be specified when it is created. When a message is passed to a +:mod:`~email.generator`, the generator uses the policy from the message by +default, but you can also pass a specific policy to the generator that will +override the one stored on the message object. + +The default value for the *policy* keyword for the :mod:`email.parser` classes +and the parser convenience functions **will be changing** in a future version of +Python. Therefore you should **always specify explicitly which policy you want +to use** when calling any of the classes and functions described in the +:mod:`~email.parser` module. + +The first part of this documentation covers the features of :class:`Policy`, an +:term:`abstract base class` that defines the features that are common to all +policy objects, including :const:`compat32`. This includes certain hook +methods that are called internally by the email package, which a custom policy +could override to obtain different behavior. The second part describes the +concrete classes :class:`EmailPolicy` and :class:`Compat32`, which implement +the hooks that provide the standard behavior and the backward compatible +behavior and features, respectively. + +:class:`Policy` instances are immutable, but they can be cloned, accepting the +same keyword arguments as the class constructor and returning a new +:class:`Policy` instance that is a copy of the original but with the specified +attributes values changed. + +As an example, the following code could be used to read an email message from a +file on disk and pass it to the system ``sendmail`` program on a Unix system: + +.. testsetup:: + + from unittest import mock + mocker = mock.patch('subprocess.Popen') + m = mocker.start() + proc = mock.MagicMock() + m.return_value = proc + proc.stdin.close.return_value = None + mymsg = open('mymsg.txt', 'w') + mymsg.write('To: abc@xyz.com\n\n') + mymsg.flush() + +.. doctest:: + + >>> from email import message_from_binary_file + >>> from email.generator import BytesGenerator + >>> from email import policy + >>> from subprocess import Popen, PIPE + >>> with open('mymsg.txt', 'rb') as f: + ... msg = message_from_binary_file(f, policy=policy.default) + >>> p = Popen(['sendmail', msg['To'].addresses[0]], stdin=PIPE) + >>> g = BytesGenerator(p.stdin, policy=msg.policy.clone(linesep='\r\n')) + >>> g.flatten(msg) + >>> p.stdin.close() + >>> rc = p.wait() + +.. testcleanup:: + + mymsg.close() + mocker.stop() + import os + os.remove('mymsg.txt') + +Here we are telling :class:`~email.generator.BytesGenerator` to use the RFC +correct line separator characters when creating the binary string to feed into +``sendmail's`` ``stdin``, where the default policy would use ``\n`` line +separators. + +Some email package methods accept a *policy* keyword argument, allowing the +policy to be overridden for that method. For example, the following code uses +the :meth:`~email.message.Message.as_bytes` method of the *msg* object from +the previous example and writes the message to a file using the native line +separators for the platform on which it is running:: + + >>> import os + >>> with open('converted.txt', 'wb') as f: + ... f.write(msg.as_bytes(policy=msg.policy.clone(linesep=os.linesep))) + 17 + +Policy objects can also be combined using the addition operator, producing a +policy object whose settings are a combination of the non-default values of the +summed objects:: + + >>> compat_SMTP = policy.compat32.clone(linesep='\r\n') + >>> compat_strict = policy.compat32.clone(raise_on_defect=True) + >>> compat_strict_SMTP = compat_SMTP + compat_strict + +This operation is not commutative; that is, the order in which the objects are +added matters. To illustrate:: + + >>> policy100 = policy.compat32.clone(max_line_length=100) + >>> policy80 = policy.compat32.clone(max_line_length=80) + >>> apolicy = policy100 + policy80 + >>> apolicy.max_line_length + 80 + >>> apolicy = policy80 + policy100 + >>> apolicy.max_line_length + 100 + + +.. class:: Policy(**kw) + + This is the :term:`abstract base class` for all policy classes. It provides + default implementations for a couple of trivial methods, as well as the + implementation of the immutability property, the :meth:`clone` method, and + the constructor semantics. + + The constructor of a policy class can be passed various keyword arguments. + The arguments that may be specified are any non-method properties on this + class, plus any additional non-method properties on the concrete class. A + value specified in the constructor will override the default value for the + corresponding attribute. + + This class defines the following properties, and thus values for the + following may be passed in the constructor of any policy class: + + + .. attribute:: max_line_length + + The maximum length of any line in the serialized output, not counting the + end of line character(s). Default is 78, per :rfc:`5322`. A value of + ``0`` or :const:`None` indicates that no line wrapping should be + done at all. + + + .. attribute:: linesep + + The string to be used to terminate lines in serialized output. The + default is ``\n`` because that's the internal end-of-line discipline used + by Python, though ``\r\n`` is required by the RFCs. + + + .. attribute:: cte_type + + Controls the type of Content Transfer Encodings that may be or are + required to be used. The possible values are: + + .. tabularcolumns:: |l|L| + + ======== =============================================================== + ``7bit`` all data must be "7 bit clean" (ASCII-only). This means that + where necessary data will be encoded using either + quoted-printable or base64 encoding. + + ``8bit`` data is not constrained to be 7 bit clean. Data in headers is + still required to be ASCII-only and so will be encoded (see + :meth:`fold_binary` and :attr:`~EmailPolicy.utf8` below for + exceptions), but body parts may use the ``8bit`` CTE. + ======== =============================================================== + + A ``cte_type`` value of ``8bit`` only works with ``BytesGenerator``, not + ``Generator``, because strings cannot contain binary data. If a + ``Generator`` is operating under a policy that specifies + ``cte_type=8bit``, it will act as if ``cte_type`` is ``7bit``. + + + .. attribute:: raise_on_defect + + If :const:`True`, any defects encountered will be raised as errors. If + :const:`False` (the default), defects will be passed to the + :meth:`register_defect` method. + + + .. attribute:: mangle_from\_ + + If :const:`True`, lines starting with *"From "* in the body are + escaped by putting a ``>`` in front of them. This parameter is used when + the message is being serialized by a generator. + Default: :const:`False`. + + .. versionadded:: 3.5 + The *mangle_from_* parameter. + + + .. attribute:: message_factory + + A factory function for constructing a new empty message object. Used + by the parser when building messages. Defaults to ``None``, in + which case :class:`~email.message.Message` is used. + + .. versionadded:: 3.6 + + The following :class:`Policy` method is intended to be called by code using + the email library to create policy instances with custom settings: + + + .. method:: clone(**kw) + + Return a new :class:`Policy` instance whose attributes have the same + values as the current instance, except where those attributes are + given new values by the keyword arguments. + + + The remaining :class:`Policy` methods are called by the email package code, + and are not intended to be called by an application using the email package. + A custom policy must implement all of these methods. + + + .. method:: handle_defect(obj, defect) + + Handle a *defect* found on *obj*. When the email package calls this + method, *defect* will always be a subclass of + :class:`~email.errors.Defect`. + + The default implementation checks the :attr:`raise_on_defect` flag. If + it is ``True``, *defect* is raised as an exception. If it is ``False`` + (the default), *obj* and *defect* are passed to :meth:`register_defect`. + + + .. method:: register_defect(obj, defect) + + Register a *defect* on *obj*. In the email package, *defect* will always + be a subclass of :class:`~email.errors.Defect`. + + The default implementation calls the ``append`` method of the ``defects`` + attribute of *obj*. When the email package calls :attr:`handle_defect`, + *obj* will normally have a ``defects`` attribute that has an ``append`` + method. Custom object types used with the email package (for example, + custom ``Message`` objects) should also provide such an attribute, + otherwise defects in parsed messages will raise unexpected errors. + + + .. method:: header_max_count(name) + + Return the maximum allowed number of headers named *name*. + + Called when a header is added to an :class:`~email.message.EmailMessage` + or :class:`~email.message.Message` object. If the returned value is not + ``0`` or ``None``, and there are already a number of headers with the + name *name* greater than or equal to the value returned, a + :exc:`ValueError` is raised. + + Because the default behavior of ``Message.__setitem__`` is to append the + value to the list of headers, it is easy to create duplicate headers + without realizing it. This method allows certain headers to be limited + in the number of instances of that header that may be added to a + ``Message`` programmatically. (The limit is not observed by the parser, + which will faithfully produce as many headers as exist in the message + being parsed.) + + The default implementation returns ``None`` for all header names. + + + .. method:: header_source_parse(sourcelines) + + The email package calls this method with a list of strings, each string + ending with the line separation characters found in the source being + parsed. The first line includes the field header name and separator. + All whitespace in the source is preserved. The method should return the + ``(name, value)`` tuple that is to be stored in the ``Message`` to + represent the parsed header. + + If an implementation wishes to retain compatibility with the existing + email package policies, *name* should be the case preserved name (all + characters up to the '``:``' separator), while *value* should be the + unfolded value (all line separator characters removed, but whitespace + kept intact), stripped of leading whitespace. + + *sourcelines* may contain surrogateescaped binary data. + + There is no default implementation + + + .. method:: header_store_parse(name, value) + + The email package calls this method with the name and value provided by + the application program when the application program is modifying a + ``Message`` programmatically (as opposed to a ``Message`` created by a + parser). The method should return the ``(name, value)`` tuple that is to + be stored in the ``Message`` to represent the header. + + If an implementation wishes to retain compatibility with the existing + email package policies, the *name* and *value* should be strings or + string subclasses that do not change the content of the passed in + arguments. + + There is no default implementation + + + .. method:: header_fetch_parse(name, value) + + The email package calls this method with the *name* and *value* currently + stored in the ``Message`` when that header is requested by the + application program, and whatever the method returns is what is passed + back to the application as the value of the header being retrieved. + Note that there may be more than one header with the same name stored in + the ``Message``; the method is passed the specific name and value of the + header destined to be returned to the application. + + *value* may contain surrogateescaped binary data. There should be no + surrogateescaped binary data in the value returned by the method. + + There is no default implementation + + + .. method:: fold(name, value) + + The email package calls this method with the *name* and *value* currently + stored in the ``Message`` for a given header. The method should return a + string that represents that header "folded" correctly (according to the + policy settings) by composing the *name* with the *value* and inserting + :attr:`linesep` characters at the appropriate places. See :rfc:`5322` + for a discussion of the rules for folding email headers. + + *value* may contain surrogateescaped binary data. There should be no + surrogateescaped binary data in the string returned by the method. + + + .. method:: fold_binary(name, value) + + The same as :meth:`fold`, except that the returned value should be a + bytes object rather than a string. + + *value* may contain surrogateescaped binary data. These could be + converted back into binary data in the returned bytes object. + + + +.. class:: EmailPolicy(**kw) + + This concrete :class:`Policy` provides behavior that is intended to be fully + compliant with the current email RFCs. These include (but are not limited + to) :rfc:`5322`, :rfc:`2047`, and the current MIME RFCs. + + This policy adds new header parsing and folding algorithms. Instead of + simple strings, headers are ``str`` subclasses with attributes that depend + on the type of the field. The parsing and folding algorithm fully implement + :rfc:`2047` and :rfc:`5322`. + + The default value for the :attr:`~email.policy.Policy.message_factory` + attribute is :class:`~email.message.EmailMessage`. + + In addition to the settable attributes listed above that apply to all + policies, this policy adds the following additional attributes: + + .. versionadded:: 3.6 [1]_ + + + .. attribute:: utf8 + + If ``False``, follow :rfc:`5322`, supporting non-ASCII characters in + headers by encoding them as "encoded words". If ``True``, follow + :rfc:`6532` and use ``utf-8`` encoding for headers. Messages + formatted in this way may be passed to SMTP servers that support + the ``SMTPUTF8`` extension (:rfc:`6531`). + + + .. attribute:: refold_source + + If the value for a header in the ``Message`` object originated from a + :mod:`~email.parser` (as opposed to being set by a program), this + attribute indicates whether or not a generator should refold that value + when transforming the message back into serialized form. The possible + values are: + + ======== =============================================================== + ``none`` all source values use original folding + + ``long`` source values that have any line that is longer than + ``max_line_length`` will be refolded + + ``all`` all values are refolded. + ======== =============================================================== + + The default is ``long``. + + + .. attribute:: header_factory + + A callable that takes two arguments, ``name`` and ``value``, where + ``name`` is a header field name and ``value`` is an unfolded header field + value, and returns a string subclass that represents that header. A + default ``header_factory`` (see :mod:`~email.headerregistry`) is provided + that supports custom parsing for the various address and date :RFC:`5322` + header field types, and the major MIME header field stypes. Support for + additional custom parsing will be added in the future. + + + .. attribute:: content_manager + + An object with at least two methods: get_content and set_content. When + the :meth:`~email.message.EmailMessage.get_content` or + :meth:`~email.message.EmailMessage.set_content` method of an + :class:`~email.message.EmailMessage` object is called, it calls the + corresponding method of this object, passing it the message object as its + first argument, and any arguments or keywords that were passed to it as + additional arguments. By default ``content_manager`` is set to + :data:`~email.contentmanager.raw_data_manager`. + + .. versionadded:: 3.4 + + + The class provides the following concrete implementations of the abstract + methods of :class:`Policy`: + + + .. method:: header_max_count(name) + + Returns the value of the + :attr:`~email.headerregistry.BaseHeader.max_count` attribute of the + specialized class used to represent the header with the given name. + + + .. method:: header_source_parse(sourcelines) + + + The name is parsed as everything up to the '``:``' and returned + unmodified. The value is determined by stripping leading whitespace off + the remainder of the first line, joining all subsequent lines together, + and stripping any trailing carriage return or linefeed characters. + + + .. method:: header_store_parse(name, value) + + The name is returned unchanged. If the input value has a ``name`` + attribute and it matches *name* ignoring case, the value is returned + unchanged. Otherwise the *name* and *value* are passed to + ``header_factory``, and the resulting header object is returned as + the value. In this case a ``ValueError`` is raised if the input value + contains CR or LF characters. + + + .. method:: header_fetch_parse(name, value) + + If the value has a ``name`` attribute, it is returned to unmodified. + Otherwise the *name*, and the *value* with any CR or LF characters + removed, are passed to the ``header_factory``, and the resulting + header object is returned. Any surrogateescaped bytes get turned into + the unicode unknown-character glyph. + + + .. method:: fold(name, value) + + Header folding is controlled by the :attr:`refold_source` policy setting. + A value is considered to be a 'source value' if and only if it does not + have a ``name`` attribute (having a ``name`` attribute means it is a + header object of some sort). If a source value needs to be refolded + according to the policy, it is converted into a header object by + passing the *name* and the *value* with any CR and LF characters removed + to the ``header_factory``. Folding of a header object is done by + calling its ``fold`` method with the current policy. + + Source values are split into lines using :meth:`~str.splitlines`. If + the value is not to be refolded, the lines are rejoined using the + ``linesep`` from the policy and returned. The exception is lines + containing non-ascii binary data. In that case the value is refolded + regardless of the ``refold_source`` setting, which causes the binary data + to be CTE encoded using the ``unknown-8bit`` charset. + + + .. method:: fold_binary(name, value) + + The same as :meth:`fold` if :attr:`~Policy.cte_type` is ``7bit``, except + that the returned value is bytes. + + If :attr:`~Policy.cte_type` is ``8bit``, non-ASCII binary data is + converted back + into bytes. Headers with binary data are not refolded, regardless of the + ``refold_header`` setting, since there is no way to know whether the + binary data consists of single byte characters or multibyte characters. + + +The following instances of :class:`EmailPolicy` provide defaults suitable for +specific application domains. Note that in the future the behavior of these +instances (in particular the ``HTTP`` instance) may be adjusted to conform even +more closely to the RFCs relevant to their domains. + + +.. data:: default + + An instance of ``EmailPolicy`` with all defaults unchanged. This policy + uses the standard Python ``\n`` line endings rather than the RFC-correct + ``\r\n``. + + +.. data:: SMTP + + Suitable for serializing messages in conformance with the email RFCs. + Like ``default``, but with ``linesep`` set to ``\r\n``, which is RFC + compliant. + + +.. data:: SMTPUTF8 + + The same as ``SMTP`` except that :attr:`~EmailPolicy.utf8` is ``True``. + Useful for serializing messages to a message store without using encoded + words in the headers. Should only be used for SMTP transmission if the + sender or recipient addresses have non-ASCII characters (the + :meth:`smtplib.SMTP.send_message` method handles this automatically). + + +.. data:: HTTP + + Suitable for serializing headers with for use in HTTP traffic. Like + ``SMTP`` except that ``max_line_length`` is set to ``None`` (unlimited). + + +.. data:: strict + + Convenience instance. The same as ``default`` except that + ``raise_on_defect`` is set to ``True``. This allows any policy to be made + strict by writing:: + + somepolicy + policy.strict + + +With all of these :class:`EmailPolicies <.EmailPolicy>`, the effective API of +the email package is changed from the Python 3.2 API in the following ways: + + * Setting a header on a :class:`~email.message.Message` results in that + header being parsed and a header object created. + + * Fetching a header value from a :class:`~email.message.Message` results + in that header being parsed and a header object created and + returned. + + * Any header object, or any header that is refolded due to the + policy settings, is folded using an algorithm that fully implements the + RFC folding algorithms, including knowing where encoded words are required + and allowed. + +From the application view, this means that any header obtained through the +:class:`~email.message.EmailMessage` is a header object with extra +attributes, whose string value is the fully decoded unicode value of the +header. Likewise, a header may be assigned a new value, or a new header +created, using a unicode string, and the policy will take care of converting +the unicode string into the correct RFC encoded form. + +The header objects and their attributes are described in +:mod:`~email.headerregistry`. + + + +.. class:: Compat32(**kw) + + This concrete :class:`Policy` is the backward compatibility policy. It + replicates the behavior of the email package in Python 3.2. The + :mod:`~email.policy` module also defines an instance of this class, + :const:`compat32`, that is used as the default policy. Thus the default + behavior of the email package is to maintain compatibility with Python 3.2. + + The following attributes have values that are different from the + :class:`Policy` default: + + + .. attribute:: mangle_from_ + + The default is ``True``. + + + The class provides the following concrete implementations of the + abstract methods of :class:`Policy`: + + + .. method:: header_source_parse(sourcelines) + + The name is parsed as everything up to the '``:``' and returned + unmodified. The value is determined by stripping leading whitespace off + the remainder of the first line, joining all subsequent lines together, + and stripping any trailing carriage return or linefeed characters. + + + .. method:: header_store_parse(name, value) + + The name and value are returned unmodified. + + + .. method:: header_fetch_parse(name, value) + + If the value contains binary data, it is converted into a + :class:`~email.header.Header` object using the ``unknown-8bit`` charset. + Otherwise it is returned unmodified. + + + .. method:: fold(name, value) + + Headers are folded using the :class:`~email.header.Header` folding + algorithm, which preserves existing line breaks in the value, and wraps + each resulting line to the ``max_line_length``. Non-ASCII binary data are + CTE encoded using the ``unknown-8bit`` charset. + + + .. method:: fold_binary(name, value) + + Headers are folded using the :class:`~email.header.Header` folding + algorithm, which preserves existing line breaks in the value, and wraps + each resulting line to the ``max_line_length``. If ``cte_type`` is + ``7bit``, non-ascii binary data is CTE encoded using the ``unknown-8bit`` + charset. Otherwise the original source header is used, with its existing + line breaks and any (RFC invalid) binary data it may contain. + + +.. data:: compat32 + + An instance of :class:`Compat32`, providing backward compatibility with the + behavior of the email package in Python 3.2. + + +.. rubric:: Footnotes + +.. [1] Originally added in 3.3 as a :term:`provisional feature `. diff --git a/cpython_2/environment/repo/Doc/library/email.rst b/cpython_2/environment/repo/Doc/library/email.rst new file mode 100644 index 0000000000000000000000000000000000000000..fae99cf3e6abbed983fbc9c55de04b9cf515eb5d --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/email.rst @@ -0,0 +1,152 @@ +:mod:`email` --- An email and MIME handling package +=================================================== + +.. module:: email + :synopsis: Package supporting the parsing, manipulating, and generating + email messages. +.. moduleauthor:: Barry A. Warsaw , + R. David Murray +.. sectionauthor:: R. David Murray + +**Source code:** :source:`Lib/email/__init__.py` + +-------------- + +The :mod:`email` package is a library for managing email messages. It is +specifically *not* designed to do any sending of email messages to SMTP +(:rfc:`2821`), NNTP, or other servers; those are functions of modules such as +:mod:`smtplib` and :mod:`nntplib`. The :mod:`email` package attempts to be as +RFC-compliant as possible, supporting :rfc:`5233` and :rfc:`6532`, as well as +such MIME-related RFCs as :rfc:`2045`, :rfc:`2046`, :rfc:`2047`, :rfc:`2183`, +and :rfc:`2231`. + +The overall structure of the email package can be divided into three major +components, plus a fourth component that controls the behavior of the other +components. + +The central component of the package is an "object model" that represents email +messages. An application interacts with the package primarily through the +object model interface defined in the :mod:`~email.message` sub-module. The +application can use this API to ask questions about an existing email, to +construct a new email, or to add or remove email subcomponents that themselves +use the same object model interface. That is, following the nature of email +messages and their MIME subcomponents, the email object model is a tree +structure of objects that all provide the :class:`~email.message.EmailMessage` +API. + +The other two major components of the package are the :mod:`~email.parser` and +the :mod:`~email.generator`. The parser takes the serialized version of an +email message (a stream of bytes) and converts it into a tree of +:class:`~email.message.EmailMessage` objects. The generator takes an +:class:`~email.message.EmailMessage` and turns it back into a serialized byte +stream. (The parser and generator also handle streams of text characters, but +this usage is discouraged as it is too easy to end up with messages that are +not valid in one way or another.) + +The control component is the :mod:`~email.policy` module. Every +:class:`~email.message.EmailMessage`, every :mod:`~email.generator`, and every +:mod:`~email.parser` has an associated :mod:`~email.policy` object that +controls its behavior. Usually an application only needs to specify the policy +when an :class:`~email.message.EmailMessage` is created, either by directly +instantiating an :class:`~email.message.EmailMessage` to create a new email, +or by parsing an input stream using a :mod:`~email.parser`. But the policy can +be changed when the message is serialized using a :mod:`~email.generator`. +This allows, for example, a generic email message to be parsed from disk, but +to serialize it using standard SMTP settings when sending it to an email +server. + +The email package does its best to hide the details of the various governing +RFCs from the application. Conceptually the application should be able to +treat the email message as a structured tree of unicode text and binary +attachments, without having to worry about how these are represented when +serialized. In practice, however, it is often necessary to be aware of at +least some of the rules governing MIME messages and their structure, +specifically the names and nature of the MIME "content types" and how they +identify multipart documents. For the most part this knowledge should only be +required for more complex applications, and even then it should only be the +high level structure in question, and not the details of how those structures +are represented. Since MIME content types are used widely in modern internet +software (not just email), this will be a familiar concept to many programmers. + +The following sections describe the functionality of the :mod:`email` package. +We start with the :mod:`~email.message` object model, which is the primary +interface an application will use, and follow that with the +:mod:`~email.parser` and :mod:`~email.generator` components. Then we cover the +:mod:`~email.policy` controls, which completes the treatment of the main +components of the library. + +The next three sections cover the exceptions the package may raise and the +defects (non-compliance with the RFCs) that the :mod:`~email.parser` may +detect. Then we cover the :mod:`~email.headerregistry` and the +:mod:`~email.contentmanager` sub-components, which provide tools for doing more +detailed manipulation of headers and payloads, respectively. Both of these +components contain features relevant to consuming and producing non-trivial +messages, but also document their extensibility APIs, which will be of interest +to advanced applications. + +Following those is a set of examples of using the fundamental parts of the APIs +covered in the preceding sections. + +The foregoing represent the modern (unicode friendly) API of the email package. +The remaining sections, starting with the :class:`~email.message.Message` +class, cover the legacy :data:`~email.policy.compat32` API that deals much more +directly with the details of how email messages are represented. The +:data:`~email.policy.compat32` API does *not* hide the details of the RFCs from +the application, but for applications that need to operate at that level, they +can be useful tools. This documentation is also relevant for applications that +are still using the :mod:`~email.policy.compat32` API for backward +compatibility reasons. + +.. versionchanged:: 3.6 + Docs reorganized and rewritten to promote the new + :class:`~email.message.EmailMessage`/:class:`~email.policy.EmailPolicy` + API. + +Contents of the :mod:`email` package documentation: + +.. toctree:: + + email.message.rst + email.parser.rst + email.generator.rst + email.policy.rst + + email.errors.rst + email.headerregistry.rst + email.contentmanager.rst + + email.examples.rst + +Legacy API: + +.. toctree:: + + email.compat32-message.rst + email.mime.rst + email.header.rst + email.charset.rst + email.encoders.rst + email.utils.rst + email.iterators.rst + + +.. seealso:: + + Module :mod:`smtplib` + SMTP (Simple Mail Transport Protocol) client + + Module :mod:`poplib` + POP (Post Office Protocol) client + + Module :mod:`imaplib` + IMAP (Internet Message Access Protocol) client + + Module :mod:`nntplib` + NNTP (Net News Transport Protocol) client + + Module :mod:`mailbox` + Tools for creating, reading, and managing collections of messages on disk + using a variety standard formats. + + Module :mod:`smtpd` + SMTP server framework (primarily useful for testing) diff --git a/cpython_2/environment/repo/Doc/library/email.utils.rst b/cpython_2/environment/repo/Doc/library/email.utils.rst new file mode 100644 index 0000000000000000000000000000000000000000..4d0e920eb0ad2951727b01891222351d9bea4f7a --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/email.utils.rst @@ -0,0 +1,218 @@ +:mod:`email.utils`: Miscellaneous utilities +------------------------------------------- + +.. module:: email.utils + :synopsis: Miscellaneous email package utilities. + +**Source code:** :source:`Lib/email/utils.py` + +-------------- + +There are a couple of useful utilities provided in the :mod:`email.utils` +module: + +.. function:: localtime(dt=None) + + Return local time as an aware datetime object. If called without + arguments, return current time. Otherwise *dt* argument should be a + :class:`~datetime.datetime` instance, and it is converted to the local time + zone according to the system time zone database. If *dt* is naive (that + is, ``dt.tzinfo`` is ``None``), it is assumed to be in local time. In this + case, a positive or zero value for *isdst* causes ``localtime`` to presume + initially that summer time (for example, Daylight Saving Time) is or is not + (respectively) in effect for the specified time. A negative value for + *isdst* causes the ``localtime`` to attempt to divine whether summer time + is in effect for the specified time. + + .. versionadded:: 3.3 + + +.. function:: make_msgid(idstring=None, domain=None) + + Returns a string suitable for an :rfc:`2822`\ -compliant + :mailheader:`Message-ID` header. Optional *idstring* if given, is a string + used to strengthen the uniqueness of the message id. Optional *domain* if + given provides the portion of the msgid after the '@'. The default is the + local hostname. It is not normally necessary to override this default, but + may be useful certain cases, such as a constructing distributed system that + uses a consistent domain name across multiple hosts. + + .. versionchanged:: 3.2 + Added the *domain* keyword. + + +The remaining functions are part of the legacy (``Compat32``) email API. There +is no need to directly use these with the new API, since the parsing and +formatting they provide is done automatically by the header parsing machinery +of the new API. + + +.. function:: quote(str) + + Return a new string with backslashes in *str* replaced by two backslashes, and + double quotes replaced by backslash-double quote. + + +.. function:: unquote(str) + + Return a new string which is an *unquoted* version of *str*. If *str* ends and + begins with double quotes, they are stripped off. Likewise if *str* ends and + begins with angle brackets, they are stripped off. + + +.. function:: parseaddr(address) + + Parse address -- which should be the value of some address-containing field such + as :mailheader:`To` or :mailheader:`Cc` -- into its constituent *realname* and + *email address* parts. Returns a tuple of that information, unless the parse + fails, in which case a 2-tuple of ``('', '')`` is returned. + + +.. function:: formataddr(pair, charset='utf-8') + + The inverse of :meth:`parseaddr`, this takes a 2-tuple of the form ``(realname, + email_address)`` and returns the string value suitable for a :mailheader:`To` or + :mailheader:`Cc` header. If the first element of *pair* is false, then the + second element is returned unmodified. + + Optional *charset* is the character set that will be used in the :rfc:`2047` + encoding of the ``realname`` if the ``realname`` contains non-ASCII + characters. Can be an instance of :class:`str` or a + :class:`~email.charset.Charset`. Defaults to ``utf-8``. + + .. versionchanged:: 3.3 + Added the *charset* option. + + +.. function:: getaddresses(fieldvalues) + + This method returns a list of 2-tuples of the form returned by ``parseaddr()``. + *fieldvalues* is a sequence of header field values as might be returned by + :meth:`Message.get_all `. Here's a simple + example that gets all the recipients of a message:: + + from email.utils import getaddresses + + tos = msg.get_all('to', []) + ccs = msg.get_all('cc', []) + resent_tos = msg.get_all('resent-to', []) + resent_ccs = msg.get_all('resent-cc', []) + all_recipients = getaddresses(tos + ccs + resent_tos + resent_ccs) + + +.. function:: parsedate(date) + + Attempts to parse a date according to the rules in :rfc:`2822`. however, some + mailers don't follow that format as specified, so :func:`parsedate` tries to + guess correctly in such cases. *date* is a string containing an :rfc:`2822` + date, such as ``"Mon, 20 Nov 1995 19:12:08 -0500"``. If it succeeds in parsing + the date, :func:`parsedate` returns a 9-tuple that can be passed directly to + :func:`time.mktime`; otherwise ``None`` will be returned. Note that indexes 6, + 7, and 8 of the result tuple are not usable. + + +.. function:: parsedate_tz(date) + + Performs the same function as :func:`parsedate`, but returns either ``None`` or + a 10-tuple; the first 9 elements make up a tuple that can be passed directly to + :func:`time.mktime`, and the tenth is the offset of the date's timezone from UTC + (which is the official term for Greenwich Mean Time) [#]_. If the input string + has no timezone, the last element of the tuple returned is ``0``, which represents + UTC. Note that indexes 6, 7, and 8 of the result tuple are not usable. + + +.. function:: parsedate_to_datetime(date) + + The inverse of :func:`format_datetime`. Performs the same function as + :func:`parsedate`, but on success returns a :mod:`~datetime.datetime`. If + the input date has a timezone of ``-0000``, the ``datetime`` will be a naive + ``datetime``, and if the date is conforming to the RFCs it will represent a + time in UTC but with no indication of the actual source timezone of the + message the date comes from. If the input date has any other valid timezone + offset, the ``datetime`` will be an aware ``datetime`` with the + corresponding a :class:`~datetime.timezone` :class:`~datetime.tzinfo`. + + .. versionadded:: 3.3 + + +.. function:: mktime_tz(tuple) + + Turn a 10-tuple as returned by :func:`parsedate_tz` into a UTC + timestamp (seconds since the Epoch). If the timezone item in the + tuple is ``None``, assume local time. + + +.. function:: formatdate(timeval=None, localtime=False, usegmt=False) + + Returns a date string as per :rfc:`2822`, e.g.:: + + Fri, 09 Nov 2001 01:08:47 -0000 + + Optional *timeval* if given is a floating point time value as accepted by + :func:`time.gmtime` and :func:`time.localtime`, otherwise the current time is + used. + + Optional *localtime* is a flag that when ``True``, interprets *timeval*, and + returns a date relative to the local timezone instead of UTC, properly taking + daylight savings time into account. The default is ``False`` meaning UTC is + used. + + Optional *usegmt* is a flag that when ``True``, outputs a date string with the + timezone as an ascii string ``GMT``, rather than a numeric ``-0000``. This is + needed for some protocols (such as HTTP). This only applies when *localtime* is + ``False``. The default is ``False``. + + +.. function:: format_datetime(dt, usegmt=False) + + Like ``formatdate``, but the input is a :mod:`datetime` instance. If it is + a naive datetime, it is assumed to be "UTC with no information about the + source timezone", and the conventional ``-0000`` is used for the timezone. + If it is an aware ``datetime``, then the numeric timezone offset is used. + If it is an aware timezone with offset zero, then *usegmt* may be set to + ``True``, in which case the string ``GMT`` is used instead of the numeric + timezone offset. This provides a way to generate standards conformant HTTP + date headers. + + .. versionadded:: 3.3 + + +.. function:: decode_rfc2231(s) + + Decode the string *s* according to :rfc:`2231`. + + +.. function:: encode_rfc2231(s, charset=None, language=None) + + Encode the string *s* according to :rfc:`2231`. Optional *charset* and + *language*, if given is the character set name and language name to use. If + neither is given, *s* is returned as-is. If *charset* is given but *language* + is not, the string is encoded using the empty string for *language*. + + +.. function:: collapse_rfc2231_value(value, errors='replace', fallback_charset='us-ascii') + + When a header parameter is encoded in :rfc:`2231` format, + :meth:`Message.get_param ` may return a + 3-tuple containing the character set, + language, and value. :func:`collapse_rfc2231_value` turns this into a unicode + string. Optional *errors* is passed to the *errors* argument of :class:`str`'s + :func:`~str.encode` method; it defaults to ``'replace'``. Optional + *fallback_charset* specifies the character set to use if the one in the + :rfc:`2231` header is not known by Python; it defaults to ``'us-ascii'``. + + For convenience, if the *value* passed to :func:`collapse_rfc2231_value` is not + a tuple, it should be a string and it is returned unquoted. + + +.. function:: decode_params(params) + + Decode parameters list according to :rfc:`2231`. *params* is a sequence of + 2-tuples containing elements of the form ``(content-type, string-value)``. + + +.. rubric:: Footnotes + +.. [#] Note that the sign of the timezone offset is the opposite of the sign of the + ``time.timezone`` variable for the same timezone; the latter variable follows + the POSIX standard while this module follows :rfc:`2822`. diff --git a/cpython_2/environment/repo/Doc/library/ensurepip.rst b/cpython_2/environment/repo/Doc/library/ensurepip.rst new file mode 100644 index 0000000000000000000000000000000000000000..a5221250c40486af667f398d22db9d830452baab --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/ensurepip.rst @@ -0,0 +1,135 @@ +:mod:`ensurepip` --- Bootstrapping the ``pip`` installer +======================================================== + +.. module:: ensurepip + :synopsis: Bootstrapping the "pip" installer into an existing Python + installation or virtual environment. + +.. versionadded:: 3.4 + +-------------- + +The :mod:`ensurepip` package provides support for bootstrapping the ``pip`` +installer into an existing Python installation or virtual environment. This +bootstrapping approach reflects the fact that ``pip`` is an independent +project with its own release cycle, and the latest available stable version +is bundled with maintenance and feature releases of the CPython reference +interpreter. + +In most cases, end users of Python shouldn't need to invoke this module +directly (as ``pip`` should be bootstrapped by default), but it may be +needed if installing ``pip`` was skipped when installing Python (or +when creating a virtual environment) or after explicitly uninstalling +``pip``. + +.. note:: + + This module *does not* access the internet. All of the components + needed to bootstrap ``pip`` are included as internal parts of the + package. + +.. seealso:: + + :ref:`installing-index` + The end user guide for installing Python packages + + :pep:`453`: Explicit bootstrapping of pip in Python installations + The original rationale and specification for this module. + + +Command line interface +---------------------- + +The command line interface is invoked using the interpreter's ``-m`` switch. + +The simplest possible invocation is:: + + python -m ensurepip + +This invocation will install ``pip`` if it is not already installed, +but otherwise does nothing. To ensure the installed version of ``pip`` +is at least as recent as the one bundled with ``ensurepip``, pass the +``--upgrade`` option:: + + python -m ensurepip --upgrade + +By default, ``pip`` is installed into the current virtual environment +(if one is active) or into the system site packages (if there is no +active virtual environment). The installation location can be controlled +through two additional command line options: + +* ``--root ``: Installs ``pip`` relative to the given root directory + rather than the root of the currently active virtual environment (if any) + or the default root for the current Python installation. +* ``--user``: Installs ``pip`` into the user site packages directory rather + than globally for the current Python installation (this option is not + permitted inside an active virtual environment). + +By default, the scripts ``pipX`` and ``pipX.Y`` will be installed (where +X.Y stands for the version of Python used to invoke ``ensurepip``). The +scripts installed can be controlled through two additional command line +options: + +* ``--altinstall``: if an alternate installation is requested, the ``pipX`` + script will *not* be installed. + +* ``--default-pip``: if a "default pip" installation is requested, the + ``pip`` script will be installed in addition to the two regular scripts. + +Providing both of the script selection options will trigger an exception. + + +Module API +---------- + +:mod:`ensurepip` exposes two functions for programmatic use: + +.. function:: version() + + Returns a string specifying the bundled version of pip that will be + installed when bootstrapping an environment. + +.. function:: bootstrap(root=None, upgrade=False, user=False, \ + altinstall=False, default_pip=False, \ + verbosity=0) + + Bootstraps ``pip`` into the current or designated environment. + + *root* specifies an alternative root directory to install relative to. + If *root* is ``None``, then installation uses the default install location + for the current environment. + + *upgrade* indicates whether or not to upgrade an existing installation + of an earlier version of ``pip`` to the bundled version. + + *user* indicates whether to use the user scheme rather than installing + globally. + + By default, the scripts ``pipX`` and ``pipX.Y`` will be installed (where + X.Y stands for the current version of Python). + + If *altinstall* is set, then ``pipX`` will *not* be installed. + + If *default_pip* is set, then ``pip`` will be installed in addition to + the two regular scripts. + + Setting both *altinstall* and *default_pip* will trigger + :exc:`ValueError`. + + *verbosity* controls the level of output to :data:`sys.stdout` from the + bootstrapping operation. + + .. audit-event:: ensurepip.bootstrap root ensurepip.bootstrap + + .. note:: + + The bootstrapping process has side effects on both ``sys.path`` and + ``os.environ``. Invoking the command line interface in a subprocess + instead allows these side effects to be avoided. + + .. note:: + + The bootstrapping process may install additional modules required by + ``pip``, but other software should not assume those dependencies will + always be present by default (as the dependencies may be removed in a + future version of ``pip``). diff --git a/cpython_2/environment/repo/Doc/library/enum.rst b/cpython_2/environment/repo/Doc/library/enum.rst new file mode 100644 index 0000000000000000000000000000000000000000..4b4f5eb1944cc572c3399894b52486f9456d203f --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/enum.rst @@ -0,0 +1,1160 @@ +:mod:`enum` --- Support for enumerations +======================================== + +.. module:: enum + :synopsis: Implementation of an enumeration class. + +.. moduleauthor:: Ethan Furman +.. sectionauthor:: Barry Warsaw +.. sectionauthor:: Eli Bendersky +.. sectionauthor:: Ethan Furman + +.. versionadded:: 3.4 + +**Source code:** :source:`Lib/enum.py` + +---------------- + +An enumeration is a set of symbolic names (members) bound to unique, +constant values. Within an enumeration, the members can be compared +by identity, and the enumeration itself can be iterated over. + + +Module Contents +--------------- + +This module defines four enumeration classes that can be used to define unique +sets of names and values: :class:`Enum`, :class:`IntEnum`, :class:`Flag`, and +:class:`IntFlag`. It also defines one decorator, :func:`unique`, and one +helper, :class:`auto`. + +.. class:: Enum + + Base class for creating enumerated constants. See section + `Functional API`_ for an alternate construction syntax. + +.. class:: IntEnum + + Base class for creating enumerated constants that are also + subclasses of :class:`int`. + +.. class:: IntFlag + + Base class for creating enumerated constants that can be combined using + the bitwise operators without losing their :class:`IntFlag` membership. + :class:`IntFlag` members are also subclasses of :class:`int`. + +.. class:: Flag + + Base class for creating enumerated constants that can be combined using + the bitwise operations without losing their :class:`Flag` membership. + +.. function:: unique + + Enum class decorator that ensures only one name is bound to any one value. + +.. class:: auto + + Instances are replaced with an appropriate value for Enum members. By default, the initial value starts at 1. + +.. versionadded:: 3.6 ``Flag``, ``IntFlag``, ``auto`` + + +Creating an Enum +---------------- + +Enumerations are created using the :keyword:`class` syntax, which makes them +easy to read and write. An alternative creation method is described in +`Functional API`_. To define an enumeration, subclass :class:`Enum` as +follows:: + + >>> from enum import Enum + >>> class Color(Enum): + ... RED = 1 + ... GREEN = 2 + ... BLUE = 3 + ... + +.. note:: Enum member values + + Member values can be anything: :class:`int`, :class:`str`, etc.. If + the exact value is unimportant you may use :class:`auto` instances and an + appropriate value will be chosen for you. Care must be taken if you mix + :class:`auto` with other values. + +.. note:: Nomenclature + + - The class :class:`Color` is an *enumeration* (or *enum*) + - The attributes :attr:`Color.RED`, :attr:`Color.GREEN`, etc., are + *enumeration members* (or *enum members*) and are functionally constants. + - The enum members have *names* and *values* (the name of + :attr:`Color.RED` is ``RED``, the value of :attr:`Color.BLUE` is + ``3``, etc.) + +.. note:: + + Even though we use the :keyword:`class` syntax to create Enums, Enums + are not normal Python classes. See `How are Enums different?`_ for + more details. + +Enumeration members have human readable string representations:: + + >>> print(Color.RED) + Color.RED + +...while their ``repr`` has more information:: + + >>> print(repr(Color.RED)) + + +The *type* of an enumeration member is the enumeration it belongs to:: + + >>> type(Color.RED) + + >>> isinstance(Color.GREEN, Color) + True + >>> + +Enum members also have a property that contains just their item name:: + + >>> print(Color.RED.name) + RED + +Enumerations support iteration, in definition order:: + + >>> class Shake(Enum): + ... VANILLA = 7 + ... CHOCOLATE = 4 + ... COOKIES = 9 + ... MINT = 3 + ... + >>> for shake in Shake: + ... print(shake) + ... + Shake.VANILLA + Shake.CHOCOLATE + Shake.COOKIES + Shake.MINT + +Enumeration members are hashable, so they can be used in dictionaries and sets:: + + >>> apples = {} + >>> apples[Color.RED] = 'red delicious' + >>> apples[Color.GREEN] = 'granny smith' + >>> apples == {Color.RED: 'red delicious', Color.GREEN: 'granny smith'} + True + + +Programmatic access to enumeration members and their attributes +--------------------------------------------------------------- + +Sometimes it's useful to access members in enumerations programmatically (i.e. +situations where ``Color.RED`` won't do because the exact color is not known +at program-writing time). ``Enum`` allows such access:: + + >>> Color(1) + + >>> Color(3) + + +If you want to access enum members by *name*, use item access:: + + >>> Color['RED'] + + >>> Color['GREEN'] + + +If you have an enum member and need its :attr:`name` or :attr:`value`:: + + >>> member = Color.RED + >>> member.name + 'RED' + >>> member.value + 1 + + +Duplicating enum members and values +----------------------------------- + +Having two enum members with the same name is invalid:: + + >>> class Shape(Enum): + ... SQUARE = 2 + ... SQUARE = 3 + ... + Traceback (most recent call last): + ... + TypeError: Attempted to reuse key: 'SQUARE' + +However, two enum members are allowed to have the same value. Given two members +A and B with the same value (and A defined first), B is an alias to A. By-value +lookup of the value of A and B will return A. By-name lookup of B will also +return A:: + + >>> class Shape(Enum): + ... SQUARE = 2 + ... DIAMOND = 1 + ... CIRCLE = 3 + ... ALIAS_FOR_SQUARE = 2 + ... + >>> Shape.SQUARE + + >>> Shape.ALIAS_FOR_SQUARE + + >>> Shape(2) + + +.. note:: + + Attempting to create a member with the same name as an already + defined attribute (another member, a method, etc.) or attempting to create + an attribute with the same name as a member is not allowed. + + +Ensuring unique enumeration values +---------------------------------- + +By default, enumerations allow multiple names as aliases for the same value. +When this behavior isn't desired, the following decorator can be used to +ensure each value is used only once in the enumeration: + +.. decorator:: unique + +A :keyword:`class` decorator specifically for enumerations. It searches an +enumeration's :attr:`__members__` gathering any aliases it finds; if any are +found :exc:`ValueError` is raised with the details:: + + >>> from enum import Enum, unique + >>> @unique + ... class Mistake(Enum): + ... ONE = 1 + ... TWO = 2 + ... THREE = 3 + ... FOUR = 3 + ... + Traceback (most recent call last): + ... + ValueError: duplicate values found in : FOUR -> THREE + + +Using automatic values +---------------------- + +If the exact value is unimportant you can use :class:`auto`:: + + >>> from enum import Enum, auto + >>> class Color(Enum): + ... RED = auto() + ... BLUE = auto() + ... GREEN = auto() + ... + >>> list(Color) + [, , ] + +The values are chosen by :func:`_generate_next_value_`, which can be +overridden:: + + >>> class AutoName(Enum): + ... def _generate_next_value_(name, start, count, last_values): + ... return name + ... + >>> class Ordinal(AutoName): + ... NORTH = auto() + ... SOUTH = auto() + ... EAST = auto() + ... WEST = auto() + ... + >>> list(Ordinal) + [, , , ] + +.. note:: + + The goal of the default :meth:`_generate_next_value_` methods is to provide + the next :class:`int` in sequence with the last :class:`int` provided, but + the way it does this is an implementation detail and may change. + +.. note:: + + The :meth:`_generate_next_value_` method must be defined before any members. + +Iteration +--------- + +Iterating over the members of an enum does not provide the aliases:: + + >>> list(Shape) + [, , ] + +The special attribute ``__members__`` is a read-only ordered mapping of names +to members. It includes all names defined in the enumeration, including the +aliases:: + + >>> for name, member in Shape.__members__.items(): + ... name, member + ... + ('SQUARE', ) + ('DIAMOND', ) + ('CIRCLE', ) + ('ALIAS_FOR_SQUARE', ) + +The ``__members__`` attribute can be used for detailed programmatic access to +the enumeration members. For example, finding all the aliases:: + + >>> [name for name, member in Shape.__members__.items() if member.name != name] + ['ALIAS_FOR_SQUARE'] + + +Comparisons +----------- + +Enumeration members are compared by identity:: + + >>> Color.RED is Color.RED + True + >>> Color.RED is Color.BLUE + False + >>> Color.RED is not Color.BLUE + True + +Ordered comparisons between enumeration values are *not* supported. Enum +members are not integers (but see `IntEnum`_ below):: + + >>> Color.RED < Color.BLUE + Traceback (most recent call last): + File "", line 1, in + TypeError: '<' not supported between instances of 'Color' and 'Color' + +Equality comparisons are defined though:: + + >>> Color.BLUE == Color.RED + False + >>> Color.BLUE != Color.RED + True + >>> Color.BLUE == Color.BLUE + True + +Comparisons against non-enumeration values will always compare not equal +(again, :class:`IntEnum` was explicitly designed to behave differently, see +below):: + + >>> Color.BLUE == 2 + False + + +Allowed members and attributes of enumerations +---------------------------------------------- + +The examples above use integers for enumeration values. Using integers is +short and handy (and provided by default by the `Functional API`_), but not +strictly enforced. In the vast majority of use-cases, one doesn't care what +the actual value of an enumeration is. But if the value *is* important, +enumerations can have arbitrary values. + +Enumerations are Python classes, and can have methods and special methods as +usual. If we have this enumeration:: + + >>> class Mood(Enum): + ... FUNKY = 1 + ... HAPPY = 3 + ... + ... def describe(self): + ... # self is the member here + ... return self.name, self.value + ... + ... def __str__(self): + ... return 'my custom str! {0}'.format(self.value) + ... + ... @classmethod + ... def favorite_mood(cls): + ... # cls here is the enumeration + ... return cls.HAPPY + ... + +Then:: + + >>> Mood.favorite_mood() + + >>> Mood.HAPPY.describe() + ('HAPPY', 3) + >>> str(Mood.FUNKY) + 'my custom str! 1' + +The rules for what is allowed are as follows: names that start and end with +a single underscore are reserved by enum and cannot be used; all other +attributes defined within an enumeration will become members of this +enumeration, with the exception of special methods (:meth:`__str__`, +:meth:`__add__`, etc.), descriptors (methods are also descriptors), and +variable names listed in :attr:`_ignore_`. + +Note: if your enumeration defines :meth:`__new__` and/or :meth:`__init__` then +any value(s) given to the enum member will be passed into those methods. +See `Planet`_ for an example. + + +Restricted Enum subclassing +--------------------------- + +A new :class:`Enum` class must have one base Enum class, up to one concrete +data type, and as many :class:`object`-based mixin classes as needed. The +order of these base classes is:: + + class EnumName([mix-in, ...,] [data-type,] base-enum): + pass + +Also, subclassing an enumeration is allowed only if the enumeration does not define +any members. So this is forbidden:: + + >>> class MoreColor(Color): + ... PINK = 17 + ... + Traceback (most recent call last): + ... + TypeError: Cannot extend enumerations + +But this is allowed:: + + >>> class Foo(Enum): + ... def some_behavior(self): + ... pass + ... + >>> class Bar(Foo): + ... HAPPY = 1 + ... SAD = 2 + ... + +Allowing subclassing of enums that define members would lead to a violation of +some important invariants of types and instances. On the other hand, it makes +sense to allow sharing some common behavior between a group of enumerations. +(See `OrderedEnum`_ for an example.) + + +Pickling +-------- + +Enumerations can be pickled and unpickled:: + + >>> from test.test_enum import Fruit + >>> from pickle import dumps, loads + >>> Fruit.TOMATO is loads(dumps(Fruit.TOMATO)) + True + +The usual restrictions for pickling apply: picklable enums must be defined in +the top level of a module, since unpickling requires them to be importable +from that module. + +.. note:: + + With pickle protocol version 4 it is possible to easily pickle enums + nested in other classes. + +It is possible to modify how Enum members are pickled/unpickled by defining +:meth:`__reduce_ex__` in the enumeration class. + + +Functional API +-------------- + +The :class:`Enum` class is callable, providing the following functional API:: + + >>> Animal = Enum('Animal', 'ANT BEE CAT DOG') + >>> Animal + + >>> Animal.ANT + + >>> Animal.ANT.value + 1 + >>> list(Animal) + [, , , ] + +The semantics of this API resemble :class:`~collections.namedtuple`. The first +argument of the call to :class:`Enum` is the name of the enumeration. + +The second argument is the *source* of enumeration member names. It can be a +whitespace-separated string of names, a sequence of names, a sequence of +2-tuples with key/value pairs, or a mapping (e.g. dictionary) of names to +values. The last two options enable assigning arbitrary values to +enumerations; the others auto-assign increasing integers starting with 1 (use +the ``start`` parameter to specify a different starting value). A +new class derived from :class:`Enum` is returned. In other words, the above +assignment to :class:`Animal` is equivalent to:: + + >>> class Animal(Enum): + ... ANT = 1 + ... BEE = 2 + ... CAT = 3 + ... DOG = 4 + ... + +The reason for defaulting to ``1`` as the starting number and not ``0`` is +that ``0`` is ``False`` in a boolean sense, but enum members all evaluate +to ``True``. + +Pickling enums created with the functional API can be tricky as frame stack +implementation details are used to try and figure out which module the +enumeration is being created in (e.g. it will fail if you use a utility +function in separate module, and also may not work on IronPython or Jython). +The solution is to specify the module name explicitly as follows:: + + >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', module=__name__) + +.. warning:: + + If ``module`` is not supplied, and Enum cannot determine what it is, + the new Enum members will not be unpicklable; to keep errors closer to + the source, pickling will be disabled. + +The new pickle protocol 4 also, in some circumstances, relies on +:attr:`~definition.__qualname__` being set to the location where pickle will be able +to find the class. For example, if the class was made available in class +SomeData in the global scope:: + + >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', qualname='SomeData.Animal') + +The complete signature is:: + + Enum(value='NewEnumName', names=<...>, *, module='...', qualname='...', type=, start=1) + +:value: What the new Enum class will record as its name. + +:names: The Enum members. This can be a whitespace or comma separated string + (values will start at 1 unless otherwise specified):: + + 'RED GREEN BLUE' | 'RED,GREEN,BLUE' | 'RED, GREEN, BLUE' + + or an iterator of names:: + + ['RED', 'GREEN', 'BLUE'] + + or an iterator of (name, value) pairs:: + + [('CYAN', 4), ('MAGENTA', 5), ('YELLOW', 6)] + + or a mapping:: + + {'CHARTREUSE': 7, 'SEA_GREEN': 11, 'ROSEMARY': 42} + +:module: name of module where new Enum class can be found. + +:qualname: where in module new Enum class can be found. + +:type: type to mix in to new Enum class. + +:start: number to start counting at if only names are passed in. + +.. versionchanged:: 3.5 + The *start* parameter was added. + + +Derived Enumerations +-------------------- + +IntEnum +^^^^^^^ + +The first variation of :class:`Enum` that is provided is also a subclass of +:class:`int`. Members of an :class:`IntEnum` can be compared to integers; +by extension, integer enumerations of different types can also be compared +to each other:: + + >>> from enum import IntEnum + >>> class Shape(IntEnum): + ... CIRCLE = 1 + ... SQUARE = 2 + ... + >>> class Request(IntEnum): + ... POST = 1 + ... GET = 2 + ... + >>> Shape == 1 + False + >>> Shape.CIRCLE == 1 + True + >>> Shape.CIRCLE == Request.POST + True + +However, they still can't be compared to standard :class:`Enum` enumerations:: + + >>> class Shape(IntEnum): + ... CIRCLE = 1 + ... SQUARE = 2 + ... + >>> class Color(Enum): + ... RED = 1 + ... GREEN = 2 + ... + >>> Shape.CIRCLE == Color.RED + False + +:class:`IntEnum` values behave like integers in other ways you'd expect:: + + >>> int(Shape.CIRCLE) + 1 + >>> ['a', 'b', 'c'][Shape.CIRCLE] + 'b' + >>> [i for i in range(Shape.SQUARE)] + [0, 1] + + +IntFlag +^^^^^^^ + +The next variation of :class:`Enum` provided, :class:`IntFlag`, is also based +on :class:`int`. The difference being :class:`IntFlag` members can be combined +using the bitwise operators (&, \|, ^, ~) and the result is still an +:class:`IntFlag` member. However, as the name implies, :class:`IntFlag` +members also subclass :class:`int` and can be used wherever an :class:`int` is +used. Any operation on an :class:`IntFlag` member besides the bit-wise +operations will lose the :class:`IntFlag` membership. + +.. versionadded:: 3.6 + +Sample :class:`IntFlag` class:: + + >>> from enum import IntFlag + >>> class Perm(IntFlag): + ... R = 4 + ... W = 2 + ... X = 1 + ... + >>> Perm.R | Perm.W + + >>> Perm.R + Perm.W + 6 + >>> RW = Perm.R | Perm.W + >>> Perm.R in RW + True + +It is also possible to name the combinations:: + + >>> class Perm(IntFlag): + ... R = 4 + ... W = 2 + ... X = 1 + ... RWX = 7 + >>> Perm.RWX + + >>> ~Perm.RWX + + +Another important difference between :class:`IntFlag` and :class:`Enum` is that +if no flags are set (the value is 0), its boolean evaluation is :data:`False`:: + + >>> Perm.R & Perm.X + + >>> bool(Perm.R & Perm.X) + False + +Because :class:`IntFlag` members are also subclasses of :class:`int` they can +be combined with them:: + + >>> Perm.X | 8 + + + +Flag +^^^^ + +The last variation is :class:`Flag`. Like :class:`IntFlag`, :class:`Flag` +members can be combined using the bitwise operators (&, \|, ^, ~). Unlike +:class:`IntFlag`, they cannot be combined with, nor compared against, any +other :class:`Flag` enumeration, nor :class:`int`. While it is possible to +specify the values directly it is recommended to use :class:`auto` as the +value and let :class:`Flag` select an appropriate value. + +.. versionadded:: 3.6 + +Like :class:`IntFlag`, if a combination of :class:`Flag` members results in no +flags being set, the boolean evaluation is :data:`False`:: + + >>> from enum import Flag, auto + >>> class Color(Flag): + ... RED = auto() + ... BLUE = auto() + ... GREEN = auto() + ... + >>> Color.RED & Color.GREEN + + >>> bool(Color.RED & Color.GREEN) + False + +Individual flags should have values that are powers of two (1, 2, 4, 8, ...), +while combinations of flags won't:: + + >>> class Color(Flag): + ... RED = auto() + ... BLUE = auto() + ... GREEN = auto() + ... WHITE = RED | BLUE | GREEN + ... + >>> Color.WHITE + + +Giving a name to the "no flags set" condition does not change its boolean +value:: + + >>> class Color(Flag): + ... BLACK = 0 + ... RED = auto() + ... BLUE = auto() + ... GREEN = auto() + ... + >>> Color.BLACK + + >>> bool(Color.BLACK) + False + +.. note:: + + For the majority of new code, :class:`Enum` and :class:`Flag` are strongly + recommended, since :class:`IntEnum` and :class:`IntFlag` break some + semantic promises of an enumeration (by being comparable to integers, and + thus by transitivity to other unrelated enumerations). :class:`IntEnum` + and :class:`IntFlag` should be used only in cases where :class:`Enum` and + :class:`Flag` will not do; for example, when integer constants are replaced + with enumerations, or for interoperability with other systems. + + +Others +^^^^^^ + +While :class:`IntEnum` is part of the :mod:`enum` module, it would be very +simple to implement independently:: + + class IntEnum(int, Enum): + pass + +This demonstrates how similar derived enumerations can be defined; for example +a :class:`StrEnum` that mixes in :class:`str` instead of :class:`int`. + +Some rules: + +1. When subclassing :class:`Enum`, mix-in types must appear before + :class:`Enum` itself in the sequence of bases, as in the :class:`IntEnum` + example above. +2. While :class:`Enum` can have members of any type, once you mix in an + additional type, all the members must have values of that type, e.g. + :class:`int` above. This restriction does not apply to mix-ins which only + add methods and don't specify another type. +3. When another data type is mixed in, the :attr:`value` attribute is *not the + same* as the enum member itself, although it is equivalent and will compare + equal. +4. %-style formatting: `%s` and `%r` call the :class:`Enum` class's + :meth:`__str__` and :meth:`__repr__` respectively; other codes (such as + `%i` or `%h` for IntEnum) treat the enum member as its mixed-in type. +5. :ref:`Formatted string literals `, :meth:`str.format`, + and :func:`format` will use the mixed-in type's :meth:`__format__` + unless :meth:`__str__` or :meth:`__format__` is overridden in the subclass, + in which case the overridden methods or :class:`Enum` methods will be used. + Use the !s and !r format codes to force usage of the :class:`Enum` class's + :meth:`__str__` and :meth:`__repr__` methods. + +When to use :meth:`__new__` vs. :meth:`__init__` +------------------------------------------------ + +:meth:`__new__` must be used whenever you want to customize the actual value of +the :class:`Enum` member. Any other modifications may go in either +:meth:`__new__` or :meth:`__init__`, with :meth:`__init__` being preferred. + +For example, if you want to pass several items to the constructor, but only +want one of them to be the value:: + + >>> class Coordinate(bytes, Enum): + ... """ + ... Coordinate with binary codes that can be indexed by the int code. + ... """ + ... def __new__(cls, value, label, unit): + ... obj = bytes.__new__(cls, [value]) + ... obj._value_ = value + ... obj.label = label + ... obj.unit = unit + ... return obj + ... PX = (0, 'P.X', 'km') + ... PY = (1, 'P.Y', 'km') + ... VX = (2, 'V.X', 'km/s') + ... VY = (3, 'V.Y', 'km/s') + ... + + >>> print(Coordinate['PY']) + Coordinate.PY + + >>> print(Coordinate(3)) + Coordinate.VY + +Interesting examples +-------------------- + +While :class:`Enum`, :class:`IntEnum`, :class:`IntFlag`, and :class:`Flag` are +expected to cover the majority of use-cases, they cannot cover them all. Here +are recipes for some different types of enumerations that can be used directly, +or as examples for creating one's own. + + +Omitting values +^^^^^^^^^^^^^^^ + +In many use-cases one doesn't care what the actual value of an enumeration +is. There are several ways to define this type of simple enumeration: + +- use instances of :class:`auto` for the value +- use instances of :class:`object` as the value +- use a descriptive string as the value +- use a tuple as the value and a custom :meth:`__new__` to replace the + tuple with an :class:`int` value + +Using any of these methods signifies to the user that these values are not +important, and also enables one to add, remove, or reorder members without +having to renumber the remaining members. + +Whichever method you choose, you should provide a :meth:`repr` that also hides +the (unimportant) value:: + + >>> class NoValue(Enum): + ... def __repr__(self): + ... return '<%s.%s>' % (self.__class__.__name__, self.name) + ... + + +Using :class:`auto` +""""""""""""""""""" + +Using :class:`auto` would look like:: + + >>> class Color(NoValue): + ... RED = auto() + ... BLUE = auto() + ... GREEN = auto() + ... + >>> Color.GREEN + + + +Using :class:`object` +""""""""""""""""""""" + +Using :class:`object` would look like:: + + >>> class Color(NoValue): + ... RED = object() + ... GREEN = object() + ... BLUE = object() + ... + >>> Color.GREEN + + + +Using a descriptive string +"""""""""""""""""""""""""" + +Using a string as the value would look like:: + + >>> class Color(NoValue): + ... RED = 'stop' + ... GREEN = 'go' + ... BLUE = 'too fast!' + ... + >>> Color.GREEN + + >>> Color.GREEN.value + 'go' + + +Using a custom :meth:`__new__` +"""""""""""""""""""""""""""""" + +Using an auto-numbering :meth:`__new__` would look like:: + + >>> class AutoNumber(NoValue): + ... def __new__(cls): + ... value = len(cls.__members__) + 1 + ... obj = object.__new__(cls) + ... obj._value_ = value + ... return obj + ... + >>> class Color(AutoNumber): + ... RED = () + ... GREEN = () + ... BLUE = () + ... + >>> Color.GREEN + + >>> Color.GREEN.value + 2 + + +.. note:: + + The :meth:`__new__` method, if defined, is used during creation of the Enum + members; it is then replaced by Enum's :meth:`__new__` which is used after + class creation for lookup of existing members. + + +OrderedEnum +^^^^^^^^^^^ + +An ordered enumeration that is not based on :class:`IntEnum` and so maintains +the normal :class:`Enum` invariants (such as not being comparable to other +enumerations):: + + >>> class OrderedEnum(Enum): + ... def __ge__(self, other): + ... if self.__class__ is other.__class__: + ... return self.value >= other.value + ... return NotImplemented + ... def __gt__(self, other): + ... if self.__class__ is other.__class__: + ... return self.value > other.value + ... return NotImplemented + ... def __le__(self, other): + ... if self.__class__ is other.__class__: + ... return self.value <= other.value + ... return NotImplemented + ... def __lt__(self, other): + ... if self.__class__ is other.__class__: + ... return self.value < other.value + ... return NotImplemented + ... + >>> class Grade(OrderedEnum): + ... A = 5 + ... B = 4 + ... C = 3 + ... D = 2 + ... F = 1 + ... + >>> Grade.C < Grade.A + True + + +DuplicateFreeEnum +^^^^^^^^^^^^^^^^^ + +Raises an error if a duplicate member name is found instead of creating an +alias:: + + >>> class DuplicateFreeEnum(Enum): + ... def __init__(self, *args): + ... cls = self.__class__ + ... if any(self.value == e.value for e in cls): + ... a = self.name + ... e = cls(self.value).name + ... raise ValueError( + ... "aliases not allowed in DuplicateFreeEnum: %r --> %r" + ... % (a, e)) + ... + >>> class Color(DuplicateFreeEnum): + ... RED = 1 + ... GREEN = 2 + ... BLUE = 3 + ... GRENE = 2 + ... + Traceback (most recent call last): + ... + ValueError: aliases not allowed in DuplicateFreeEnum: 'GRENE' --> 'GREEN' + +.. note:: + + This is a useful example for subclassing Enum to add or change other + behaviors as well as disallowing aliases. If the only desired change is + disallowing aliases, the :func:`unique` decorator can be used instead. + + +Planet +^^^^^^ + +If :meth:`__new__` or :meth:`__init__` is defined the value of the enum member +will be passed to those methods:: + + >>> class Planet(Enum): + ... MERCURY = (3.303e+23, 2.4397e6) + ... VENUS = (4.869e+24, 6.0518e6) + ... EARTH = (5.976e+24, 6.37814e6) + ... MARS = (6.421e+23, 3.3972e6) + ... JUPITER = (1.9e+27, 7.1492e7) + ... SATURN = (5.688e+26, 6.0268e7) + ... URANUS = (8.686e+25, 2.5559e7) + ... NEPTUNE = (1.024e+26, 2.4746e7) + ... def __init__(self, mass, radius): + ... self.mass = mass # in kilograms + ... self.radius = radius # in meters + ... @property + ... def surface_gravity(self): + ... # universal gravitational constant (m3 kg-1 s-2) + ... G = 6.67300E-11 + ... return G * self.mass / (self.radius * self.radius) + ... + >>> Planet.EARTH.value + (5.976e+24, 6378140.0) + >>> Planet.EARTH.surface_gravity + 9.802652743337129 + + +TimePeriod +^^^^^^^^^^ + +An example to show the :attr:`_ignore_` attribute in use:: + + >>> from datetime import timedelta + >>> class Period(timedelta, Enum): + ... "different lengths of time" + ... _ignore_ = 'Period i' + ... Period = vars() + ... for i in range(367): + ... Period['day_%d' % i] = i + ... + >>> list(Period)[:2] + [, ] + >>> list(Period)[-2:] + [, ] + + +How are Enums different? +------------------------ + +Enums have a custom metaclass that affects many aspects of both derived Enum +classes and their instances (members). + + +Enum Classes +^^^^^^^^^^^^ + +The :class:`EnumMeta` metaclass is responsible for providing the +:meth:`__contains__`, :meth:`__dir__`, :meth:`__iter__` and other methods that +allow one to do things with an :class:`Enum` class that fail on a typical +class, such as `list(Color)` or `some_enum_var in Color`. :class:`EnumMeta` is +responsible for ensuring that various other methods on the final :class:`Enum` +class are correct (such as :meth:`__new__`, :meth:`__getnewargs__`, +:meth:`__str__` and :meth:`__repr__`). + + +Enum Members (aka instances) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The most interesting thing about Enum members is that they are singletons. +:class:`EnumMeta` creates them all while it is creating the :class:`Enum` +class itself, and then puts a custom :meth:`__new__` in place to ensure +that no new ones are ever instantiated by returning only the existing +member instances. + + +Finer Points +^^^^^^^^^^^^ + +Supported ``__dunder__`` names +"""""""""""""""""""""""""""""" + +:attr:`__members__` is a read-only ordered mapping of ``member_name``:``member`` +items. It is only available on the class. + +:meth:`__new__`, if specified, must create and return the enum members; it is +also a very good idea to set the member's :attr:`_value_` appropriately. Once +all the members are created it is no longer used. + + +Supported ``_sunder_`` names +"""""""""""""""""""""""""""" + +- ``_name_`` -- name of the member +- ``_value_`` -- value of the member; can be set / modified in ``__new__`` + +- ``_missing_`` -- a lookup function used when a value is not found; may be + overridden +- ``_ignore_`` -- a list of names, either as a :class:`list` or a :class:`str`, + that will not be transformed into members, and will be removed from the final + class +- ``_order_`` -- used in Python 2/3 code to ensure member order is consistent + (class attribute, removed during class creation) +- ``_generate_next_value_`` -- used by the `Functional API`_ and by + :class:`auto` to get an appropriate value for an enum member; may be + overridden + +.. versionadded:: 3.6 ``_missing_``, ``_order_``, ``_generate_next_value_`` +.. versionadded:: 3.7 ``_ignore_`` + +To help keep Python 2 / Python 3 code in sync an :attr:`_order_` attribute can +be provided. It will be checked against the actual order of the enumeration +and raise an error if the two do not match:: + + >>> class Color(Enum): + ... _order_ = 'RED GREEN BLUE' + ... RED = 1 + ... BLUE = 3 + ... GREEN = 2 + ... + Traceback (most recent call last): + ... + TypeError: member order does not match _order_ + +.. note:: + + In Python 2 code the :attr:`_order_` attribute is necessary as definition + order is lost before it can be recorded. + +``Enum`` member type +"""""""""""""""""""" + +:class:`Enum` members are instances of their :class:`Enum` class, and are +normally accessed as ``EnumClass.member``. Under certain circumstances they +can also be accessed as ``EnumClass.member.member``, but you should never do +this as that lookup may fail or, worse, return something besides the +:class:`Enum` member you are looking for (this is another good reason to use +all-uppercase names for members):: + + >>> class FieldTypes(Enum): + ... name = 0 + ... value = 1 + ... size = 2 + ... + >>> FieldTypes.value.size + + >>> FieldTypes.size.value + 2 + +.. versionchanged:: 3.5 + + +Boolean value of ``Enum`` classes and members +""""""""""""""""""""""""""""""""""""""""""""" + +:class:`Enum` members that are mixed with non-:class:`Enum` types (such as +:class:`int`, :class:`str`, etc.) are evaluated according to the mixed-in +type's rules; otherwise, all members evaluate as :data:`True`. To make your +own Enum's boolean evaluation depend on the member's value add the following to +your class:: + + def __bool__(self): + return bool(self.value) + +:class:`Enum` classes always evaluate as :data:`True`. + + +``Enum`` classes with methods +""""""""""""""""""""""""""""" + +If you give your :class:`Enum` subclass extra methods, like the `Planet`_ +class above, those methods will show up in a :func:`dir` of the member, +but not of the class:: + + >>> dir(Planet) + ['EARTH', 'JUPITER', 'MARS', 'MERCURY', 'NEPTUNE', 'SATURN', 'URANUS', 'VENUS', '__class__', '__doc__', '__members__', '__module__'] + >>> dir(Planet.EARTH) + ['__class__', '__doc__', '__module__', 'name', 'surface_gravity', 'value'] + + +Combining members of ``Flag`` +""""""""""""""""""""""""""""" + +If a combination of Flag members is not named, the :func:`repr` will include +all named flags and all named combinations of flags that are in the value:: + + >>> class Color(Flag): + ... RED = auto() + ... GREEN = auto() + ... BLUE = auto() + ... MAGENTA = RED | BLUE + ... YELLOW = RED | GREEN + ... CYAN = GREEN | BLUE + ... + >>> Color(3) # named combination + + >>> Color(7) # not named combination + + diff --git a/cpython_2/environment/repo/Doc/library/errno.rst b/cpython_2/environment/repo/Doc/library/errno.rst new file mode 100644 index 0000000000000000000000000000000000000000..1cbd51c582c0cf0340a989e34fb0c4cbec9bd77e --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/errno.rst @@ -0,0 +1,639 @@ +:mod:`errno` --- Standard errno system symbols +============================================== + +.. module:: errno + :synopsis: Standard errno system symbols. + +---------------- + +This module makes available standard ``errno`` system symbols. The value of each +symbol is the corresponding integer value. The names and descriptions are +borrowed from :file:`linux/include/errno.h`, which should be pretty +all-inclusive. + + +.. data:: errorcode + + Dictionary providing a mapping from the errno value to the string name in the + underlying system. For instance, ``errno.errorcode[errno.EPERM]`` maps to + ``'EPERM'``. + +To translate a numeric error code to an error message, use :func:`os.strerror`. + +Of the following list, symbols that are not used on the current platform are not +defined by the module. The specific list of defined symbols is available as +``errno.errorcode.keys()``. Symbols available can include: + + +.. data:: EPERM + + Operation not permitted + + +.. data:: ENOENT + + No such file or directory + + +.. data:: ESRCH + + No such process + + +.. data:: EINTR + + Interrupted system call. + + .. seealso:: + This error is mapped to the exception :exc:`InterruptedError`. + + +.. data:: EIO + + I/O error + + +.. data:: ENXIO + + No such device or address + + +.. data:: E2BIG + + Arg list too long + + +.. data:: ENOEXEC + + Exec format error + + +.. data:: EBADF + + Bad file number + + +.. data:: ECHILD + + No child processes + + +.. data:: EAGAIN + + Try again + + +.. data:: ENOMEM + + Out of memory + + +.. data:: EACCES + + Permission denied + + +.. data:: EFAULT + + Bad address + + +.. data:: ENOTBLK + + Block device required + + +.. data:: EBUSY + + Device or resource busy + + +.. data:: EEXIST + + File exists + + +.. data:: EXDEV + + Cross-device link + + +.. data:: ENODEV + + No such device + + +.. data:: ENOTDIR + + Not a directory + + +.. data:: EISDIR + + Is a directory + + +.. data:: EINVAL + + Invalid argument + + +.. data:: ENFILE + + File table overflow + + +.. data:: EMFILE + + Too many open files + + +.. data:: ENOTTY + + Not a typewriter + + +.. data:: ETXTBSY + + Text file busy + + +.. data:: EFBIG + + File too large + + +.. data:: ENOSPC + + No space left on device + + +.. data:: ESPIPE + + Illegal seek + + +.. data:: EROFS + + Read-only file system + + +.. data:: EMLINK + + Too many links + + +.. data:: EPIPE + + Broken pipe + + +.. data:: EDOM + + Math argument out of domain of func + + +.. data:: ERANGE + + Math result not representable + + +.. data:: EDEADLK + + Resource deadlock would occur + + +.. data:: ENAMETOOLONG + + File name too long + + +.. data:: ENOLCK + + No record locks available + + +.. data:: ENOSYS + + Function not implemented + + +.. data:: ENOTEMPTY + + Directory not empty + + +.. data:: ELOOP + + Too many symbolic links encountered + + +.. data:: EWOULDBLOCK + + Operation would block + + +.. data:: ENOMSG + + No message of desired type + + +.. data:: EIDRM + + Identifier removed + + +.. data:: ECHRNG + + Channel number out of range + + +.. data:: EL2NSYNC + + Level 2 not synchronized + + +.. data:: EL3HLT + + Level 3 halted + + +.. data:: EL3RST + + Level 3 reset + + +.. data:: ELNRNG + + Link number out of range + + +.. data:: EUNATCH + + Protocol driver not attached + + +.. data:: ENOCSI + + No CSI structure available + + +.. data:: EL2HLT + + Level 2 halted + + +.. data:: EBADE + + Invalid exchange + + +.. data:: EBADR + + Invalid request descriptor + + +.. data:: EXFULL + + Exchange full + + +.. data:: ENOANO + + No anode + + +.. data:: EBADRQC + + Invalid request code + + +.. data:: EBADSLT + + Invalid slot + + +.. data:: EDEADLOCK + + File locking deadlock error + + +.. data:: EBFONT + + Bad font file format + + +.. data:: ENOSTR + + Device not a stream + + +.. data:: ENODATA + + No data available + + +.. data:: ETIME + + Timer expired + + +.. data:: ENOSR + + Out of streams resources + + +.. data:: ENONET + + Machine is not on the network + + +.. data:: ENOPKG + + Package not installed + + +.. data:: EREMOTE + + Object is remote + + +.. data:: ENOLINK + + Link has been severed + + +.. data:: EADV + + Advertise error + + +.. data:: ESRMNT + + Srmount error + + +.. data:: ECOMM + + Communication error on send + + +.. data:: EPROTO + + Protocol error + + +.. data:: EMULTIHOP + + Multihop attempted + + +.. data:: EDOTDOT + + RFS specific error + + +.. data:: EBADMSG + + Not a data message + + +.. data:: EOVERFLOW + + Value too large for defined data type + + +.. data:: ENOTUNIQ + + Name not unique on network + + +.. data:: EBADFD + + File descriptor in bad state + + +.. data:: EREMCHG + + Remote address changed + + +.. data:: ELIBACC + + Can not access a needed shared library + + +.. data:: ELIBBAD + + Accessing a corrupted shared library + + +.. data:: ELIBSCN + + .lib section in a.out corrupted + + +.. data:: ELIBMAX + + Attempting to link in too many shared libraries + + +.. data:: ELIBEXEC + + Cannot exec a shared library directly + + +.. data:: EILSEQ + + Illegal byte sequence + + +.. data:: ERESTART + + Interrupted system call should be restarted + + +.. data:: ESTRPIPE + + Streams pipe error + + +.. data:: EUSERS + + Too many users + + +.. data:: ENOTSOCK + + Socket operation on non-socket + + +.. data:: EDESTADDRREQ + + Destination address required + + +.. data:: EMSGSIZE + + Message too long + + +.. data:: EPROTOTYPE + + Protocol wrong type for socket + + +.. data:: ENOPROTOOPT + + Protocol not available + + +.. data:: EPROTONOSUPPORT + + Protocol not supported + + +.. data:: ESOCKTNOSUPPORT + + Socket type not supported + + +.. data:: EOPNOTSUPP + + Operation not supported on transport endpoint + + +.. data:: EPFNOSUPPORT + + Protocol family not supported + + +.. data:: EAFNOSUPPORT + + Address family not supported by protocol + + +.. data:: EADDRINUSE + + Address already in use + + +.. data:: EADDRNOTAVAIL + + Cannot assign requested address + + +.. data:: ENETDOWN + + Network is down + + +.. data:: ENETUNREACH + + Network is unreachable + + +.. data:: ENETRESET + + Network dropped connection because of reset + + +.. data:: ECONNABORTED + + Software caused connection abort + + +.. data:: ECONNRESET + + Connection reset by peer + + +.. data:: ENOBUFS + + No buffer space available + + +.. data:: EISCONN + + Transport endpoint is already connected + + +.. data:: ENOTCONN + + Transport endpoint is not connected + + +.. data:: ESHUTDOWN + + Cannot send after transport endpoint shutdown + + +.. data:: ETOOMANYREFS + + Too many references: cannot splice + + +.. data:: ETIMEDOUT + + Connection timed out + + +.. data:: ECONNREFUSED + + Connection refused + + +.. data:: EHOSTDOWN + + Host is down + + +.. data:: EHOSTUNREACH + + No route to host + + +.. data:: EALREADY + + Operation already in progress + + +.. data:: EINPROGRESS + + Operation now in progress + + +.. data:: ESTALE + + Stale NFS file handle + + +.. data:: EUCLEAN + + Structure needs cleaning + + +.. data:: ENOTNAM + + Not a XENIX named type file + + +.. data:: ENAVAIL + + No XENIX semaphores available + + +.. data:: EISNAM + + Is a named type file + + +.. data:: EREMOTEIO + + Remote I/O error + + +.. data:: EDQUOT + + Quota exceeded + diff --git a/cpython_2/environment/repo/Doc/library/exceptions.rst b/cpython_2/environment/repo/Doc/library/exceptions.rst new file mode 100644 index 0000000000000000000000000000000000000000..df2cda9d67ad153971e374db1eef138ffe8d44da --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/exceptions.rst @@ -0,0 +1,760 @@ +.. _bltin-exceptions: + +Built-in Exceptions +=================== + +.. index:: + statement: try + statement: except + +In Python, all exceptions must be instances of a class that derives from +:class:`BaseException`. In a :keyword:`try` statement with an :keyword:`except` +clause that mentions a particular class, that clause also handles any exception +classes derived from that class (but not exception classes from which *it* is +derived). Two exception classes that are not related via subclassing are never +equivalent, even if they have the same name. + +.. index:: statement: raise + +The built-in exceptions listed below can be generated by the interpreter or +built-in functions. Except where mentioned, they have an "associated value" +indicating the detailed cause of the error. This may be a string or a tuple of +several items of information (e.g., an error code and a string explaining the +code). The associated value is usually passed as arguments to the exception +class's constructor. + +User code can raise built-in exceptions. This can be used to test an exception +handler or to report an error condition "just like" the situation in which the +interpreter raises the same exception; but beware that there is nothing to +prevent user code from raising an inappropriate error. + +The built-in exception classes can be subclassed to define new exceptions; +programmers are encouraged to derive new exceptions from the :exc:`Exception` +class or one of its subclasses, and not from :exc:`BaseException`. More +information on defining exceptions is available in the Python Tutorial under +:ref:`tut-userexceptions`. + +When raising (or re-raising) an exception in an :keyword:`except` or +:keyword:`finally` clause +:attr:`__context__` is automatically set to the last exception caught; if the +new exception is not handled the traceback that is eventually displayed will +include the originating exception(s) and the final exception. + +When raising a new exception (rather than using a bare ``raise`` to re-raise +the exception currently being handled), the implicit exception context can be +supplemented with an explicit cause by using :keyword:`from` with +:keyword:`raise`:: + + raise new_exc from original_exc + +The expression following :keyword:`from` must be an exception or ``None``. It +will be set as :attr:`__cause__` on the raised exception. Setting +:attr:`__cause__` also implicitly sets the :attr:`__suppress_context__` +attribute to ``True``, so that using ``raise new_exc from None`` +effectively replaces the old exception with the new one for display +purposes (e.g. converting :exc:`KeyError` to :exc:`AttributeError`), while +leaving the old exception available in :attr:`__context__` for introspection +when debugging. + +The default traceback display code shows these chained exceptions in +addition to the traceback for the exception itself. An explicitly chained +exception in :attr:`__cause__` is always shown when present. An implicitly +chained exception in :attr:`__context__` is shown only if :attr:`__cause__` +is :const:`None` and :attr:`__suppress_context__` is false. + +In either case, the exception itself is always shown after any chained +exceptions so that the final line of the traceback always shows the last +exception that was raised. + + +Base classes +------------ + +The following exceptions are used mostly as base classes for other exceptions. + +.. exception:: BaseException + + The base class for all built-in exceptions. It is not meant to be directly + inherited by user-defined classes (for that, use :exc:`Exception`). If + :func:`str` is called on an instance of this class, the representation of + the argument(s) to the instance are returned, or the empty string when + there were no arguments. + + .. attribute:: args + + The tuple of arguments given to the exception constructor. Some built-in + exceptions (like :exc:`OSError`) expect a certain number of arguments and + assign a special meaning to the elements of this tuple, while others are + usually called only with a single string giving an error message. + + .. method:: with_traceback(tb) + + This method sets *tb* as the new traceback for the exception and returns + the exception object. It is usually used in exception handling code like + this:: + + try: + ... + except SomeException: + tb = sys.exc_info()[2] + raise OtherException(...).with_traceback(tb) + + +.. exception:: Exception + + All built-in, non-system-exiting exceptions are derived from this class. All + user-defined exceptions should also be derived from this class. + + +.. exception:: ArithmeticError + + The base class for those built-in exceptions that are raised for various + arithmetic errors: :exc:`OverflowError`, :exc:`ZeroDivisionError`, + :exc:`FloatingPointError`. + + +.. exception:: BufferError + + Raised when a :ref:`buffer ` related operation cannot be + performed. + + +.. exception:: LookupError + + The base class for the exceptions that are raised when a key or index used on + a mapping or sequence is invalid: :exc:`IndexError`, :exc:`KeyError`. This + can be raised directly by :func:`codecs.lookup`. + + +Concrete exceptions +------------------- + +The following exceptions are the exceptions that are usually raised. + +.. exception:: AssertionError + + .. index:: statement: assert + + Raised when an :keyword:`assert` statement fails. + + +.. exception:: AttributeError + + Raised when an attribute reference (see :ref:`attribute-references`) or + assignment fails. (When an object does not support attribute references or + attribute assignments at all, :exc:`TypeError` is raised.) + + +.. exception:: EOFError + + Raised when the :func:`input` function hits an end-of-file condition (EOF) + without reading any data. (N.B.: the :meth:`io.IOBase.read` and + :meth:`io.IOBase.readline` methods return an empty string when they hit EOF.) + + +.. exception:: FloatingPointError + + Not currently used. + + +.. exception:: GeneratorExit + + Raised when a :term:`generator` or :term:`coroutine` is closed; + see :meth:`generator.close` and :meth:`coroutine.close`. It + directly inherits from :exc:`BaseException` instead of :exc:`Exception` since + it is technically not an error. + + +.. exception:: ImportError + + Raised when the :keyword:`import` statement has troubles trying to + load a module. Also raised when the "from list" in ``from ... import`` + has a name that cannot be found. + + The :attr:`name` and :attr:`path` attributes can be set using keyword-only + arguments to the constructor. When set they represent the name of the module + that was attempted to be imported and the path to any file which triggered + the exception, respectively. + + .. versionchanged:: 3.3 + Added the :attr:`name` and :attr:`path` attributes. + +.. exception:: ModuleNotFoundError + + A subclass of :exc:`ImportError` which is raised by :keyword:`import` + when a module could not be located. It is also raised when ``None`` + is found in :data:`sys.modules`. + + .. versionadded:: 3.6 + + +.. exception:: IndexError + + Raised when a sequence subscript is out of range. (Slice indices are + silently truncated to fall in the allowed range; if an index is not an + integer, :exc:`TypeError` is raised.) + + .. XXX xref to sequences + + +.. exception:: KeyError + + Raised when a mapping (dictionary) key is not found in the set of existing keys. + + .. XXX xref to mapping objects? + + +.. exception:: KeyboardInterrupt + + Raised when the user hits the interrupt key (normally :kbd:`Control-C` or + :kbd:`Delete`). During execution, a check for interrupts is made + regularly. The exception inherits from :exc:`BaseException` so as to not be + accidentally caught by code that catches :exc:`Exception` and thus prevent + the interpreter from exiting. + + +.. exception:: MemoryError + + Raised when an operation runs out of memory but the situation may still be + rescued (by deleting some objects). The associated value is a string indicating + what kind of (internal) operation ran out of memory. Note that because of the + underlying memory management architecture (C's :c:func:`malloc` function), the + interpreter may not always be able to completely recover from this situation; it + nevertheless raises an exception so that a stack traceback can be printed, in + case a run-away program was the cause. + + +.. exception:: NameError + + Raised when a local or global name is not found. This applies only to + unqualified names. The associated value is an error message that includes the + name that could not be found. + + +.. exception:: NotImplementedError + + This exception is derived from :exc:`RuntimeError`. In user defined base + classes, abstract methods should raise this exception when they require + derived classes to override the method, or while the class is being + developed to indicate that the real implementation still needs to be added. + + .. note:: + + It should not be used to indicate that an operator or method is not + meant to be supported at all -- in that case either leave the operator / + method undefined or, if a subclass, set it to :data:`None`. + + .. note:: + + ``NotImplementedError`` and ``NotImplemented`` are not interchangeable, + even though they have similar names and purposes. See + :data:`NotImplemented` for details on when to use it. + +.. exception:: OSError([arg]) + OSError(errno, strerror[, filename[, winerror[, filename2]]]) + + .. index:: module: errno + + This exception is raised when a system function returns a system-related + error, including I/O failures such as "file not found" or "disk full" + (not for illegal argument types or other incidental errors). + + The second form of the constructor sets the corresponding attributes, + described below. The attributes default to :const:`None` if not + specified. For backwards compatibility, if three arguments are passed, + the :attr:`~BaseException.args` attribute contains only a 2-tuple + of the first two constructor arguments. + + The constructor often actually returns a subclass of :exc:`OSError`, as + described in `OS exceptions`_ below. The particular subclass depends on + the final :attr:`.errno` value. This behaviour only occurs when + constructing :exc:`OSError` directly or via an alias, and is not + inherited when subclassing. + + .. attribute:: errno + + A numeric error code from the C variable :c:data:`errno`. + + .. attribute:: winerror + + Under Windows, this gives you the native + Windows error code. The :attr:`.errno` attribute is then an approximate + translation, in POSIX terms, of that native error code. + + Under Windows, if the *winerror* constructor argument is an integer, + the :attr:`.errno` attribute is determined from the Windows error code, + and the *errno* argument is ignored. On other platforms, the + *winerror* argument is ignored, and the :attr:`winerror` attribute + does not exist. + + .. attribute:: strerror + + The corresponding error message, as provided by + the operating system. It is formatted by the C + functions :c:func:`perror` under POSIX, and :c:func:`FormatMessage` + under Windows. + + .. attribute:: filename + filename2 + + For exceptions that involve a file system path (such as :func:`open` or + :func:`os.unlink`), :attr:`filename` is the file name passed to the function. + For functions that involve two file system paths (such as + :func:`os.rename`), :attr:`filename2` corresponds to the second + file name passed to the function. + + + .. versionchanged:: 3.3 + :exc:`EnvironmentError`, :exc:`IOError`, :exc:`WindowsError`, + :exc:`socket.error`, :exc:`select.error` and + :exc:`mmap.error` have been merged into :exc:`OSError`, and the + constructor may return a subclass. + + .. versionchanged:: 3.4 + The :attr:`filename` attribute is now the original file name passed to + the function, instead of the name encoded to or decoded from the + filesystem encoding. Also, the *filename2* constructor argument and + attribute was added. + + +.. exception:: OverflowError + + Raised when the result of an arithmetic operation is too large to be + represented. This cannot occur for integers (which would rather raise + :exc:`MemoryError` than give up). However, for historical reasons, + OverflowError is sometimes raised for integers that are outside a required + range. Because of the lack of standardization of floating point exception + handling in C, most floating point operations are not checked. + + +.. exception:: RecursionError + + This exception is derived from :exc:`RuntimeError`. It is raised when the + interpreter detects that the maximum recursion depth (see + :func:`sys.getrecursionlimit`) is exceeded. + + .. versionadded:: 3.5 + Previously, a plain :exc:`RuntimeError` was raised. + + +.. exception:: ReferenceError + + This exception is raised when a weak reference proxy, created by the + :func:`weakref.proxy` function, is used to access an attribute of the referent + after it has been garbage collected. For more information on weak references, + see the :mod:`weakref` module. + + +.. exception:: RuntimeError + + Raised when an error is detected that doesn't fall in any of the other + categories. The associated value is a string indicating what precisely went + wrong. + + +.. exception:: StopIteration + + Raised by built-in function :func:`next` and an :term:`iterator`\'s + :meth:`~iterator.__next__` method to signal that there are no further + items produced by the iterator. + + The exception object has a single attribute :attr:`value`, which is + given as an argument when constructing the exception, and defaults + to :const:`None`. + + When a :term:`generator` or :term:`coroutine` function + returns, a new :exc:`StopIteration` instance is + raised, and the value returned by the function is used as the + :attr:`value` parameter to the constructor of the exception. + + If a generator code directly or indirectly raises :exc:`StopIteration`, + it is converted into a :exc:`RuntimeError` (retaining the + :exc:`StopIteration` as the new exception's cause). + + .. versionchanged:: 3.3 + Added ``value`` attribute and the ability for generator functions to + use it to return a value. + + .. versionchanged:: 3.5 + Introduced the RuntimeError transformation via + ``from __future__ import generator_stop``, see :pep:`479`. + + .. versionchanged:: 3.7 + Enable :pep:`479` for all code by default: a :exc:`StopIteration` + error raised in a generator is transformed into a :exc:`RuntimeError`. + +.. exception:: StopAsyncIteration + + Must be raised by :meth:`__anext__` method of an + :term:`asynchronous iterator` object to stop the iteration. + + .. versionadded:: 3.5 + +.. exception:: SyntaxError + + Raised when the parser encounters a syntax error. This may occur in an + :keyword:`import` statement, in a call to the built-in functions :func:`exec` + or :func:`eval`, or when reading the initial script or standard input + (also interactively). + + Instances of this class have attributes :attr:`filename`, :attr:`lineno`, + :attr:`offset` and :attr:`text` for easier access to the details. :func:`str` + of the exception instance returns only the message. + + +.. exception:: IndentationError + + Base class for syntax errors related to incorrect indentation. This is a + subclass of :exc:`SyntaxError`. + + +.. exception:: TabError + + Raised when indentation contains an inconsistent use of tabs and spaces. + This is a subclass of :exc:`IndentationError`. + + +.. exception:: SystemError + + Raised when the interpreter finds an internal error, but the situation does not + look so serious to cause it to abandon all hope. The associated value is a + string indicating what went wrong (in low-level terms). + + You should report this to the author or maintainer of your Python interpreter. + Be sure to report the version of the Python interpreter (``sys.version``; it is + also printed at the start of an interactive Python session), the exact error + message (the exception's associated value) and if possible the source of the + program that triggered the error. + + +.. exception:: SystemExit + + This exception is raised by the :func:`sys.exit` function. It inherits from + :exc:`BaseException` instead of :exc:`Exception` so that it is not accidentally + caught by code that catches :exc:`Exception`. This allows the exception to + properly propagate up and cause the interpreter to exit. When it is not + handled, the Python interpreter exits; no stack traceback is printed. The + constructor accepts the same optional argument passed to :func:`sys.exit`. + If the value is an integer, it specifies the system exit status (passed to + C's :c:func:`exit` function); if it is ``None``, the exit status is zero; if + it has another type (such as a string), the object's value is printed and + the exit status is one. + + A call to :func:`sys.exit` is translated into an exception so that clean-up + handlers (:keyword:`finally` clauses of :keyword:`try` statements) can be + executed, and so that a debugger can execute a script without running the risk + of losing control. The :func:`os._exit` function can be used if it is + absolutely positively necessary to exit immediately (for example, in the child + process after a call to :func:`os.fork`). + + .. attribute:: code + + The exit status or error message that is passed to the constructor. + (Defaults to ``None``.) + + +.. exception:: TypeError + + Raised when an operation or function is applied to an object of inappropriate + type. The associated value is a string giving details about the type mismatch. + + This exception may be raised by user code to indicate that an attempted + operation on an object is not supported, and is not meant to be. If an object + is meant to support a given operation but has not yet provided an + implementation, :exc:`NotImplementedError` is the proper exception to raise. + + Passing arguments of the wrong type (e.g. passing a :class:`list` when an + :class:`int` is expected) should result in a :exc:`TypeError`, but passing + arguments with the wrong value (e.g. a number outside expected boundaries) + should result in a :exc:`ValueError`. + +.. exception:: UnboundLocalError + + Raised when a reference is made to a local variable in a function or method, but + no value has been bound to that variable. This is a subclass of + :exc:`NameError`. + + +.. exception:: UnicodeError + + Raised when a Unicode-related encoding or decoding error occurs. It is a + subclass of :exc:`ValueError`. + + :exc:`UnicodeError` has attributes that describe the encoding or decoding + error. For example, ``err.object[err.start:err.end]`` gives the particular + invalid input that the codec failed on. + + .. attribute:: encoding + + The name of the encoding that raised the error. + + .. attribute:: reason + + A string describing the specific codec error. + + .. attribute:: object + + The object the codec was attempting to encode or decode. + + .. attribute:: start + + The first index of invalid data in :attr:`object`. + + .. attribute:: end + + The index after the last invalid data in :attr:`object`. + + +.. exception:: UnicodeEncodeError + + Raised when a Unicode-related error occurs during encoding. It is a subclass of + :exc:`UnicodeError`. + + +.. exception:: UnicodeDecodeError + + Raised when a Unicode-related error occurs during decoding. It is a subclass of + :exc:`UnicodeError`. + + +.. exception:: UnicodeTranslateError + + Raised when a Unicode-related error occurs during translating. It is a subclass + of :exc:`UnicodeError`. + + +.. exception:: ValueError + + Raised when an operation or function receives an argument that has the + right type but an inappropriate value, and the situation is not described by a + more precise exception such as :exc:`IndexError`. + + +.. exception:: ZeroDivisionError + + Raised when the second argument of a division or modulo operation is zero. The + associated value is a string indicating the type of the operands and the + operation. + + +The following exceptions are kept for compatibility with previous versions; +starting from Python 3.3, they are aliases of :exc:`OSError`. + +.. exception:: EnvironmentError + +.. exception:: IOError + +.. exception:: WindowsError + + Only available on Windows. + + +OS exceptions +^^^^^^^^^^^^^ + +The following exceptions are subclasses of :exc:`OSError`, they get raised +depending on the system error code. + +.. exception:: BlockingIOError + + Raised when an operation would block on an object (e.g. socket) set + for non-blocking operation. + Corresponds to :c:data:`errno` ``EAGAIN``, ``EALREADY``, + ``EWOULDBLOCK`` and ``EINPROGRESS``. + + In addition to those of :exc:`OSError`, :exc:`BlockingIOError` can have + one more attribute: + + .. attribute:: characters_written + + An integer containing the number of characters written to the stream + before it blocked. This attribute is available when using the + buffered I/O classes from the :mod:`io` module. + +.. exception:: ChildProcessError + + Raised when an operation on a child process failed. + Corresponds to :c:data:`errno` ``ECHILD``. + +.. exception:: ConnectionError + + A base class for connection-related issues. + + Subclasses are :exc:`BrokenPipeError`, :exc:`ConnectionAbortedError`, + :exc:`ConnectionRefusedError` and :exc:`ConnectionResetError`. + +.. exception:: BrokenPipeError + + A subclass of :exc:`ConnectionError`, raised when trying to write on a + pipe while the other end has been closed, or trying to write on a socket + which has been shutdown for writing. + Corresponds to :c:data:`errno` ``EPIPE`` and ``ESHUTDOWN``. + +.. exception:: ConnectionAbortedError + + A subclass of :exc:`ConnectionError`, raised when a connection attempt + is aborted by the peer. + Corresponds to :c:data:`errno` ``ECONNABORTED``. + +.. exception:: ConnectionRefusedError + + A subclass of :exc:`ConnectionError`, raised when a connection attempt + is refused by the peer. + Corresponds to :c:data:`errno` ``ECONNREFUSED``. + +.. exception:: ConnectionResetError + + A subclass of :exc:`ConnectionError`, raised when a connection is + reset by the peer. + Corresponds to :c:data:`errno` ``ECONNRESET``. + +.. exception:: FileExistsError + + Raised when trying to create a file or directory which already exists. + Corresponds to :c:data:`errno` ``EEXIST``. + +.. exception:: FileNotFoundError + + Raised when a file or directory is requested but doesn't exist. + Corresponds to :c:data:`errno` ``ENOENT``. + +.. exception:: InterruptedError + + Raised when a system call is interrupted by an incoming signal. + Corresponds to :c:data:`errno` :py:data:`~errno.EINTR`. + + .. versionchanged:: 3.5 + Python now retries system calls when a syscall is interrupted by a + signal, except if the signal handler raises an exception (see :pep:`475` + for the rationale), instead of raising :exc:`InterruptedError`. + +.. exception:: IsADirectoryError + + Raised when a file operation (such as :func:`os.remove`) is requested + on a directory. + Corresponds to :c:data:`errno` ``EISDIR``. + +.. exception:: NotADirectoryError + + Raised when a directory operation (such as :func:`os.listdir`) is requested + on something which is not a directory. + Corresponds to :c:data:`errno` ``ENOTDIR``. + +.. exception:: PermissionError + + Raised when trying to run an operation without the adequate access + rights - for example filesystem permissions. + Corresponds to :c:data:`errno` ``EACCES`` and ``EPERM``. + +.. exception:: ProcessLookupError + + Raised when a given process doesn't exist. + Corresponds to :c:data:`errno` ``ESRCH``. + +.. exception:: TimeoutError + + Raised when a system function timed out at the system level. + Corresponds to :c:data:`errno` ``ETIMEDOUT``. + +.. versionadded:: 3.3 + All the above :exc:`OSError` subclasses were added. + + +.. seealso:: + + :pep:`3151` - Reworking the OS and IO exception hierarchy + + +.. _warning-categories-as-exceptions: + +Warnings +-------- + +The following exceptions are used as warning categories; see the +:ref:`warning-categories` documentation for more details. + +.. exception:: Warning + + Base class for warning categories. + + +.. exception:: UserWarning + + Base class for warnings generated by user code. + + +.. exception:: DeprecationWarning + + Base class for warnings about deprecated features when those warnings are + intended for other Python developers. + + Ignored by the default warning filters, except in the ``__main__`` module + (:pep:`565`). Enabling the :ref:`Python Development Mode ` shows + this warning. + + +.. exception:: PendingDeprecationWarning + + Base class for warnings about features which are obsolete and + expected to be deprecated in the future, but are not deprecated + at the moment. + + This class is rarely used as emitting a warning about a possible + upcoming deprecation is unusual, and :exc:`DeprecationWarning` + is preferred for already active deprecations. + + Ignored by the default warning filters. Enabling the :ref:`Python + Development Mode ` shows this warning. + + +.. exception:: SyntaxWarning + + Base class for warnings about dubious syntax. + + +.. exception:: RuntimeWarning + + Base class for warnings about dubious runtime behavior. + + +.. exception:: FutureWarning + + Base class for warnings about deprecated features when those warnings are + intended for end users of applications that are written in Python. + + +.. exception:: ImportWarning + + Base class for warnings about probable mistakes in module imports. + + Ignored by the default warning filters. Enabling the :ref:`Python + Development Mode ` shows this warning. + + +.. exception:: UnicodeWarning + + Base class for warnings related to Unicode. + + +.. exception:: BytesWarning + + Base class for warnings related to :class:`bytes` and :class:`bytearray`. + + +.. exception:: ResourceWarning + + Base class for warnings related to resource usage. + + Ignored by the default warning filters. Enabling the :ref:`Python + Development Mode ` shows this warning. + + .. versionadded:: 3.2 + + + +Exception hierarchy +------------------- + +The class hierarchy for built-in exceptions is: + +.. literalinclude:: ../../Lib/test/exception_hierarchy.txt diff --git a/cpython_2/environment/repo/Doc/library/faulthandler.rst b/cpython_2/environment/repo/Doc/library/faulthandler.rst new file mode 100644 index 0000000000000000000000000000000000000000..59274c1dd7ec354a8b0094e71fcd281c1fa63173 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/faulthandler.rst @@ -0,0 +1,177 @@ +:mod:`faulthandler` --- Dump the Python traceback +================================================= + +.. module:: faulthandler + :synopsis: Dump the Python traceback. + +.. versionadded:: 3.3 + +---------------- + +This module contains functions to dump Python tracebacks explicitly, on a fault, +after a timeout, or on a user signal. Call :func:`faulthandler.enable` to +install fault handlers for the :const:`SIGSEGV`, :const:`SIGFPE`, +:const:`SIGABRT`, :const:`SIGBUS`, and :const:`SIGILL` signals. You can also +enable them at startup by setting the :envvar:`PYTHONFAULTHANDLER` environment +variable or by using the :option:`-X` ``faulthandler`` command line option. + +The fault handler is compatible with system fault handlers like Apport or the +Windows fault handler. The module uses an alternative stack for signal handlers +if the :c:func:`sigaltstack` function is available. This allows it to dump the +traceback even on a stack overflow. + +The fault handler is called on catastrophic cases and therefore can only use +signal-safe functions (e.g. it cannot allocate memory on the heap). Because of +this limitation traceback dumping is minimal compared to normal Python +tracebacks: + +* Only ASCII is supported. The ``backslashreplace`` error handler is used on + encoding. +* Each string is limited to 500 characters. +* Only the filename, the function name and the line number are + displayed. (no source code) +* It is limited to 100 frames and 100 threads. +* The order is reversed: the most recent call is shown first. + +By default, the Python traceback is written to :data:`sys.stderr`. To see +tracebacks, applications must be run in the terminal. A log file can +alternatively be passed to :func:`faulthandler.enable`. + +The module is implemented in C, so tracebacks can be dumped on a crash or when +Python is deadlocked. + +The :ref:`Python Development Mode ` calls :func:`faulthandler.enable` +at Python startup. + + +Dumping the traceback +--------------------- + +.. function:: dump_traceback(file=sys.stderr, all_threads=True) + + Dump the tracebacks of all threads into *file*. If *all_threads* is + ``False``, dump only the current thread. + + .. versionchanged:: 3.5 + Added support for passing file descriptor to this function. + + +Fault handler state +------------------- + +.. function:: enable(file=sys.stderr, all_threads=True) + + Enable the fault handler: install handlers for the :const:`SIGSEGV`, + :const:`SIGFPE`, :const:`SIGABRT`, :const:`SIGBUS` and :const:`SIGILL` + signals to dump the Python traceback. If *all_threads* is ``True``, + produce tracebacks for every running thread. Otherwise, dump only the current + thread. + + The *file* must be kept open until the fault handler is disabled: see + :ref:`issue with file descriptors `. + + .. versionchanged:: 3.5 + Added support for passing file descriptor to this function. + + .. versionchanged:: 3.6 + On Windows, a handler for Windows exception is also installed. + +.. function:: disable() + + Disable the fault handler: uninstall the signal handlers installed by + :func:`enable`. + +.. function:: is_enabled() + + Check if the fault handler is enabled. + + +Dumping the tracebacks after a timeout +-------------------------------------- + +.. function:: dump_traceback_later(timeout, repeat=False, file=sys.stderr, exit=False) + + Dump the tracebacks of all threads, after a timeout of *timeout* seconds, or + every *timeout* seconds if *repeat* is ``True``. If *exit* is ``True``, call + :c:func:`_exit` with status=1 after dumping the tracebacks. (Note + :c:func:`_exit` exits the process immediately, which means it doesn't do any + cleanup like flushing file buffers.) If the function is called twice, the new + call replaces previous parameters and resets the timeout. The timer has a + sub-second resolution. + + The *file* must be kept open until the traceback is dumped or + :func:`cancel_dump_traceback_later` is called: see :ref:`issue with file + descriptors `. + + This function is implemented using a watchdog thread. + + .. versionchanged:: 3.7 + This function is now always available. + + .. versionchanged:: 3.5 + Added support for passing file descriptor to this function. + +.. function:: cancel_dump_traceback_later() + + Cancel the last call to :func:`dump_traceback_later`. + + +Dumping the traceback on a user signal +-------------------------------------- + +.. function:: register(signum, file=sys.stderr, all_threads=True, chain=False) + + Register a user signal: install a handler for the *signum* signal to dump + the traceback of all threads, or of the current thread if *all_threads* is + ``False``, into *file*. Call the previous handler if chain is ``True``. + + The *file* must be kept open until the signal is unregistered by + :func:`unregister`: see :ref:`issue with file descriptors `. + + Not available on Windows. + + .. versionchanged:: 3.5 + Added support for passing file descriptor to this function. + +.. function:: unregister(signum) + + Unregister a user signal: uninstall the handler of the *signum* signal + installed by :func:`register`. Return ``True`` if the signal was registered, + ``False`` otherwise. + + Not available on Windows. + + +.. _faulthandler-fd: + +Issue with file descriptors +--------------------------- + +:func:`enable`, :func:`dump_traceback_later` and :func:`register` keep the +file descriptor of their *file* argument. If the file is closed and its file +descriptor is reused by a new file, or if :func:`os.dup2` is used to replace +the file descriptor, the traceback will be written into a different file. Call +these functions again each time that the file is replaced. + + +Example +------- + +Example of a segmentation fault on Linux with and without enabling the fault +handler: + +.. code-block:: shell-session + + $ python3 -c "import ctypes; ctypes.string_at(0)" + Segmentation fault + + $ python3 -q -X faulthandler + >>> import ctypes + >>> ctypes.string_at(0) + Fatal Python error: Segmentation fault + + Current thread 0x00007fb899f39700 (most recent call first): + File "/home/python/cpython/Lib/ctypes/__init__.py", line 486 in string_at + File "", line 1 in + Segmentation fault + diff --git a/cpython_2/environment/repo/Doc/library/fcntl.rst b/cpython_2/environment/repo/Doc/library/fcntl.rst new file mode 100644 index 0000000000000000000000000000000000000000..07a15d27216e92ae497858e5b06e9dea7457987e --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/fcntl.rst @@ -0,0 +1,188 @@ +:mod:`fcntl` --- The ``fcntl`` and ``ioctl`` system calls +========================================================= + +.. module:: fcntl + :platform: Unix + :synopsis: The fcntl() and ioctl() system calls. + +.. sectionauthor:: Jaap Vermeulen + +.. index:: + pair: UNIX; file control + pair: UNIX; I/O control + +---------------- + +This module performs file control and I/O control on file descriptors. It is an +interface to the :c:func:`fcntl` and :c:func:`ioctl` Unix routines. For a +complete description of these calls, see :manpage:`fcntl(2)` and +:manpage:`ioctl(2)` Unix manual pages. + +All functions in this module take a file descriptor *fd* as their first +argument. This can be an integer file descriptor, such as returned by +``sys.stdin.fileno()``, or an :class:`io.IOBase` object, such as ``sys.stdin`` +itself, which provides a :meth:`~io.IOBase.fileno` that returns a genuine file +descriptor. + +.. versionchanged:: 3.3 + Operations in this module used to raise an :exc:`IOError` where they now + raise an :exc:`OSError`. + +.. versionchanged:: 3.8 + The fcntl module now contains ``F_ADD_SEALS``, ``F_GET_SEALS``, and + ``F_SEAL_*`` constants for sealing of :func:`os.memfd_create` file + descriptors. + +.. versionchanged:: 3.9 + On macOS, the fcntl module exposes the ``F_GETPATH`` constant, which obtains + the path of a file from a file descriptor. + On Linux(>=3.15), the fcntl module exposes the ``F_OFD_GETLK``, ``F_OFD_SETLK`` + and ``F_OFD_SETLKW`` constants, which working with open file description locks. + +The module defines the following functions: + + +.. function:: fcntl(fd, cmd, arg=0) + + Perform the operation *cmd* on file descriptor *fd* (file objects providing + a :meth:`~io.IOBase.fileno` method are accepted as well). The values used + for *cmd* are operating system dependent, and are available as constants + in the :mod:`fcntl` module, using the same names as used in the relevant C + header files. The argument *arg* can either be an integer value, or a + :class:`bytes` object. With an integer value, the return value of this + function is the integer return value of the C :c:func:`fcntl` call. When + the argument is bytes it represents a binary structure, e.g. created by + :func:`struct.pack`. The binary data is copied to a buffer whose address is + passed to the C :c:func:`fcntl` call. The return value after a successful + call is the contents of the buffer, converted to a :class:`bytes` object. + The length of the returned object will be the same as the length of the + *arg* argument. This is limited to 1024 bytes. If the information returned + in the buffer by the operating system is larger than 1024 bytes, this is + most likely to result in a segmentation violation or a more subtle data + corruption. + + If the :c:func:`fcntl` fails, an :exc:`OSError` is raised. + + .. audit-event:: fcntl.fcntl fd,cmd,arg fcntl.fcntl + + +.. function:: ioctl(fd, request, arg=0, mutate_flag=True) + + This function is identical to the :func:`~fcntl.fcntl` function, except + that the argument handling is even more complicated. + + The *request* parameter is limited to values that can fit in 32-bits. + Additional constants of interest for use as the *request* argument can be + found in the :mod:`termios` module, under the same names as used in + the relevant C header files. + + The parameter *arg* can be one of an integer, an object supporting the + read-only buffer interface (like :class:`bytes`) or an object supporting + the read-write buffer interface (like :class:`bytearray`). + + In all but the last case, behaviour is as for the :func:`~fcntl.fcntl` + function. + + If a mutable buffer is passed, then the behaviour is determined by the value of + the *mutate_flag* parameter. + + If it is false, the buffer's mutability is ignored and behaviour is as for a + read-only buffer, except that the 1024 byte limit mentioned above is avoided -- + so long as the buffer you pass is at least as long as what the operating system + wants to put there, things should work. + + If *mutate_flag* is true (the default), then the buffer is (in effect) passed + to the underlying :func:`ioctl` system call, the latter's return code is + passed back to the calling Python, and the buffer's new contents reflect the + action of the :func:`ioctl`. This is a slight simplification, because if the + supplied buffer is less than 1024 bytes long it is first copied into a static + buffer 1024 bytes long which is then passed to :func:`ioctl` and copied back + into the supplied buffer. + + If the :c:func:`ioctl` fails, an :exc:`OSError` exception is raised. + + An example:: + + >>> import array, fcntl, struct, termios, os + >>> os.getpgrp() + 13341 + >>> struct.unpack('h', fcntl.ioctl(0, termios.TIOCGPGRP, " "))[0] + 13341 + >>> buf = array.array('h', [0]) + >>> fcntl.ioctl(0, termios.TIOCGPGRP, buf, 1) + 0 + >>> buf + array('h', [13341]) + + .. audit-event:: fcntl.ioctl fd,request,arg fcntl.ioctl + + +.. function:: flock(fd, operation) + + Perform the lock operation *operation* on file descriptor *fd* (file objects providing + a :meth:`~io.IOBase.fileno` method are accepted as well). See the Unix manual + :manpage:`flock(2)` for details. (On some systems, this function is emulated + using :c:func:`fcntl`.) + + If the :c:func:`flock` fails, an :exc:`OSError` exception is raised. + + .. audit-event:: fcntl.flock fd,operation fcntl.flock + + +.. function:: lockf(fd, cmd, len=0, start=0, whence=0) + + This is essentially a wrapper around the :func:`~fcntl.fcntl` locking calls. + *fd* is the file descriptor (file objects providing a :meth:`~io.IOBase.fileno` + method are accepted as well) of the file to lock or unlock, and *cmd* + is one of the following values: + + * :const:`LOCK_UN` -- unlock + * :const:`LOCK_SH` -- acquire a shared lock + * :const:`LOCK_EX` -- acquire an exclusive lock + + When *cmd* is :const:`LOCK_SH` or :const:`LOCK_EX`, it can also be + bitwise ORed with :const:`LOCK_NB` to avoid blocking on lock acquisition. + If :const:`LOCK_NB` is used and the lock cannot be acquired, an + :exc:`OSError` will be raised and the exception will have an *errno* + attribute set to :const:`EACCES` or :const:`EAGAIN` (depending on the + operating system; for portability, check for both values). On at least some + systems, :const:`LOCK_EX` can only be used if the file descriptor refers to a + file opened for writing. + + *len* is the number of bytes to lock, *start* is the byte offset at + which the lock starts, relative to *whence*, and *whence* is as with + :func:`io.IOBase.seek`, specifically: + + * :const:`0` -- relative to the start of the file (:data:`os.SEEK_SET`) + * :const:`1` -- relative to the current buffer position (:data:`os.SEEK_CUR`) + * :const:`2` -- relative to the end of the file (:data:`os.SEEK_END`) + + The default for *start* is 0, which means to start at the beginning of the file. + The default for *len* is 0 which means to lock to the end of the file. The + default for *whence* is also 0. + + .. audit-event:: fcntl.lockf fd,cmd,len,start,whence fcntl.lockf + +Examples (all on a SVR4 compliant system):: + + import struct, fcntl, os + + f = open(...) + rv = fcntl.fcntl(f, fcntl.F_SETFL, os.O_NDELAY) + + lockdata = struct.pack('hhllhh', fcntl.F_WRLCK, 0, 0, 0, 0, 0) + rv = fcntl.fcntl(f, fcntl.F_SETLKW, lockdata) + +Note that in the first example the return value variable *rv* will hold an +integer value; in the second example it will hold a :class:`bytes` object. The +structure lay-out for the *lockdata* variable is system dependent --- therefore +using the :func:`flock` call may be better. + + +.. seealso:: + + Module :mod:`os` + If the locking flags :data:`~os.O_SHLOCK` and :data:`~os.O_EXLOCK` are + present in the :mod:`os` module (on BSD only), the :func:`os.open` + function provides an alternative to the :func:`lockf` and :func:`flock` + functions.