Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f853be9

Browse files
committed
Restore Python 2.1 StringIO.py behaviour: support concatenating
Unicode string snippets to larger Unicode strings. This fix should also go into Python 2.2.1.
1 parent 23105d5 commit f853be9

2 files changed

Lines changed: 23 additions & 5 deletions

File tree

Lib/StringIO.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
bytes that occupy space in the buffer.
2929
- There's a simple test set (see end of this file).
3030
"""
31-
31+
import types
3232
try:
3333
from errno import EINVAL
3434
except ImportError:
@@ -38,8 +38,10 @@
3838

3939
class StringIO:
4040
def __init__(self, buf = ''):
41-
# Force self.buf to be a string
42-
self.buf = str(buf)
41+
# Force self.buf to be a string or unicode
42+
if type(buf) is not types.UnicodeType:
43+
buf = str(buf)
44+
self.buf = buf
4345
self.len = len(buf)
4446
self.buflist = []
4547
self.pos = 0
@@ -135,8 +137,9 @@ def write(self, s):
135137
if self.closed:
136138
raise ValueError, "I/O operation on closed file"
137139
if not s: return
138-
# Force s to be a string
139-
s = str(s)
140+
# Force s to be a string or unicode
141+
if type(s) is not types.UnicodeType:
142+
s = str(s)
140143
if self.pos > self.len:
141144
self.buflist.append('\0'*(self.pos - self.len))
142145
self.len = self.pos

Lib/test/test_StringIO.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,21 @@ def test_iterator(self):
7171
class TestStringIO(TestGenericStringIO):
7272
MODULE = StringIO
7373

74+
def test_unicode(self):
75+
76+
# The StringIO module also supports concatenating Unicode
77+
# snippets to larger Unicode strings. This is tested by this
78+
# method. Note that cStringIO does not support this extension.
79+
80+
f = self.MODULE.StringIO()
81+
f.write(self._line[:6])
82+
f.seek(3)
83+
f.write(unicode(self._line[20:26]))
84+
f.write(unicode(self._line[52]))
85+
s = f.getvalue()
86+
self.assertEqual(s, unicode('abcuvwxyz!'))
87+
self.assertEqual(type(s), types.UnicodeType)
88+
7489
class TestcStringIO(TestGenericStringIO):
7590
MODULE = cStringIO
7691

0 commit comments

Comments
 (0)