Skip to content

Commit b6f80d7

Browse files
Merge #26
26: warn for truncate r=ltratt a=nanjekyejoannah Use seek(0) before doing truncate(0) BytesIO.truncate() does not shift the file pointer, so we need to seek() to move the file pointer, otherwise writing after truncating will mess up the stream. s.truncate(0) -> s.seek(0) s.truncate(0) Co-authored-by: Joannah Nanjekye <[email protected]>
2 parents b825d1f + 100e234 commit b6f80d7

File tree

2 files changed

+12
-0
lines changed

2 files changed

+12
-0
lines changed

Lib/test/test_py3kwarn.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,14 @@ def test_file_xreadlines(self):
283283
with check_py3k_warnings() as w:
284284
self.assertWarning(f.xreadlines(), w, expected)
285285

286+
def test_bytesio_truncate(self):
287+
from io import BytesIO
288+
x = BytesIO(b'AAAAAA')
289+
expected = "BytesIO.truncate() does not shift the file pointer: use seek(0) before doing truncate(0)"
290+
self.assertWarning(x.truncate(0), w, expected)
291+
w.reset()
292+
self.assertNoWarning(x.truncate(-1), w)
293+
286294
def test_file_open(self):
287295
expected = ("The builtin 'file()'/'open()' function is not supported in 3.x, "
288296
"use the 'io.open()' function instead with the encoding keyword argument")

Modules/_io/bytesio.c

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -447,6 +447,10 @@ bytesio_truncate(bytesio *self, PyObject *args)
447447
size = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
448448
if (size == -1 && PyErr_Occurred())
449449
return NULL;
450+
if (size == 0 && PyErr_WarnPy3k_WithFix("BytesIO.truncate() does not shift the file pointer",
451+
"use seek(0) before doing truncate(0)", 1) < 0){
452+
return NULL;
453+
}
450454
}
451455
else if (arg == Py_None) {
452456
/* Truncate to current position if no argument is passed. */

0 commit comments

Comments
 (0)