From 59a521ee07693cc5c58d68987691df4bcc9e48ff Mon Sep 17 00:00:00 2001 From: Sebastian Berg Date: Fri, 26 Apr 2019 09:21:32 -0700 Subject: [PATCH] BUG: (py2 only) fix unicode support for savetxt fmt string By now, all that is needed is to also allow unicode strings to pass through. Adds a test for the support which already succeeds on python3. Closes gh-4053 (replaces the old PR) --- numpy/lib/npyio.py | 2 +- numpy/lib/tests/test_io.py | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/numpy/lib/npyio.py b/numpy/lib/npyio.py index beeba13349ad..3414ecd81e8e 100644 --- a/numpy/lib/npyio.py +++ b/numpy/lib/npyio.py @@ -1390,7 +1390,7 @@ def first_write(self, v): if len(fmt) != ncol: raise AttributeError('fmt has wrong shape. %s' % str(fmt)) format = asstr(delimiter).join(map(asstr, fmt)) - elif isinstance(fmt, str): + elif isinstance(fmt, basestring): n_fmt_chars = fmt.count('%') error = ValueError('fmt has wrong number of %% formats: %s' % fmt) if n_fmt_chars == 1: diff --git a/numpy/lib/tests/test_io.py b/numpy/lib/tests/test_io.py index 835344429de1..f26f89f40db7 100644 --- a/numpy/lib/tests/test_io.py +++ b/numpy/lib/tests/test_io.py @@ -561,6 +561,19 @@ def test_unicode_stringstream(self): s.seek(0) assert_equal(s.read(), utf8 + '\n') + @pytest.mark.parametrize("fmt", [u"%f", b"%f"]) + @pytest.mark.parametrize("iotype", [StringIO, BytesIO]) + def test_unicode_and_bytes_fmt(self, fmt, iotype): + # string type of fmt should not matter, see also gh-4053 + a = np.array([1.]) + s = iotype() + np.savetxt(s, a, fmt=fmt) + s.seek(0) + if iotype is StringIO: + assert_equal(s.read(), u"%f\n" % 1.) + else: + assert_equal(s.read(), b"%f\n" % 1.) + class LoadTxtBase(object): def check_compressed(self, fopen, suffixes):