aio-libs/aiohttp · error · TypeError
Unable to decode.
Error message
Unable to decode.
What it means
Raised unconditionally by BodyPartReaderPayload.decode(). BodyPartReaderPayload is a streaming Payload wrapper around a BodyPartReader; it cannot materialize its full content as a string because the underlying stream may be arbitrarily large and can only be consumed once. The method exists only to satisfy the Payload ABC contract and deliberately rejects synchronous decoding.
Source
Thrown at aiohttp/multipart.py:652
@payload_type(BodyPartReader, order=Order.try_first)
class BodyPartReaderPayload(Payload):
_value: BodyPartReader
# _autoclose = False (inherited) - Streaming reader that may have resources
def __init__(self, value: BodyPartReader, *args: Any, **kwargs: Any) -> None:
super().__init__(value, *args, **kwargs)
params: dict[str, str] = {}
if value.name is not None:
params["name"] = value.name
if value.filename is not None:
params["filename"] = value.filename
if params:
self.set_content_disposition("attachment", True, **params)
def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str:
raise TypeError("Unable to decode.")
async def as_bytes(self, encoding: str = "utf-8", errors: str = "strict") -> bytes:
"""Raises TypeError as body parts should be consumed via write().
This is intentional: BodyPartReader payloads are designed for streaming
large data (potentially gigabytes) and must be consumed only once via
the write() method to avoid memory exhaustion. They cannot be buffered
in memory for reuse.
"""
raise TypeError("Unable to read body part as bytes. Use write() to consume.")
async def write(self, writer: AbstractStreamWriter) -> None:
field = self._value
while chunk := await field.read_chunk(size=DEFAULT_CHUNK_SIZE):
async for d in field.decode_iter(chunk):
await writer.write(d)
View on GitHub (pinned to c0ef574e29)
Solutions
- Do not call decode() on streaming payloads — consume them via `await payload.write(writer)` instead.
- If you need bytes, switch to a non-streaming payload (BytesPayload) by first reading the part into memory: `data = await part.read(decode=True)`.
- Type-check with isinstance(payload, BodyPartReaderPayload) before calling decode() in generic code.
Example fix
// before
text = payload.decode()
// after
buf = io.BytesIO()
await payload.write(StreamWriter(buf)) # stream-consume instead
text = buf.getvalue().decode('utf-8')
Defensive patterns
Strategy: type-guard
Validate before calling
from aiohttp.multipart import BodyPartReaderPayload
if isinstance(payload, BodyPartReaderPayload):
raise TypeError('use write() to consume streaming payloads') Type guard
from aiohttp.multipart import BodyPartReaderPayload
def is_streaming_payload(p) -> bool:
return isinstance(p, BodyPartReaderPayload) Try / catch
try:
text = payload.decode()
except TypeError:
# streaming payload — consume via write()
buf = io.BytesIO()
await payload.write(StreamWriter(buf))
text = buf.getvalue().decode('utf-8') Prevention
- Never call decode()/as_bytes() on payloads of unknown type without an isinstance check.
- In generic middleware, branch on BodyPartReaderPayload before buffering.
- Prefer the write() contract for all payload consumption.
When it happens
Trigger: Calling `.decode()` on a payload obtained from a BodyPartReader (e.g. when a BodyPartReader is registered as a payload via @payload_type and then someone calls payload.decode()). Happens in generic payload-handling code that assumes all Payload subclasses support decode().
Common situations: Generic middleware that calls `.decode()` on every payload; test helpers serializing payloads to strings; copying a BodyPartReader into another request body via a path that tries to buffer the whole thing.
Related errors
- Unable to read body part as bytes. Use write() to consume.
- Only io.IOBase, multidict and (name, file) pairs allowed, us
- Can not serialize value type: %r headers: %r value: %r
- Could not find starting boundary {self._boundary!r}
- Cannot create payload from %r
AI-assisted analysis of aio-libs/aiohttp@c0ef574e29 (2026-08-04).
Data as JSON: /data/errors/9a1938c9700e73c1.json.
Report an issue: GitHub.