Python BytesIO — .getvalue() vs .getbuffer()
While building full stack applications and agentic workflows, I kept running into the same decision point around in-memory file handling. Thought a community reference blog would be useful.
What is BytesIO ?
io.BytesIO is an in-memory binary stream — essentially a file that lives in RAM instead of on disk. Internally it wraps a byte array and maintains a position pointer (like a cursor). You use it when you want to read or write bytes without touching the filesystem, common in file processing pipelines, API integrations, and anywhere you pass binary data between services.
The two functions
.getvalue()
- Returns a new bytes object — a full copy of the buffer contents regardless of current position
- Memory cost: file size × 2 (original buffer + copy)
- Safe to pass around independently; immutable; works even after buffer is closed
- Internally calls memcpy on the underlying bytearray
.getbuffer()
- Returns a memoryview — a zero-copy reference into the buffer’s internal memory
- No extra allocation; efficient for large files
- The BytesIO is locked (no writes or resizes allowed) while the memoryview is alive
- Release it with del mv when done, otherwise the lock persists and can silently leak memory in long-running processes
- Accepts the Python buffer protocol — works directly with f.write(), socket.send(), hashlib.update() without an intermediate copy
Example: Reading a file from SharePoint via Graph API
Get Gaurav Jain’s stories in your inbox
Join Medium for free to get updates from this writer.
Authentication uses an SPN (service principal) via ClientSecretCredential. The token is passed as a Bearer header to Microsoft Graph. Graph may return a @microsoft.graph.downloadUrl — a pre-authenticated temporary URL that doesn’t require the Authorization header on the download request.
import io, os, asyncio
import httpx
from azure.identity import ClientSecretCredential
GRAPH_BASE = "https://graph.microsoft.com/v1.0"
def get_token() -> str:
cred = ClientSecretCredential(
tenant_id=os.environ["SHAREPOINT_TENANT_ID"],
client_id=os.environ["SHAREPOINT_CLIENT_ID"],
client_secret=os.environ["SHAREPOINT_CLIENT_SECRET"],
)
return cred.get_token("https://graph.microsoft.com/.default").token
async def fetch_latest_file() -> tuple[str, io.BytesIO]:
token = get_token()
folder = os.environ.get("SHAREPOINT_DEST_FOLDER", "").strip("/")
async with httpx.AsyncClient() as client:
# resolve shorthand site id (hostname:/sites/Name) to opaque GUID
r = await client.get(f"{GRAPH_BASE}/sites/{os.environ['SHAREPOINT_SITE_ID']}", headers={"Authorization": f"Bearer {token}"})
r.raise_for_status()
site_id = r.json()["id"]
# list folder children, pick most recently modified
r = await client.get(f"{GRAPH_BASE}/sites/{site_id}/drive/root:/{folder}:/children", headers={"Authorization": f"Bearer {token}"})
r.raise_for_status()
latest = max(r.json()["value"], key=lambda x: x.get("lastModifiedDateTime") or "")
# prefer pre-authenticated downloadUrl, fallback to content endpoint with token
url = latest.get("@microsoft.graph.downloadUrl") or \
f"{GRAPH_BASE}/sites/{site_id}/drive/items/{latest['id']}/content"
r = await client.get(url, timeout=120)
r.raise_for_status()
return latest["name"], io.BytesIO(r.content)Now using the buffer:
name, buf = asyncio.run(fetch_latest_file())
# .getvalue() - allocates a full copy as immutable bytes
data: bytes = buf.getvalue()
# .getbuffer() - zero-copy memoryview, no extra allocation
mv = buf.getbuffer()
with open(name, "wb") as f:
f.write(mv) # f.write() accepts buffer protocol directly
del mv # release the lock so BytesIO can be GC'd or rewritten
# streaming in chunks - avoids holding the full file in memory at once
buf.seek(0)
while chunk := buf.read(8192):
pass # push chunk to upstream API, blob storage, or upload sessionUnder the hood: Why it matters at concurrency
BytesIO internally uses a byte array. Both .getvalue() and .getbuffer() expose the same underlying data — the difference is whether Python allocates a new object or shares memory via the buffer protocol.
At high concurrency (e.g., 20 concurrent users each downloading a 50 MB file), holding a full BytesIO per request means 1 GB of peak memory just from the buffers. .getbuffer() avoids the copy but still holds the full file. The real fix at scale is to not accumulate the whole file at all — stream the HTTP response in chunks directly to disk or Azure Blob:
# stream Graph response directly — BytesIO never created
async with client.stream("GET", download_url) as resp:
resp.raise_for_status()
with open(name, "wb") as f:
async for chunk in resp.aiter_bytes(8192):
f.write(chunk)This keeps memory per request near zero regardless of file size, and is the right pattern for production pipelines.
Rule of thumb (from my experience so far)
- If Use case is around small file which could be passed around safely then go with .getvalue()
- If Use case is around large files or uploads, then go with .getbuffer() + del mv
- If Use case is around High concurrency / large files then Stream chunks directly, skip BytesIO
- If Use case around Hashing without copy then you could try hashlib.sha256(buf.getbuffer()).hexdigest()
#Python #Azure #SharePoint #MicrosoftGraph #AgenticAI #BackendEngineering









