Skip to main content

Lib/array.py

Source:

cpython 3.14 @ ab2d84fe1023/Modules/arraymodule.c

The array module is implemented entirely in C (Modules/arraymodule.c). There is no pure-Python Lib/array.py; the module is compiled into the interpreter. This annotation covers the C implementation.

array.array stores a homogeneous sequence of machine-typed values (C int, double, etc.) in a compact contiguous buffer, unlike list which stores PyObject* pointers. It implements the buffer protocol, allowing zero-copy interop with memoryview, struct, and ctypes.

Map

SymbolRole
array.arrayTyped array type with typecode
typecodesString of all valid single-character type codes
frombytes / tobytesImport/export raw bytes
fromfile / tofileRead/write typed data from file objects
fromlist / tolistConvert to/from a Python list
byteswapReverse byte order in-place for all items
buffer_infoReturn (address, length) of the underlying buffer

Reading

Typecodes

Each array object is parameterized by a single-character typecode that determines the C type of each element and its size.

CodeC typeSize
'b'signed char1
'B'unsigned char1
'h'signed short2
'H'unsigned short2
'i'signed int2 or 4
'I'unsigned int2 or 4
'l'signed long4 or 8
'L'unsigned long4 or 8
'q'signed long long8
'Q'unsigned long long8
'f'float4
'd'double8
'u'Py_UCS4 (deprecated)4

frombytes and tobytes

frombytes(b) appends items decoded from the raw bytes b. The length of b must be a multiple of itemsize. tobytes() returns a bytes object that is the raw memory content of the array, suitable for writing to disk or sending over a socket.

Buffer protocol

array.array exports the PEP 3118 buffer protocol. A memoryview of an array has format set to the struct-format character corresponding to the typecode and itemsize equal to the C type size. This means NumPy and other buffer-aware code can read an array without copying.

fromfile and tofile

# CPython: Modules/arraymodule.c array_fromfile
# Reads n items from a binary file object f.
a.fromfile(f, n)

fromfile calls f.read(n * itemsize) and then calls frombytes on the result. tofile calls f.write(tobytes()).

gopy notes

Status: not yet ported. The Go port needs a concrete ArrayObject type with a typecode field and a []byte backing buffer. The buffer protocol integration requires implementing objects/buffer.go interfaces. Typecode handling maps directly to Go's fixed-width integer and float types.