Relative seeks on string IO
Terry Reedy
tjreedy at udel.edu
Tue Sep 6 16:49:19 EDT 2011
On 9/6/2011 3:18 AM, Pierre Quentel wrote:
> I am wondering why relative seeks fail on string IO in Python 3.2
Good question.
> from io import StringIO
> txt = StringIO('Favourite Worst Nightmare')
> txt.seek(8) # no problem with absolute seek
Please post code without non-code indents, like so:
from io import StringIO
txt = StringIO('Favourite Worst Nightmare')
txt.seek(8,0) # no problem with absolute seek
txt.seek(0,1) # 0 characters from current position ok, and useless
txt.seek(-2,2) # end-relative gives error message for cur-relative
so someone can copy and paste without deleting indents.
I verified with 3.2.2 on Win7. I am curious what 2.7 and 3.1 do.
What system are you using? Does it have a narrow or wide unicode build?
(IE, what is the value of sys.maxunicode?)
> txt.seek(2,1) # 2 characters from current position
>
> raises "IOError: Can't do nonzero cur-relative seeks" (tested with
> Python3.2.2 on WindowsXP)
>
> A seek relative to the end of the string IO raises the same IOError
> Is there any reason why relative seeks on string IO are not allowed in
> Python3.2, or is it a bug that could be fixed in a next version ?
Since StringIO seeks by fixed-size code units (depending on the build),
making seeking from the current position and end trivial, I consider
this a behavior bug. At minimum, it is a doc bug. I opened
http://bugs.python.org/issue12922
As noted there, I suspect the limitation in inherited from TextIOBase.
But I challenge that it should be.
I was somewhat surprised that seeking (from the start) is not limited to
the existing text. Seeking past the end fills in with nulls. (They are
typically a nuisance though.)
from io import StringIO
txt = StringIO('0123456789')
txt.seek(15,0) # no problem with absolute seek
txt.write('xxx')
s = txt.getvalue()
print(ord(s[12]))
# 0
--
Terry Jan Reedy
More information about the Python-list
mailing list