-
-
Notifications
You must be signed in to change notification settings - Fork 33.4k
Description
Feature or enhancement
Proposal:
Update bytearray to have its internal buffer always be a PyBytesObject and add a new method, .take_bytes([n]) which extracts that buffer.
.take_byes([n]) adds a way to go from a "mutable" buffer of bytes to an immutable one without requiring a memcpy.
This creates a path to resolve gh-60107
When would I use this?
Any code which makes a ba = bytearray(), modifies it, then calls bytes(ba). Other common patterns are bytes(ba); ba.clear() or bytes(ba[:n]); del ba[:n]. Note that if you want to discard data past a point, the most efficient pattern becomes ba.resize(n); ba.take_bytes() so that take_bytes([n]) doesn’t need to keep around the soon to be discarded extra bytes.
Has this already been discussed elsewhere?
I have already discussed this feature proposal on Discourse
Links to previous discussion of this feature:
https://discuss.python.org/t/add-take-bytes-n-to-bytearray-providing-a-zero-copy-path-to-bytes/103804/5
https://discuss.python.org/t/add-zero-copy-conversion-of-bytearray-to-bytes-by-providing-bytes/79164 -- edit: added