Repository navigation
io.BytesIO.truncate does not work as advertised #71448
Description
Activity
% python3.6 -c "import io; b=io.BytesIO(); assert b.truncate(42) == 42; assert len(b.getbuffer()) == 42, 'expected length 42, got {}'.format(len(b.getbuffer()))" Traceback (most recent call last): File "<string>", line 1, in <module> AssertionError: expected length 42, got 0The documentation [0] says that truncate can extend objects, and there is no indication that BytesIO does not support that. As demonstrated, truncate returns the new size, but the buffer obtained from that BytesIO is of size zero (likewise, b.getvalue() returns b''.
0: https://docs.python.org/3.6/library/io.html#io.IOBase.truncate
Reacted by James E. A. and RayKoopa- addedstdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or errorAn unexpected behavior, bug, or error
on Jun 7, 2016 BytesIO is supposed to implement IOBase. I would treat this as a bug in existing versions too.
Is this a bug or a documentation matter? Inspecting BytesIO.truncate's code, it does resizing similar to list, this seems to be a designed feature, which conflicts with the documented behaviour.
FWIW, I consider the documented behavior a feature. My use case is to allocate a BytesIO object with a given size, obtain a view to its buffer, and write to it from a c library.
I'm willing to try to fix this behavior.
I just want to check that this would not be considered breaking backwards compatibility. I can imagine in theory some code relying on it, but I would say that it would be relying on a bug. If some code is passed BytesIO in place of a file, then the current behavior is clearly undesirable. If some code specifically uses BytesIO and relies on this... I guess this can happen, but should be very rare and contrary to widely documented behavior. So it seems ok to just fix this, but I'm not very familiar with how such changes are usually handled in cPython, so I'd like to get approval from someone experienced.
Still an issue.
truncatereturns a nonsensical result that does not represent its new buffer size. So even if you check it - you're being lied to.I built a prototype of this new feature: https://github.com/python/cpython/compare/main...cmaloney:cpython:gh_71488_exp?expand=1.
@serhiy-storchaka if that looks like a reasonable change to you I'll add the NEWS and work into a full PR.
- addedtype-featureA feature request or enhancementA feature request or enhancementand removedtype-bugAn unexpected behavior, bug, or errorAn unexpected behavior, bug, or error
on Jun 17, 2026 Implemented the missing behavior, truncate which extends, in #152252 which is ready for review.
Reacted by RayKoopa
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
Linked PRs