Debian Codegraph @

mypyc/doc/librt_vecs.rst

raw
1 .. _librt-vecs:
2
3 librt.vecs
4 ==========
5
6 The ``librt.vecs`` module defines the ``vec`` type, a low-level, uniform growable array type.
7 It's part of the ``librt`` package on PyPI.
8
9 When constructing a ``vec``, the item type ``T`` is always explicitly given via ``vec[T]``::
10
11 from librt.vecs import append, vec
12
13 v = vec[float]([1.0, 2.5]) # Construct vec[float] with two items
14
15 ``vec`` supports many sequence operations, though it's not a full sequence type::
16
17 len(v) # 2
18 v[0] # 1.0
19 v[-1] # 2.5
20 for x in v:
21 print(x)
22
23 The length of each ``vec`` value is immutable. Appending an item is still a fast operation,
24 but it returns a new ``vec`` value::
25
26 v = append(v, -0.5)
27 print(v) # vec[float]([1.0, 2.5, -0.5])
28
29 ``vec`` only supports simple, uniform item types. It uses an efficient packed binary encoding
30 for these *value item types*:
31
32 * ``mypy_extensions.i64`` (signed 64-bit integer)
33 * ``mypy_extensions.i32`` (signed 32-bit integer)
34 * ``mypy_extensions.i16`` (signed 16-bit integer)
35 * ``mypy_extensions.u8`` (unsigned byte)
36 * ``float`` (64-bit float)
37 * ``bool``
38
39 ``int`` is not a valid item type, since it has an arbitrary precision, and vec is an
40 efficiency-focused type. Use one of the fixed-length integer types instead.
41
42 Class item types (e.g. ``str`` or ``MyNativeClass``) are represented as regular object references.
43 Optional class item types (e.g. ``str | None``) are supported for convenience, but arbitrary
44 union types are not supported as item types. Nested vecs are supported, e.g. ``vec[vec[i64]]``.
45
46 A vec value is often used as an efficient alternative to ``list`` or ``array.array`` in code
47 compiled using mypyc. Its primary advantages are an efficient packed memory representation
48 for value item types and very fast inlined get and set item operations.
49
50 Vec instances perform runtime checking of item types. Since values of type variables are
51 not available at runtime (they are *erased*), type variables can't be used as item types.
52
53 A vec value is effectively an immutable (length, buffer) pair. This means that any operation
54 that changes the length of a vec, including ``append`` as we saw above, returns a modified
55 value.
56
57 .. note::
58 An immutable length allows more efficient code to be generated by mypyc, and vec values
59 can be allocated to machine registers effectively. However, vec values must be boxed
60 if used in a non-native context, such as if added to a list or dict.
61
62 Here are some examples of valid vec types:
63
64 .. list-table::
65 :header-rows: 1
66
67 * - Type
68 - Item representation
69 * - ``vec[i32]``
70 - Packed 32-bit integers
71 * - ``vec[float]``
72 - Packed 64-bit floats
73 * - ``vec[str]``
74 - Object references
75 * - ``vec[vec[u8]]``
76 - Packed vec values
77
78 The ``vec`` class
79 -----------------
80
81 .. class:: vec[T](items: Iterable[T] = ..., *, capacity: i64 = ...)
82
83 A generic growable array type. The runtime type parameter ``T`` used when
84 calling ``vec[T](...)`` determines the element type.
85
86 The ``capacity`` parameter allows defining the minimum initial
87 capacity of the buffer, some of which may be unused after
88 construction. Unused capacity allows fast ``append`` and ``extend``
89 operations that don't need to reallocate the buffer. Actual capacity
90 will be larger than ``capacity`` if ``items`` has more than ``capacity``
91 items.
92
93 Construction from ``list`` and ``tuple`` objects is optimized.
94 Also, for value item types, construction from an object that implements
95 the buffer protocol is optimized (such as ``bytes``), if the format
96 is compatible with the vec item type.
97
98 Mypyc treats ``vec[T]([x] * n)`` as a special form. For example,
99 ``vec[u8]([0] * n)`` constructs a zero-initialized vec object
100 efficiently, without building an intermediate list. There are
101 also other constructor-related special forms -- see `Special
102 forms`_ below.
103
104 It's an error to construct a ``vec`` object without providing an
105 item type: ``vec()`` raises an exception.
106
107 .. describe:: len(v) → i64
108
109 Return the length of ``v``.
110
111 .. describe:: v[i] → T
112
113 Return item at index ``i`` (index may be negative).
114
115 .. describe:: v[i:j] → vec[T]
116
117 Return a slice. This constructs a new ``vec`` object. ``i`` and ``j`` may be negative.
118
119 .. describe:: v[i] = o
120
121 Assign to an item (index may be negative).
122
123 .. describe:: o in v → bool
124
125 Return True if ``v`` contains ``o``.
126
127 .. describe:: for o in v
128
129 Iterate over items.
130
131 .. describe:: memoryview(v)
132
133 ``vec`` implements the buffer protocol, but only for value item types that use a
134 packed representation.
135
136 Functions
137 ---------
138
139 Since the following operations return a modified value, they are module-level functions
140 instead of methods.
141
142 .. function:: append(v: vec[T], o: T) -> vec[T]
143
144 Return ``v`` with item ``o`` appended to it. If ``v`` has unused capacity, reuse
145 the existing buffer. The time complexity is O(1) on average. Example::
146
147 v = vec[i32]()
148 v = append(v, 1)
149
150 .. function:: extend(v: vec[T], it: Iterable[T]) -> vec[T]
151
152 Return ``v`` with all items from iterable ``it`` appended to it. If ``v`` has sufficient
153 unused capacity, reuse the existing buffer. The time complexity is O(n) on average,
154 where n is the length of ``it``. Example::
155
156 v = vec[u8]()
157 v = extend(v, b"foo")
158
159 .. function:: remove(v: vec[T], o: T) -> vec[T]
160
161 Return ``v`` with the first instance of item ``o`` removed. Reuse the buffer
162 from ``v``. Raise ``ValueError`` if value doesn't exist. Example::
163
164 v = vec[i32]([1, 2, 3])
165 v = remove(v, 2)
166 # v has items [1, 3]
167
168 .. function:: pop(v: vec[T], i: i64 = -1) -> tuple[vec[T], T]
169
170 Return ``(new_v, item)``, where ``item`` is the value at index ``i`` and
171 ``new_v`` is ``v`` with that item removed. Reuse the buffer from ``v``.
172 Example::
173
174 v = vec[i32]([1, 2, 3])
175 v, x = pop(v)
176 # x is 3; v has items [1, 2]
177
178 Special forms
179 --------------
180
181 Certain combinations of operations that would be multiple separate operations in
182 regular Python are guaranteed to be compiled by mypyc to direct operations
183 with no unnecessary temporary objects.
184
185 .. list-table::
186 :header-rows: 1
187
188 * - Special form
189 - Description
190 * - ``vec[T]()``
191 - Construct empty vec with no buffer. This doesn't perform any dynamic allocation
192 (at least for non-nested vecs).
193 * - ``vec[T]([element1, ...])``
194 - Directly construct a vec object with given items, without a temporary list.
195 * - ``vec[T]([element1] * n)``
196 - Directly construct a vec with length n, without any temporary list.
197 * - ``vec[T]([<expr> for ... in <expr>])``
198 - Vec comprehension creates no temporary list.
199
200 Thread safety
201 -------------
202
203 The ``vec`` type is heavily optimized for performance, and this means that ``vec``
204 gives fewer thread safety guarantees than built-in types such as ``list``.
205 ``vec`` is a lower-level type where implicit synchronization would have a very
206 significant performance cost. However, since vec lengths are immutable, some race
207 conditions that lists can be susceptible to are not possible with vecs.
208
209 In free-threaded Python builds, it's unsafe to write or modify an item if other
210 threads might be concurrently accessing *the same item*. For example, writing ``v[4]``
211 is not safe to do if another thread might be reading ``v[4]``. Similarly, two
212 threads concurrently calling ``append`` or ``remove`` on the same vec object is not safe.
213
214 Similarly, assigning to an instance attribute of a native class with a ``vec`` type
215 is unsafe if another thread might be accessing the same attribute concurrently
216 (in a free-threaded Python build only). Using ``Final`` attributes is a way
217 to prevent this race condition, since ``Final`` attributes cannot be rebound.
218
219 Implementation details
220 ----------------------
221
222 In a native context, such as in a local variable or a parameter in a native function,
223 or in an attribute of a native class, vec values are implemented as value objects with two
224 fields: length and buffer. The buffer is a normal Python object, but it's not directly
225 accessible to users. If a vec object is empty, no buffer object is required. This means that
226 empty vecs are particularly efficient in a native context (usually 16 bytes).
227
228 A packed representation is used for buffers with supported value item types, including for
229 nested vecs. The packed representation is much more efficient than a Python list object, and
230 it's also significantly more efficient than ``array.array`` for small sequences.
231
232 Multiple vec values can share the same underlying buffer. For example, assigning a vec
233 to another variable creates an alias that refers to the same buffer::
234
235 v = vec[i32]([1, 2, 3], capacity=3)
236 w = v # v and w share the same buffer
237
238 w[0] = 99
239 print(v[0]) # 99 -- both see the change
240
241 However, this sharing is not guaranteed to persist if there are operations that change
242 the length (such as ``append``). These may reallocate the buffer, breaking the sharing
243 silently::
244
245 v = append(v, 4) # reallocates the buffer since there is no free capacity
246 v[0] = 0
247 print(w[0]) # still 99 -- v and w no longer share a buffer
248
249 If you need independent copies, use slicing (``v[:]``) to explicitly create a vec with
250 its own buffer. It's not recommended to rely on the details of buffer reallocation,
251 as these might change between ``librt`` releases.
252
253 Using vecs outside compiled code
254 --------------------------------
255
256 ``vec`` is fully supported in non-compiled code, but ``vec`` values will be boxed in such
257 non-native contexts. There will be always two objects, a boxed vec object and a buffer object,
258 whereas in native contexts usually only the buffer is a dynamically allocated object.
259 ``vec`` is primarily useful in code compiled using mypyc, and it's been heavily optimized
260 for this use case. There may be no performance benefit in interpreted code over using
261 ``list`` or ``array.array``.