Skip to content

Commit

Permalink
Merge python#26
Browse files Browse the repository at this point in the history
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 <jnanjeky@unb.ca>
  • Loading branch information
bors[bot] and nanjekyejoannah authored Apr 14, 2023
2 parents b825d1f + 100e234 commit b6f80d7
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
8 changes: 8 additions & 0 deletions Lib/test/test_py3kwarn.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,14 @@ def test_file_xreadlines(self):
with check_py3k_warnings() as w:
self.assertWarning(f.xreadlines(), w, expected)

def test_bytesio_truncate(self):
from io import BytesIO
x = BytesIO(b'AAAAAA')
expected = "BytesIO.truncate() does not shift the file pointer: use seek(0) before doing truncate(0)"
self.assertWarning(x.truncate(0), w, expected)
w.reset()
self.assertNoWarning(x.truncate(-1), w)

def test_file_open(self):
expected = ("The builtin 'file()'/'open()' function is not supported in 3.x, "
"use the 'io.open()' function instead with the encoding keyword argument")
Expand Down
4 changes: 4 additions & 0 deletions Modules/_io/bytesio.c
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,10 @@ bytesio_truncate(bytesio *self, PyObject *args)
size = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
if (size == -1 && PyErr_Occurred())
return NULL;
if (size == 0 && PyErr_WarnPy3k_WithFix("BytesIO.truncate() does not shift the file pointer",
"use seek(0) before doing truncate(0)", 1) < 0){
return NULL;
}
}
else if (arg == Py_None) {
/* Truncate to current position if no argument is passed. */
Expand Down

0 comments on commit b6f80d7

Please sign in to comment.