Skip to content

Fix BodyPartReader.read() returning bytearray instead of bytes#12494

Closed
terminalchai wants to merge 1 commit intoaio-libs:masterfrom
terminalchai:fix/multipart-read-returns-bytes
Closed

Fix BodyPartReader.read() returning bytearray instead of bytes#12494
terminalchai wants to merge 1 commit intoaio-libs:masterfrom
terminalchai:fix/multipart-read-returns-bytes

Conversation

@terminalchai
Copy link
Copy Markdown

Problem

BodyPartReader.read() accumulates data into a bytearray internally but returns it directly without converting to bytes, violating the documented return type.

This affects both code paths in read():

  • decode=False: returns the raw bytearray accumulation
  • decode=True: returns the decoded bytearray accumulation

The result is a silent type error downstream. For example, trying to JSON-serialize the result fails:

data = await part.read()
json.dumps({'content': data})
# TypeError: Object of type bytearray is not JSON serializable

Fixes #12404.

Fix

Wrap both return values in bytes():

return bytes(result)

One-line change on each code path. Two regression tests added to tests/test_multipart.py covering both decode=False and decode=True.

BodyPartReader.read() accumulated data into a bytearray internally
but returned it directly, violating the documented return type of
bytes. This caused downstream TypeError when trying to JSON-serialize
the result, e.g. json.dumps({'filename': data}).

The same defect existed on both code paths in read():
- decode=False: returned the raw accumulation bytearray
- decode=True:  returned the decoded accumulation bytearray

Fix by wrapping both return values in bytes().

Fixes aio-libs#12404
@psf-chronographer psf-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label May 8, 2026
@codspeed-hq
Copy link
Copy Markdown

codspeed-hq Bot commented May 8, 2026

Merging this PR will not alter performance

✅ 67 untouched benchmarks
⏩ 4 skipped benchmarks1


Comparing terminalchai:fix/multipart-read-returns-bytes (3dda5cb) with master (7d534ab)

Open in CodSpeed

Footnotes

  1. 4 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot:chronographer:provided There is a change note present in this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: BodyPartReader.filename and read() leak bytearray instead of str/bytes, violating API contract and breaking JSON serialization

2 participants