erase 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
erase/__init__.py ADDED
@@ -0,0 +1,46 @@
1
+ """Remove every occurrence of a value from a list, in place.
2
+
3
+ >>> from erase import erase
4
+ >>> a = ['x', 'y', 'z', 'x', 'x']
5
+ >>> erase(a, 'x')
6
+ 3
7
+ >>> a
8
+ ['y', 'z']
9
+
10
+ ``erase(seq, value)`` removes every item ``x`` of *seq* for which
11
+ ``x is value or x == value`` -- the test ``list.remove()`` uses -- and returns
12
+ how many items it removed (0 if there were none: a missing value is not an
13
+ error). It works in one pass, keeps the order of the remaining items and
14
+ never builds a second list.
15
+
16
+ The function comes from the C extension ``erase._erase`` when it is
17
+ available, and from the pure-Python module ``erase._pure`` otherwise (PyPy,
18
+ GraalPy, or a source install without a C compiler). Both behave the same;
19
+ ``HAS_C_EXTENSION`` tells which one is in use. Setting the environment
20
+ variable ``ERASE_PURE=1`` before the import selects the pure-Python
21
+ implementation even when the extension is installed.
22
+ """
23
+
24
+ import os as _os
25
+
26
+ __version__ = "0.1.0"
27
+ __all__ = ["erase", "HAS_C_EXTENSION", "__version__"]
28
+
29
+ HAS_C_EXTENSION: bool
30
+ """True if :func:`erase` is the C implementation, False if it is the pure-Python one."""
31
+
32
+ if _os.environ.get("ERASE_PURE") == "1":
33
+ from ._pure import erase
34
+
35
+ HAS_C_EXTENSION = False
36
+ else:
37
+ try:
38
+ from ._erase import erase
39
+ except ImportError: # no compiled extension for this interpreter
40
+ from ._pure import erase
41
+
42
+ HAS_C_EXTENSION = False
43
+ else:
44
+ HAS_C_EXTENSION = True
45
+
46
+ del _os
erase/_erase.pyi ADDED
@@ -0,0 +1,7 @@
1
+ """Type stub for the C extension module erase._erase."""
2
+
3
+ from collections.abc import MutableSequence
4
+ from typing import Any
5
+
6
+ def erase(seq: MutableSequence[Any], value: object, /) -> int:
7
+ """Remove every occurrence of value from seq, in place; return how many were removed."""
erase/_pure.py ADDED
@@ -0,0 +1,348 @@
1
+ """Pure-Python implementation of :func:`erase.erase`.
2
+
3
+ This module is what ``import erase`` uses when the C extension
4
+ ``erase._erase`` is not available (PyPy, GraalPy, a source install without a
5
+ C compiler) or when the environment variable ``ERASE_PURE=1`` is set. It
6
+ follows the same rules as the C implementation:
7
+
8
+ * An item ``x`` is removed when ``x is value or x == value`` -- identity
9
+ first, then ``x == value`` with the item on the left, the result
10
+ truth-tested once. This is the test ``list.remove()``, ``list.count()``
11
+ and ``in`` use. Every item is compared exactly once, in index order.
12
+ * The number of removed items is returned; the sequence is changed in place
13
+ and the items that stay keep their order.
14
+ * If a comparison (or the truth test of its result) raises, the exception
15
+ propagates and the sequence is left unchanged.
16
+ * If the sequence is changed while the comparisons run (by an ``__eq__``
17
+ method, for example), ``RuntimeError("list modified during erase()")`` is
18
+ raised and nothing is removed. An item is never removed unless it was
19
+ compared equal to *value* and is still in the slot where that happened.
20
+
21
+ It also provides :func:`_erase_generic`, the path for every mutable sequence
22
+ that is not a plain list. The C extension calls it for those arguments too,
23
+ so both implementations handle them identically.
24
+
25
+ Exact lists, and list subclasses that do not override ``__setitem__`` or
26
+ ``__delitem__``, are handled through ``list``'s own methods, so overriding
27
+ ``__iter__``, ``__len__``, ``__getitem__`` or ``copy`` in such a subclass has
28
+ no effect -- just as in the C implementation, which works on the list storage.
29
+
30
+ Thread safety: this implementation is exact for modifications made by the
31
+ comparisons themselves. Modifications made concurrently by other threads are
32
+ detected on a best-effort basis only: pure Python code cannot inspect and
33
+ rewrite a list in one atomic step.
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ from itertools import compress as _compress
39
+ from itertools import islice as _islice
40
+ from operator import is_ as _is
41
+
42
+ TYPE_CHECKING = False
43
+ if TYPE_CHECKING: # pragma: no cover - imports for type checkers only
44
+ from collections.abc import MutableSequence
45
+ from typing import Any
46
+
47
+ __all__ = ["erase"]
48
+
49
+ _MODIFIED = "list modified during erase()"
50
+
51
+ # list's own methods: the fast path reads and writes the list storage with
52
+ # them, so that subclasses overriding __iter__, __len__, ... are not consulted.
53
+ _list_len = list.__len__
54
+ _list_iter = list.__iter__
55
+ _list_copy = list.copy
56
+ _list_getitem = list.__getitem__
57
+ _LIST_SETITEM = list.__dict__["__setitem__"]
58
+ _LIST_DELITEM = list.__dict__["__delitem__"]
59
+ _MISSING = object()
60
+
61
+ # Swaps the bytes 0 and 1: turns a "keep" mask into a "remove" mask.
62
+ _FLIP = bytes.maketrans(b"\x00\x01", b"\x01\x00")
63
+
64
+ # Few matches (at most _FEW, or at most one per _SPARSE items): rebuild the
65
+ # list from slices, at a cost per match; otherwise with itertools.compress, at
66
+ # a (smaller) cost per item.
67
+ _FEW = 8
68
+ _SPARSE = 32
69
+
70
+
71
+ def _list_overrides(cls: type) -> tuple[bool, bool]:
72
+ """Return (overrides __setitem__, overrides __delitem__) for a list subclass.
73
+
74
+ The first definition along the MRO before ``list`` counts; one that is
75
+ ``list``'s own method is not an override. A class that is not really a
76
+ list subclass (``isinstance`` fooled by ``__class__``) counts as
77
+ overriding both. A list subclass overriding neither takes the fast path,
78
+ like an exact list. This is the rule the C implementation applies to
79
+ the type's ``mp_ass_subscript`` slot, which ``__setitem__`` and
80
+ ``__delitem__`` share.
81
+ """
82
+ setitem = delitem = _MISSING
83
+ for klass in cls.__mro__:
84
+ if klass is list:
85
+ break
86
+ attrs = klass.__dict__
87
+ if setitem is _MISSING:
88
+ setitem = attrs.get("__setitem__", _MISSING)
89
+ if delitem is _MISSING:
90
+ delitem = attrs.get("__delitem__", _MISSING)
91
+ else:
92
+ return True, True
93
+ return (
94
+ setitem is not _MISSING and setitem is not _LIST_SETITEM,
95
+ delitem is not _MISSING and delitem is not _LIST_DELITEM,
96
+ )
97
+
98
+
99
+ def erase(seq: MutableSequence[Any], value: object, /) -> int:
100
+ """Remove every occurrence of *value* from *seq*, in place; return how many were removed.
101
+
102
+ An item ``x`` is removed when ``x is value or x == value`` -- the test
103
+ ``list.remove()``, ``list.count()`` and ``in`` use, with the item on the
104
+ left. Each item is compared exactly once, in order, and the items that
105
+ stay keep their order. If *value* does not occur, nothing happens and 0
106
+ is returned; no exception is raised for a missing value.
107
+
108
+ >>> a = ['x', 'y', 'z', 'x', 'x']
109
+ >>> erase(a, 'x')
110
+ 3
111
+ >>> a
112
+ ['y', 'z']
113
+
114
+ *seq* is normally a list, but any mutable sequence works: list
115
+ subclasses, ``collections.UserList``, ``collections.deque``,
116
+ ``array.array``, ``bytearray`` and every other
117
+ ``collections.abc.MutableSequence``. Anything else (tuple, str, bytes,
118
+ range, dict, set, None, ...) raises TypeError.
119
+
120
+ If a comparison raises, the exception propagates and *seq* is left
121
+ unchanged. If *seq* is modified while the comparisons run (by an
122
+ ``__eq__`` method, for example), RuntimeError is raised and nothing is
123
+ removed. After removing most of the items of a large list, the memory
124
+ they occupied is given back.
125
+ """
126
+ if not (
127
+ isinstance(seq, list)
128
+ and (type(seq) is list or not any(_list_overrides(type(seq))))
129
+ ):
130
+ return _erase_generic(seq, value)
131
+
132
+ n = _list_len(seq)
133
+ if not n:
134
+ return 0
135
+ # One pass over the live list (bounded by its original length), as the C
136
+ # implementation does: keep[i] is True for an item that stays; the objects
137
+ # that compared equal are collected in `found`, in order.
138
+ found: list[object] = []
139
+ note = found.append
140
+ keep = [
141
+ x is not value and not x == value or note(x) is not None
142
+ for x in _islice(_list_iter(seq), n)
143
+ ]
144
+ if len(keep) != n or _list_len(seq) != n:
145
+ raise RuntimeError(_MODIFIED)
146
+ k = len(found)
147
+ if not k:
148
+ return 0
149
+
150
+ mask = bytes(keep) # 1 = keep, 0 = remove
151
+ first = mask.find(0)
152
+ if k == 1:
153
+ try:
154
+ unchanged = _list_getitem(seq, first) is found[0]
155
+ except IndexError:
156
+ unchanged = False
157
+ if not unchanged:
158
+ raise RuntimeError(_MODIFIED)
159
+ del seq[first : first + 1]
160
+ return 1
161
+
162
+ # Every slot to be cleared must still hold the very object that compared
163
+ # equal there; the other slots are taken as they are now.
164
+ cur = _list_copy(seq)
165
+ if len(cur) != n:
166
+ raise RuntimeError(_MODIFIED)
167
+ if k <= _FEW or k * _SPARSE <= n:
168
+ tail: list[object] = []
169
+ prev = pos = first
170
+ for obj in found:
171
+ if cur[pos] is not obj:
172
+ raise RuntimeError(_MODIFIED)
173
+ tail += cur[prev:pos]
174
+ prev = pos + 1
175
+ pos = mask.find(0, prev)
176
+ tail += cur[prev:]
177
+ else:
178
+ if not all(map(_is, _compress(cur, mask.translate(_FLIP)), found)):
179
+ raise RuntimeError(_MODIFIED)
180
+ tail = list(_compress(_islice(cur, first, None), mask[first:]))
181
+ # One slice assignment: the list is never seen half-updated, the removed
182
+ # objects are released only once it is consistent (and only after this
183
+ # function returns, since `found` still refers to them), and a list that
184
+ # fell well below its capacity is shrunk.
185
+ seq[first:] = tail
186
+ return k
187
+
188
+
189
+ # ---------------------------------------------------------------------------
190
+ # Generic mutable sequences
191
+
192
+ # (array.array, collections.deque, collections.UserList,
193
+ # collections.abc.MutableSequence), imported on first use so that
194
+ # ``import erase`` stays cheap.
195
+ _generic_types: tuple[type, type, type, type] | None = None
196
+
197
+ _SLICE, _DELETE, _DEQUE = range(3)
198
+
199
+
200
+ def _load_generic_types() -> tuple[type, type, type, type]:
201
+ global _generic_types
202
+ from array import array
203
+ from collections import UserList, deque
204
+ from collections.abc import MutableSequence
205
+
206
+ _generic_types = (array, deque, UserList, MutableSequence)
207
+ return _generic_types
208
+
209
+
210
+ def _erase_generic(seq: Any, value: object, /) -> int:
211
+ """Erase *value* from a mutable sequence that is not a plain list.
212
+
213
+ Called by :func:`erase` -- in both implementations -- for every argument
214
+ that is not an exact list or a list subclass inheriting list's item
215
+ assignment and deletion. It goes through the object's own methods:
216
+
217
+ * a list subclass overriding ``__setitem__``, and ``collections.UserList``:
218
+ one slice assignment ``seq[:] = kept``;
219
+ * a list subclass overriding only ``__delitem__``, and any other
220
+ ``collections.abc.MutableSequence``: ``del seq[i]`` for each matched
221
+ index, from the last to the first;
222
+ * ``collections.deque``: ``seq.clear()`` then ``seq.extend(kept)``;
223
+ * ``array.array`` and ``bytearray``: a slice assignment of an object of
224
+ the same kind.
225
+
226
+ The items are snapshotted with ``list(seq)`` (for array.array and
227
+ bytearray: from the buffer) and compared like :func:`erase` does. Before
228
+ anything is written back, the length must be unchanged and every matched
229
+ index must still hold the object that compared equal (for array.array and
230
+ bytearray: the same stored value); otherwise RuntimeError is raised and
231
+ *seq* is left unchanged. Positions that are kept take their current
232
+ contents. Anything that is not a mutable sequence raises TypeError.
233
+ """
234
+ array_type, deque_type, userlist_type, mutable_sequence = (
235
+ _generic_types or _load_generic_types()
236
+ )
237
+ if isinstance(seq, list):
238
+ overrides_setitem, overrides_delitem = _list_overrides(type(seq))
239
+ mode = _DELETE if overrides_delitem and not overrides_setitem else _SLICE
240
+ elif isinstance(seq, (bytearray, array_type)):
241
+ return _erase_buffer(seq, value, array_type)
242
+ elif isinstance(seq, deque_type):
243
+ mode = _DEQUE
244
+ elif isinstance(seq, userlist_type):
245
+ mode = _SLICE
246
+ elif isinstance(seq, mutable_sequence):
247
+ mode = _DELETE
248
+ else:
249
+ raise TypeError(
250
+ "erase() argument 1 must be a mutable sequence, not "
251
+ + type(seq).__name__
252
+ )
253
+
254
+ items = list(seq)
255
+ n = len(items)
256
+ keep = [x is not value and not x == value for x in items]
257
+ if len(seq) != n:
258
+ raise RuntimeError(_MODIFIED)
259
+ mask = bytes(keep) # 1 = keep, 0 = remove
260
+ pos = mask.find(0)
261
+ if pos < 0:
262
+ return 0
263
+ k = mask.count(0)
264
+
265
+ if mode == _DELETE:
266
+ matched = []
267
+ while pos >= 0:
268
+ if seq[pos] is not items[pos]:
269
+ raise RuntimeError(_MODIFIED)
270
+ matched.append(pos)
271
+ pos = mask.find(0, pos + 1)
272
+ for pos in reversed(matched):
273
+ del seq[pos]
274
+ return k
275
+
276
+ cur = list(seq)
277
+ if len(cur) != n:
278
+ raise RuntimeError(_MODIFIED)
279
+ drop = mask.translate(_FLIP)
280
+ if not all(map(_is, _compress(cur, drop), _compress(items, drop))):
281
+ raise RuntimeError(_MODIFIED)
282
+ kept = list(_compress(cur, mask))
283
+ if mode == _DEQUE:
284
+ seq.clear()
285
+ seq.extend(kept)
286
+ else:
287
+ seq[:] = kept
288
+ return k
289
+
290
+
291
+ def _erase_buffer(seq: Any, value: object, array_type: type) -> int:
292
+ """_erase_generic() for bytearray and array.array.
293
+
294
+ Their items are stored as raw values and boxed anew on each access, so
295
+ "the slot still holds the same object" means "the same stored bytes".
296
+ """
297
+ if type(seq) is bytearray and type(value) is int:
298
+ # Byte == int: no Python code can run, so a C-speed shortcut is exact.
299
+ if not 0 <= value <= 255:
300
+ return 0
301
+ k = seq.count(value)
302
+ if k:
303
+ seq[:] = seq.translate(None, bytes((value,)))
304
+ return k
305
+
306
+ is_bytearray = isinstance(seq, bytearray)
307
+ with memoryview(seq) as view:
308
+ before = view.tobytes()
309
+ size = view.itemsize
310
+ if is_bytearray:
311
+ items = list(before)
312
+ else:
313
+ snapshot = array_type(seq.typecode)
314
+ snapshot.frombytes(before)
315
+ items = snapshot.tolist()
316
+ n = len(items)
317
+ keep = [x is not value and not x == value for x in items]
318
+ if len(seq) != n:
319
+ raise RuntimeError(_MODIFIED)
320
+ mask = bytes(keep) # 1 = keep, 0 = remove
321
+ pos = mask.find(0)
322
+ if pos < 0:
323
+ return 0
324
+ k = mask.count(0)
325
+
326
+ with memoryview(seq) as view:
327
+ after = view.tobytes()
328
+ if len(after) != len(before):
329
+ raise RuntimeError(_MODIFIED)
330
+ parts = []
331
+ prev = 0
332
+ while pos >= 0:
333
+ lo = pos * size
334
+ hi = lo + size
335
+ if after[lo:hi] != before[lo:hi]:
336
+ raise RuntimeError(_MODIFIED)
337
+ parts.append(after[prev * size : lo])
338
+ prev = pos + 1
339
+ pos = mask.find(0, prev)
340
+ parts.append(after[prev * size :])
341
+ data = b"".join(parts)
342
+ if is_bytearray:
343
+ seq[:] = data
344
+ else:
345
+ new = array_type(seq.typecode)
346
+ new.frombytes(data)
347
+ seq[:] = new
348
+ return k
erase/py.typed ADDED
File without changes
@@ -0,0 +1,171 @@
1
+ Metadata-Version: 2.4
2
+ Name: erase
3
+ Version: 0.1.0
4
+ Summary: Remove every occurrence of a value from a list, in place, with a fast C implementation.
5
+ Author: Muhammad Asad Janjua
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/KripKrop72724/erase
8
+ Project-URL: Source, https://github.com/KripKrop72724/erase
9
+ Project-URL: Issues, https://github.com/KripKrop72724/erase/issues
10
+ Project-URL: Changelog, https://github.com/KripKrop72724/erase/blob/main/CHANGELOG.md
11
+ Keywords: list,remove,remove-all,erase,delete,in-place,sequence,c-extension
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: C
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: 3.14
24
+ Classifier: Programming Language :: Python :: 3.15
25
+ Classifier: Programming Language :: Python :: Free Threading :: 2 - Beta
26
+ Classifier: Programming Language :: Python :: Implementation :: CPython
27
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
28
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
29
+ Classifier: Typing :: Typed
30
+ Requires-Python: >=3.9
31
+ Description-Content-Type: text/markdown
32
+ License-File: LICENSE
33
+ Dynamic: license-file
34
+
35
+ # erase
36
+
37
+ [![PyPI version](https://img.shields.io/pypi/v/erase)](https://pypi.org/project/erase/)
38
+
39
+ Remove every occurrence of a value from a list in place, in linear time, and get back how many were removed.
40
+
41
+ ## Install
42
+
43
+ ```
44
+ pip install erase
45
+ ```
46
+
47
+ Requires Python 3.9 or newer. Binary wheels cover CPython 3.9 to 3.15, plus free-threaded 3.14t and 3.15t, on Linux, macOS and Windows. Everywhere else (PyPy, GraalPy, other platforms) pip installs the pure-Python wheel, which gives the same results.
48
+
49
+ ## Usage
50
+
51
+ ```pycon
52
+ >>> from erase import erase
53
+ >>> a = ['x', 'y', 'z', 'x', 'x']
54
+ >>> erase(a, 'x')
55
+ 3
56
+ >>> a
57
+ ['y', 'z']
58
+ >>> erase(a, 'w') # nothing to remove: returns 0, no ValueError
59
+ 0
60
+ ```
61
+
62
+ `erase(seq, value, /)` removes every item equal to `value` from `seq`, in place, and returns how many items it removed. `seq` stays the same object, so every reference to it sees the change. Items and values can be of any type:
63
+
64
+ ```pycon
65
+ >>> row = ['id', None, 'name', None]
66
+ >>> erase(row, None)
67
+ 2
68
+ >>> row
69
+ ['id', 'name']
70
+ >>> nums = [1, 1.0, 2, True, 3]
71
+ >>> erase(nums, 1) # 1 == 1.0 == True, so all three go, as with list.remove
72
+ 3
73
+ >>> nums
74
+ [2, 3]
75
+ >>> import math
76
+ >>> data = [0.5, math.nan, 1.5, math.nan]
77
+ >>> erase(data, math.nan) # the very object passed is removed, as with list.remove
78
+ 2
79
+ >>> data
80
+ [0.5, 1.5]
81
+ ```
82
+
83
+ ## Why not a one-liner?
84
+
85
+ | Idiom | Pitfall |
86
+ |---|---|
87
+ | `a = [x for x in a if x != v]` | Builds a new list and rebinds the name `a`. Every other reference to the list (the caller's variable, an attribute) still sees the old contents. |
88
+ | `a[:] = [x for x in a if x != v]` | In place, but first builds a temporary list of all kept items. Unlike `list.remove`, it does not check identity first, so if `v` is a NaN object, the items that are that very object are kept. |
89
+ | `list(filter((2).__ne__, a))`, the first suggestion in the [accepted Stack Overflow answer](https://stackoverflow.com/a/1157160) | Builds a new list, and mishandles equal values of other numeric types: removing `1` keeps `1.0`, because `(1).__ne__(1.0)` returns `NotImplemented`, which counts as true. On Python 3.14+ it raises `TypeError` at the first item that is not an `int`. |
90
+ | `while v in a: a.remove(v)` | Correct, but every removal searches again from the start and shifts the rest of the list: O(n·k) for k matches. At 32,000 items with 10% matches it is about 1,000 times slower than a comprehension. |
91
+ | `a.remove(x)` inside `for x in a:` | Changes the list while iterating over it, so the item after each removed one is skipped: `[1, 1, 2]` becomes `[1, 2]`. |
92
+ | `a[:] = [x for x in a if not (x is v or x == v)]` | Same result as `erase` (same test), but builds a temporary list and is usually slower than the `!=` version (see Performance). |
93
+
94
+ ## Semantics
95
+
96
+ - **Same test as `list.remove`.** An item `x` is removed when `x is value or x == value`, with the item on the left of `==` and the result's truth value used. `list.remove`, `list.count` and `in` use the same test. Each item is compared exactly once, in index order. If the comparisons have no side effects, `erase(a, v)` returns what `a.count(v)` returned before the call and leaves `a` as `while v in a: a.remove(v)` would.
97
+ - **In place.** The sequence is changed, not replaced. Kept items keep their order.
98
+ - **All or nothing.** If a comparison raises, or testing its result for truth raises, the exception propagates and the sequence is left unchanged.
99
+ - **Safe if the sequence changes during the comparisons.** Code that runs while `erase` compares (an `__eq__` method, a `__del__` it triggers, another thread) may change the sequence. If its length changed, or a slot about to be removed no longer holds the object that compared equal, `erase` raises `RuntimeError("list modified during erase()")` and changes nothing. Changes that pass this check, such as an item replaced at a kept position, are preserved. `erase` never removes an item that did not compare equal (for threads, see the FAQ).
100
+ - **Memory is given back.** When most items of a list are removed, its spare capacity is released, as `del` and `list.pop()` release it (on free-threaded builds, at the list's next resize).
101
+
102
+ ## Performance
103
+
104
+ Apple M2, CPython 3.13. Measured with [`benchmarks/bench.py`](https://github.com/KripKrop72724/erase/blob/main/benchmarks/bench.py): minimum of 15 interleaved runs, each on a fresh copy of the list.
105
+
106
+ | Scenario | `erase` | `!=` comprehension | identity-aware comprehension |
107
+ |---|--:|--:|--:|
108
+ | 1,000,000 str, 0.1% match | 2.20 ms | 17.9 ms (8.2x) | 24.8 ms (11.3x) |
109
+ | 1,000,000 str, 10% match | 2.93 ms | 19.2 ms (6.5x) | 26.4 ms (9.0x) |
110
+ | 1,000,000 small int, 10% match | 1.38 ms | 14.9 ms (10.8x) | 22.3 ms (16.1x) |
111
+ | 1,000,000 str and int, 10% None | 1.88 ms | 32.2 ms (17.2x) | 36.4 ms (19.4x) |
112
+ | 100,000 objects with a Python `__eq__`, 10% match | 4.38 ms | 7.78 ms (1.8x) | 5.76 ms (1.3x) |
113
+ | 10-item list, 2 matches | 43.1 ns | 218 ns (5.1x) | 310 ns (7.2x) |
114
+
115
+ `!=` comprehension: `a[:] = [x for x in a if x != v]`. Identity-aware comprehension: `a[:] = [x for x in a if not (x is v or x == v)]`, the same test as `erase`. In parentheses: that time divided by the time of `erase`.
116
+
117
+ **Memory.** The C extension builds no temporary list. On the 1,000,000 strings its peak extra memory is 0.13 MB with 0.1% matches and 0.93 MB with 10% (one bit per item plus one pointer per removed item), against 16.4 MB and 15.5 MB for the `!=` comprehension (the temporary list of kept items, plus a buffer for the old items that the slice assignment allocates).
118
+
119
+ **Where it gains little.** For objects whose `__eq__` is written in Python, almost all of the time goes into running `__eq__`, which `erase` has to call just like a comprehension does, so it is only a little faster than the identity-aware comprehension, which also uses `==`. The `!=` comprehension is slower than that one because, for a class that defines only `__eq__`, `!=` goes through the inherited `__ne__`, which calls `__eq__` and inverts the result.
120
+
121
+ The pure-Python implementation has the same semantics but is not faster than a comprehension.
122
+
123
+ ## Supported types
124
+
125
+ - **`list`**, and subclasses of `list` that do not override `__setitem__` or `__delitem__`: the fast path, which with the C extension works directly on the list's storage.
126
+ - **Other mutable sequences**: list subclasses that override those methods, `collections.UserList`, `collections.deque`, `array.array`, `bytearray`, and any other `collections.abc.MutableSequence`. They take a generic path that changes the object only through its own methods, with the same test and the same checks.
127
+ - **Anything else** (`tuple`, `str`, `bytes`, `range`, `dict`, `set`, `None`, ...) raises `TypeError`.
128
+
129
+ ```pycon
130
+ >>> from collections import deque
131
+ >>> d = deque([1, 2, 1, 3])
132
+ >>> erase(d, 1)
133
+ 2
134
+ >>> d
135
+ deque([2, 3])
136
+ >>> buf = bytearray(b'a,b,,c')
137
+ >>> erase(buf, ord(','))
138
+ 3
139
+ >>> buf
140
+ bytearray(b'abc')
141
+ >>> erase((1, 2, 1), 1)
142
+ Traceback (most recent call last):
143
+ ...
144
+ TypeError: erase() argument 1 must be a mutable sequence, not tuple
145
+ ```
146
+
147
+ ## Implementation notes
148
+
149
+ - **C extension.** For lists, `erase._erase` makes one O(n) pass that compares every item once and marks the matches in a bitmap, then compacts the list in place: kept items slide down with plain pointer moves, the length is set, and only then are the removed items released, so any `__del__` they trigger sees a consistent list.
150
+ - **Fast comparisons.** Items and values of the exact types `str`, `int`, `float` and `bytes` are compared directly in C, and built-in types that can never be equal, such as `None` and `str`, are not compared at all. Everything else goes through the normal `==`.
151
+ - **Pure-Python fallback.** `erase._pure` implements the same semantics. It is used on PyPy, GraalPy and wherever no binary wheel fits, and when the extension cannot be compiled from the source distribution.
152
+ - **Which one is active.** `erase.HAS_C_EXTENSION` is `True` when the C extension is in use. Set the environment variable `ERASE_PURE=1` before importing `erase` to use the pure-Python implementation anyway, for example to compare the two. `erase.__version__` gives the version.
153
+ - **Free-threaded CPython.** Wheels for 3.14t and 3.15t. The extension does not need the GIL; it locks the list with a per-object critical section, as list methods do. On free-threaded builds a list's spare capacity is released at its next resize instead of during `erase`.
154
+
155
+ ## FAQ
156
+
157
+ **Why isn't this a list method?**
158
+ Built-in types cannot be extended from Python: `list.erase = ...` raises `TypeError`. CPython core developers declined `list.remove_all()`, `list.removeall()` and a count argument for `list.remove()` several times between 2013 and 2026, and said that such a single-pass variant belongs in an extension. This is that extension.
159
+
160
+ **Is it thread-safe?**
161
+ With the C extension, on a list, yes: the comparisons, the check and the compaction run under the GIL, or under the list's lock on free-threaded builds. Another thread can only change the list while a comparison runs Python code, such as an `__eq__` written in Python, and such changes are handled as described under Semantics: `erase` never corrupts the list or removes an item that did not compare equal, and raises `RuntimeError` rather than guess. The pure-Python implementation and the generic path for other sequences make the same check, but another thread can still change the sequence between the check and the write-back, so protect a sequence shared between threads with a lock, as for any read-modify-write.
162
+
163
+ **Why did `erase(a, 1)` also remove `1.0` and `True`?**
164
+ Because they are equal to `1`: `1 == 1.0 == True`. `erase` uses the same test as `list.remove`, `list.count` and `in`. To remove only ints, use a comprehension with a type check.
165
+
166
+ **Can it remove every NaN?**
167
+ No. NaN is not equal to anything, itself included, so `erase` removes only the very NaN object you pass, as `list.remove` does; `float('nan')` makes a new object each time. To drop every NaN, use `a[:] = [x for x in a if x == x]`.
168
+
169
+ ## License
170
+
171
+ MIT. See [LICENSE](https://github.com/KripKrop72724/erase/blob/main/LICENSE).
@@ -0,0 +1,9 @@
1
+ erase/__init__.py,sha256=OSdWojldXwwl_0klx0YcST1Jir7f6Z6i3yzsfP--ORs,1467
2
+ erase/_erase.pyi,sha256=9JMOx5KHmsEGRN9w4itNF93qv_X-vO7uVeesm6Fe3_M,282
3
+ erase/_pure.py,sha256=1cMxQT5K2snP3LAjSnQuMN5tNRj4DkesVmMeJDecAGc,13116
4
+ erase/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ erase-0.1.0.dist-info/licenses/LICENSE,sha256=Q42NeWCSODiJSKrANR8gt6tf0feLNwhex-zHPTYOagk,1077
6
+ erase-0.1.0.dist-info/METADATA,sha256=6Q5MqETEAgVKwSoVpDZERLbvQ8mOQehbqDz7I0ppUtc,11723
7
+ erase-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ erase-0.1.0.dist-info/top_level.txt,sha256=e2zut3NVAyh6QdCb2h9xlCA16GruNaHz-TlepHgO3Hk,6
9
+ erase-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Muhammad Asad Janjua
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ erase