Add _WriteStream protocol for MicroPython Buffer write methods
Summary
This PR implements reference stubs for the MicroPython Buffer protocol's extended write signature, as discussed in micropython/micropython#17938.
Changes
Added a new _WriteStream Protocol to reference/_mpy_shed/buffer_mp.pyi that defines three overloaded write method signatures:
# Basic write
stream.write(buf) -> int | None
# Write with maximum length
stream.write(buf, max_len) -> int | None
# Write with offset and maximum length
stream.write(buf, off, max_len) -> int | None
This extended signature is used throughout MicroPython but was previously undocumented in the type stubs. It's commonly found in:
- Socket objects (
socket.write) - UART interfaces (
machine.UART.write) - I2C/SPI interfaces (
machine.I2C.write,machine.SPI.write) - Async stream objects (
asyncio.Stream.write)
Design
- Uses Protocol (PEP 544) for structural subtyping, allowing any class with matching signatures to automatically conform without explicit inheritance
- Returns
int | Noneto match MicroPython's behavior where non-blocking operations returnNonewhen they would block - Leverages existing
AnyReadableBuftype alias for buffer protocol compatibility - Fully documented with docstrings for each signature variant
Backward Compatibility
No breaking changes. Existing AnyReadableBuf and AnyWritableBuf type aliases remain unchanged. The new protocol is exported from _mpy_shed for use in other modules.
Testing
- All modified
.pyifiles pass Python compilation - Pyright type checking passes with 0 new errors
- Created standalone tests demonstrating protocol usage with socket-like and UART-like implementations
Closes #<issue_number>
Original prompt
This section details on the original issue you should resolve
<issue_title>create mpy_shed/reference stubs for MicroPython Buffer protocol</issue_title> <issue_description> This is likely a good addition to reference_mpy_shed\buffer_mp.pyi but care must be taken to verify correct operation and conflicts.
Also need to determine how to work with , or replace AnyReadableBuf and AnyWritableBuf
The signature is:
stream.write(buf) stream.write(buf, max_len) stream.write(buf, off, max_len)I don't think this is actually documented anywhere, but it may be relied upon in some code.
Originally posted by @dpgeorge in https://github.com/micropython/micropython/pull/17938#discussion_r2329804709 </issue_description>
<agent_instructions>also chick if and how this can be used in other reference stubs.
changes MUST be restricted to the /reference folder </agent_instructions>
Comments on the Issue (you are @copilot in this section)
💬 Share your feedback on Copilot coding agent for the chance to win a $200 gift card! Click here to start the survey.