Use zero-copy data handling with the buffer protocol
mainTo avoid unnecessary memory copying, pyreqwest utilizes the Python buffer protocol.
- Request Bodies: Returned as
pyreqwest.bytes.Bytes. This is abytes-like type. To pass this data to other libraries without copying, wrap it in amemoryview(). - Avoid Copies: Using
bytes(Bytes)orbytearray(Bytes)will trigger a copy of the underlying buffer. Usememoryview(Bytes)for zero-copy access. - Request Retries: Methods like
Request.copy()create zero-copy views, making them efficient for middleware-driven retries.
Note on Ownership: pyreqwest often transfers ownership of data structures. Once a method like Request.send() is called, the Request instance becomes unusable.
# Efficient zero-copy access to response data
response = client.get("https://example.com")
body = response.body # This is pyreqwest.bytes.Bytes
# Pass to another function without copying
process_data(memoryview(body))
# This WOULD cause a copy (avoid if performance is critical)
copy_of_data = bytes(body)