Skip to content

Commit 06e9ad2

Browse files
committed
fix csv2rec roundtrip for funky strings, too
svn path=/trunk/matplotlib/; revision=4749
1 parent f12c09d commit 06e9ad2

File tree

2 files changed

+25
-12
lines changed

2 files changed

+25
-12
lines changed

lib/matplotlib/mlab.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -2236,11 +2236,15 @@ def toval(self, x):
22362236
return repr(x)
22372237

22382238

2239+
class FormatString2(FormatObj):
2240+
def tostr(self, x):
2241+
val = repr(x)
2242+
return val[1:-1]
2243+
22392244
class FormatString(FormatObj):
22402245
def tostr(self, x):
22412246
return '"%r"'%self.toval(x)
22422247

2243-
22442248
class FormatFormatStr(FormatObj):
22452249
def __init__(self, fmt):
22462250
self.fmt = fmt
@@ -2297,7 +2301,7 @@ def __init__(self, fmt='%Y-%m-%d %H:%M:%S'):
22972301
npy.float32 : FormatFloat(),
22982302
npy.float64 : FormatFloat(),
22992303
npy.object_ : FormatObj(),
2300-
npy.string_ : FormatObj(),
2304+
npy.string_ : FormatString2(),
23012305
}
23022306

23032307
def get_formatd(r, formatd=None):

unit/mlab_unit.py

+19-10
Original file line numberDiff line numberDiff line change
@@ -13,25 +13,34 @@ def test_csv2rec_closefile(self):
1313
self.failIf( fh.closed )
1414

1515
def test_csv2rec_roundtrip(self):
16-
# Make sure double-precision floats pass through.
16+
17+
# Make sure double-precision floats and strings pass through a
18+
# roundtrip unaltered.
1719

1820
# A bug in numpy (fixed in r4602) meant that numpy scalars
1921
# lost precision when passing through repr(). csv2rec was
2022
# affected by this. This test will only pass on numpy >=
2123
# 1.0.5.
22-
ra=numpy.rec.array([(123, 1197346475.0137341), (456, 123.456)],
23-
dtype=[('a', '<i8'), ('b', '<f8')])
24-
rec2csv_closes_files = True
25-
if rec2csv_closes_files:
26-
fh = 'mlab_unit_tmp.csv'
27-
else:
28-
fh = StringIO.StringIO()
24+
ra=numpy.rec.array([(123, 1197346475.0137341, 'a,bc'),
25+
(456, 123.456, 'd\'ef'),
26+
(789, 0.000000001, 'ghi'),
27+
],
28+
dtype=[('a', '<i8'), ('b', '<f8'), ('c', '|S3')])
29+
fh = StringIO.StringIO()
2930
mlab.rec2csv( ra, fh )
30-
if not rec2csv_closes_files:
31+
fh.seek(0)
32+
if 0:
33+
print 'CSV contents:','-'*40
34+
print fh.read()
35+
print '-'*40
3136
fh.seek(0)
3237
ra2 = mlab.csv2rec(fh)
38+
fh.close()
3339
for name in ra.dtype.names:
34-
#print name, repr(ra[name]), repr(ra2[name])
40+
if 0:
41+
print name, repr(ra[name]), repr(ra2[name])
42+
dt = ra.dtype[name]
43+
print 'repr(dt.type)',repr(dt.type)
3544
self.failUnless( numpy.all(ra[name] == ra2[name]) ) # should not fail with numpy 1.0.5
3645

3746
if __name__=='__main__':

0 commit comments

Comments
 (0)