Keep a binary buffer open after TextIOWrapper.detach
A text wrapper normally owns its underlying binary stream. If the next stage needs that stream, detach() separates it from the wrapper and transfers cleanup responsibility to your code.
Run the example
Tested on Linux with Python 3.12.14. No third-party packages or network access are needed. In one Bash session, create a temporary working directory:
demo_start="$PWD"
demo_dir="$(mktemp -d)" || exit 1
cd -- "$demo_dir" || exit 1Save as demo_detached_buffer.py in that directory. Use this filename to avoid shadowing a standard-library module.
from io import BytesIO, TextIOWrapper
buffer = BytesIO()
text = TextIOWrapper(buffer, encoding="utf-8", newline="\n")
text.write("café\n")
text.flush()
binary = text.detach()
try:
print("Same buffer:", binary is buffer)
print("Buffer open:", not binary.closed)
binary.seek(0)
print("Bytes:", binary.read())
try:
text.write("again")
except ValueError:
print("Detached wrapper: unusable")
finally:
binary.close()
print("Buffer closed:", binary.closed)Run it:
python3 demo_detached_buffer.pyCaptured output:
Same buffer: True
Buffer open: True
Bytes: b'caf\xc3\xa9\n'
Detached wrapper: unusable
Buffer closed: TrueInterpret the result
The explicit flush makes the write boundary clear before detachment. The binary object remains open and must be closed by its new owner. The old wrapper is unusable after detachment; do not place it in a surrounding context that will later try to close it. This example writes only to memory. Detaching a reader is more subtle because buffering and decoding can read ahead, so it is not a general way to recover the next unread byte position. Not every text stream supports detachment.
See the version-specific Python reference for the API contract.
Clean up
In the same Bash session, remove the source file and then the empty working directory:
rm -- demo_detached_buffer.py
cd -- "$demo_start" || exit 1
rmdir -- "$demo_dir"
unset demo_start demo_dirIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.