mirror of
https://github.com/python/cpython.git
synced 2026-06-04 16:50:51 +00:00
* Replace all documentation which says "See PEP 585" The following classes in the stdlib get simple updates: - array.array - asyncio.Future - asyncio.Task - collections.defaultdict - collections.deque - contextvars.ContextVar - contextvars.Token - ctypes.Array - os.DirEntry - re.Match - re.Pattern - string.templatelib.Interpolation - string.templatelib.Template - types.MappingProxyType - queue.SimpleQueue - weakref.ref The following classes are documented publicly as functions, and are therefore updated internally (`__class_getitem__.__doc__`) but not in the public docs: - functools.partial - itertools.chain The following builtin types have updates to `__class_getitem__.__doc__` but not to any documentation pages: - BaseExceptionGroup - coroutines (from generators) - dict - enumerate - frozendict - frozenset - generators (and async generators) - list - memoryview - set - slice - tuple Special cases: - union objects are now documented as "supporting class-level []", rather than anything to do with generics. - Templates might be generic over a single type (union, in theory) or over a TypeVarTuple. As this is not currently fully settled, it is marked with a comment and a mild hint that it is a single type is used (namely, "type" is singular rather than "types", plural) * Apply suggestions from code review Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com> * Correct several class getitem docs And expand the text for tuples. Co-authored-by: Jelle Zijlstra <906600+JelleZijlstra@users.noreply.github.com> * Add notes on generic typing of builtins * Fix typo in tuple.__class_getitem__ docstring * Typo fix: malformed refs Fix `generic` links which weren't marked as `:ref:`. * Strike unnecessary docs on generic-ness Co-authored-by: Jelle Zijlstra <906600+JelleZijlstra@users.noreply.github.com> * Apply suggestions from code review These are applied at both the originally indicated locations and in the corresponding docstring definitions. Co-authored-by: Alex Waygood <66076021+AlexWaygood@users.noreply.github.com> * Update Doc/library/re.rst Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com> * Update Objects/enumobject.c Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com> * Remove tuple generic doc in 'stdtypes' page This is covered in more detail in the cross-linked typing documentation. The other copy of this documentation -- in the docstring for `tuple.__class_getitem__` -- is left in place. * Fix whitespace around new doc of generics Per review, do not introduce or remove whitespace such that section breaks are altered by the introduction of doc on various generic types. In most cases, this is a removal of an extra line. In one case (Arrays), it is the reintroduction of a line. Additionally, two other minor fixes are included: - incorrect indent on 'defaultdicts' - make `mappingproxy.__class_getitem__.__doc__` consistent with other mapping type generic docs Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com> * Move placement of memoryview generic note Previous placement was at the end of the main docstring, which is consistent with other types but places it after a section on various methods (which makes it read somewhat inconsistently). Moving it up helps resolve. Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com> * Ensure sphinxdoc does not start sentences lowercase Lowercase class names at the start of sentences are marked out with the `class` role. In the case of `deque`, documentation already refers to these as `Deques`, so this form is preferred. * Apply suggestions from code review Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com> * Fix line endings and wrap more tightly Line endings fixed by pre-commit ; also re-wrapped the MappingProxyType text which was too long. * Use 'ContextVars' style in sphinx doc --------- Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com> Co-authored-by: Jelle Zijlstra <906600+JelleZijlstra@users.noreply.github.com> Co-authored-by: Alex Waygood <66076021+AlexWaygood@users.noreply.github.com> Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com> Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
311 lines
12 KiB
ReStructuredText
311 lines
12 KiB
ReStructuredText
: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, complex numbers. Arrays are mutable :term:`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`. 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 | |
|
|
+-----------+--------------------+-------------------+-----------------------+-------+
|
|
| ``'w'`` | Py_UCS4 | Unicode character | 4 | \(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 | |
|
|
+-----------+--------------------+-------------------+-----------------------+-------+
|
|
| ``'e'`` | _Float16 | float | 2 | \(2) |
|
|
+-----------+--------------------+-------------------+-----------------------+-------+
|
|
| ``'f'`` | float | float | 4 | |
|
|
+-----------+--------------------+-------------------+-----------------------+-------+
|
|
| ``'d'`` | double | float | 8 | |
|
|
+-----------+--------------------+-------------------+-----------------------+-------+
|
|
| ``'Zf'`` | float complex | complex | 8 | \(3) |
|
|
+-----------+--------------------+-------------------+-----------------------+-------+
|
|
| ``'Zd'`` | double complex | complex | 16 | \(3) |
|
|
+-----------+--------------------+-------------------+-----------------------+-------+
|
|
|
|
|
|
Notes:
|
|
|
|
(1)
|
|
.. versionadded:: 3.13
|
|
|
|
(2)
|
|
The IEEE 754 binary16 "half precision" type was introduced in the 2008
|
|
revision of the `IEEE 754 standard <ieee 754 standard_>`_.
|
|
This type is not widely supported by C compilers. It's available
|
|
as :c:expr:`_Float16` type, if the compiler supports the Annex H
|
|
of the C23 standard.
|
|
|
|
.. versionadded:: 3.15
|
|
|
|
(3)
|
|
Complex types (``Zf`` and ``Zd``) are available unconditionally,
|
|
regardless on support for complex types (the Annex G of the C11 standard)
|
|
by the C compiler.
|
|
As specified in the C11 standard, each complex type is represented by a
|
|
two-element C array containing, respectively, the real and imaginary parts.
|
|
|
|
.. versionadded:: 3.15
|
|
|
|
.. seealso::
|
|
|
|
The :ref:`ctypes <ctypes-fundamental-data-types>` and
|
|
:ref:`struct <type-codes>` modules,
|
|
as well as third-party modules like `numpy <https://numpy.org/doc/stable/reference/arrays.interface.html#object.__array_interface__>`__,
|
|
use similar -- but slightly different -- type codes.
|
|
|
|
|
|
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:`array.itemsize` attribute.
|
|
|
|
The module defines the following item:
|
|
|
|
|
|
.. data:: typecodes
|
|
|
|
A tuple with all available type codes.
|
|
|
|
.. versionchanged:: 3.15
|
|
The type changed from :class:`str` to :class:`tuple`.
|
|
|
|
|
|
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 :class:`bytes`
|
|
or :class:`bytearray` object, a Unicode string, or iterable over elements
|
|
of the appropriate type.
|
|
|
|
If given a :class:`bytes` or :class:`bytearray` object, the initializer
|
|
is passed to the new array's :meth:`frombytes` method;
|
|
if given a Unicode string, the initializer is passed to the
|
|
:meth:`fromunicode` method;
|
|
otherwise, the initializer's iterator is passed to the :meth:`extend` method
|
|
to add initial items to the array.
|
|
|
|
Array objects support the ordinary :ref:`mutable <typesseq-mutable>` :term:`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 <bytes-like object>` are supported.
|
|
|
|
Arrays are :ref:`generic <generics>` over the type of their contents.
|
|
|
|
.. audit-event:: array.__new__ typecode,initializer array.array
|
|
|
|
|
|
.. attribute:: typecode
|
|
|
|
The typecode character used to create the array.
|
|
|
|
|
|
.. attribute:: itemsize
|
|
|
|
The length in bytes of one array item in the internal representation.
|
|
|
|
|
|
.. method:: append(value, /)
|
|
|
|
Append a new item with the specified value to the end of the array.
|
|
|
|
|
|
.. method:: 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:: byteswap()
|
|
|
|
"Byteswap" all items of the array. This is only supported for values which are
|
|
1, 2, 4, 8 or 16 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. Note, that for complex types the order of
|
|
components (the real part, followed by imaginary part) is preserved.
|
|
|
|
|
|
.. method:: count(value, /)
|
|
|
|
Return the number of occurrences of *value* in the array.
|
|
|
|
|
|
.. method:: 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:: frombytes(buffer, /)
|
|
|
|
Appends items from the :term:`bytes-like object`, interpreting
|
|
its content 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:: 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.
|
|
|
|
|
|
.. method:: 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:: fromunicode(ustr, /)
|
|
|
|
Extends this array with data from the given Unicode string.
|
|
The array must have type code ``'w'``; otherwise a :exc:`ValueError` is raised.
|
|
Use ``array.frombytes(unicodestring.encode(enc))`` to append Unicode data to an
|
|
array of some other type.
|
|
|
|
|
|
.. method:: index(value[, start[, stop]])
|
|
|
|
Return the smallest *i* such that *i* is the index of the first occurrence of
|
|
*value* in the array. The optional arguments *start* and *stop* can be
|
|
specified to search for *value* within a subsection of the array. Raise
|
|
:exc:`ValueError` if *value* is not found.
|
|
|
|
.. versionchanged:: 3.10
|
|
Added optional *start* and *stop* parameters.
|
|
|
|
|
|
.. method:: insert(index, value, /)
|
|
|
|
Insert a new item *value* in the array before position *index*. Negative
|
|
values are treated as being relative to the end of the array.
|
|
|
|
|
|
.. method:: pop(index=-1, /)
|
|
|
|
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:: remove(value, /)
|
|
|
|
Remove the first occurrence of *value* from the array.
|
|
|
|
|
|
.. method:: clear()
|
|
|
|
Remove all elements from the array.
|
|
|
|
.. versionadded:: 3.13
|
|
|
|
|
|
.. method:: reverse()
|
|
|
|
Reverse the order of the items in the array.
|
|
|
|
|
|
.. method:: 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:: tofile(f, /)
|
|
|
|
Write all items (as machine values) to the :term:`file object` *f*.
|
|
|
|
|
|
.. method:: tolist()
|
|
|
|
Convert the array to an ordinary list with the same items.
|
|
|
|
|
|
.. method:: tounicode()
|
|
|
|
Convert the array to a Unicode string. The array must have a type ``'w'``;
|
|
otherwise a :exc:`ValueError` is raised. Use ``array.tobytes().decode(enc)`` to
|
|
obtain a Unicode string from an array of some other type.
|
|
|
|
|
|
The string representation of array objects has the form
|
|
``array(typecode, initializer)``.
|
|
The *initializer* is omitted if the array is empty, otherwise it is
|
|
a Unicode string if the *typecode* is ``'w'``, otherwise it is
|
|
a list of numbers.
|
|
The string representation 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``.
|
|
Variables ``inf`` and ``nan`` must also be defined if it contains
|
|
corresponding floating-point values.
|
|
Examples::
|
|
|
|
array('l')
|
|
array('w', 'hello \u2641')
|
|
array('l', [1, 2, 3, 4, 5])
|
|
array('d', [1.0, 2.0, 3.14, -inf, nan])
|
|
|
|
|
|
.. seealso::
|
|
|
|
Module :mod:`struct`
|
|
Packing and unpacking of heterogeneous binary data.
|
|
|
|
`NumPy <https://numpy.org/>`_
|
|
The NumPy package defines another array type.
|
|
|
|
.. _ieee 754 standard: https://en.wikipedia.org/wiki/IEEE_754-2008_revision
|