Python Glossary Русский

Python 3.15+Byte sequencesfunction

bytearray.take_bytes()

bytearray — mutating

Takes the first n bytes out of a bytearray and returns them as bytes, removing them from the buffer. With no argument it takes everything and clears the buffer without copying.

Syntax

bytearray.take_bytes(n=None, /)

The common “accumulate in a bytearray, hand out bytes” pattern used to be data = bytes(buf); buf.clear(), which copies the whole buffer. take_bytes() with no argument hands the contents over without copying and leaves the buffer empty. With n it takes the beginning and the rest shifts down, which copies the tail, so for frame-by-frame parsing it pays to trim first. A negative n counts from the end, as in slices: take_bytes(-2) takes everything except the last two bytes. An n beyond the length raises IndexError rather than silently giving “whatever is there” as a slice would.

Examples

buf = bytearray(b'hello world')
head = buf.take_bytes(5)
print(head)  # → b'hello'
print(buf)  # → bytearray(b' world')
rest = buf.take_bytes()
print(rest, buf)  # → b' world' bytearray(b'')
buf = bytearray(b'abc')
try:
    buf.take_bytes(10)
except IndexError as e:
    print(type(e).__name__)  # → IndexError

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy