New submission from Terry J. Reedy <tjre...@udel.edu>:

First, there is a minor documentation issue.
15.2.3.1. I/O Base Classes
class io.IOBase
seek(offset, whence=SEEK_SET) 
Change the stream position to the given byte offset

Since StringIO seeks by code units that should perhaps say 'byte or code unit 
offset' or a separate note should be added to the doc entry for StringIO.

>>> txt = StringIO('ab\U00010030')
>>> txt.seek(3)
3
>>> txt.write('x')
1
>>> txt.getvalue()
'ab\ud800x'

The behavior problem is that seeking for StringIO does not work relative to the 
current position or end.

IOError: Can't do nonzero cur-relative seeks
# Note: this message is wrong for end-relative seeks.

I presume this is inherited from an undocumented restriction on seeking with 
text streams, because chars *might* be variably sized. However, I do not think 
it should be. StringIO does not inherit the same reason for the restriction 
(certainly not on wide builds, and on narrow builds, seeking from the beginning 
is just as problematical). For StringIO, there is no option of 'opening in 
binary (byte) mode instead' as there is for disk files. Since a StringIO object 
is a wrapped array of fixed-size units, seeking from any position is as trivial 
as it is from the beginning. And again, the current docs imply that it should 
work.

Note that seeking from the beginning is not limited to the existing content. 
Instead, skipped areas are filled with nulls.

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

So that is not a reason to limit seeking from other positions either.

----------
components: Library (Lib)
messages: 143649
nosy: terry.reedy
priority: normal
severity: normal
stage: test needed
status: open
title: StringIO and seek()
type: behavior
versions: Python 3.2, Python 3.3

_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue12922>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to