summaryrefslogtreecommitdiff
path: root/numpy
diff options
context:
space:
mode:
authorLeon Weber <leon@leonweber.de>2013-05-23 19:24:28 +0200
committerLeon Weber <leon@leonweber.de>2013-05-29 15:35:45 +0200
commitfc4ade26312bd66474834aa0bee42265e7e15353 (patch)
treef359efccf95e83fa8f281f3c14bf39d621149b56 /numpy
parent8ff5e37bff03925da4c1b121b38188f9fd779b4d (diff)
downloadnumpy-fc4ade26312bd66474834aa0bee42265e7e15353.tar.gz
ENH: Fix SyntaxError when matrix() is called with invalid string
The numpy.matrix constructor uses eval(str.translate(table)) to convert input strings to numeric matrix contents. str.translate(table) will return empty string if str consists only of invalid characters, causing SyntaxError in eval(). This is confusing, as one would expect an exception like TypeError when trying to construct a matrix from invalid input. This fix makes sure eval() is only called if str is not empty and TypeError is raised otherwise.
Diffstat (limited to 'numpy')
-rw-r--r--numpy/matrixlib/defmatrix.py13
-rw-r--r--numpy/matrixlib/tests/test_defmatrix.py4
2 files changed, 15 insertions, 2 deletions
diff --git a/numpy/matrixlib/defmatrix.py b/numpy/matrixlib/defmatrix.py
index 080e83286..1ca835af2 100644
--- a/numpy/matrixlib/defmatrix.py
+++ b/numpy/matrixlib/defmatrix.py
@@ -19,7 +19,12 @@ if sys.version_info[0] >= 3:
return None
_table = _NumCharTable()
def _eval(astr):
- return eval(astr.translate(_table))
+ str_ = astr.translate(_table)
+ if not str_:
+ raise TypeError("Invalid data string supplied: " + astr)
+ else:
+ return eval(str_)
+
else:
_table = [None]*256
for k in range(256):
@@ -34,7 +39,11 @@ else:
del k
def _eval(astr):
- return eval(astr.translate(_table,_todelete))
+ str_ = astr.translate(_table,_todelete)
+ if not str_:
+ raise TypeError("Invalid data string supplied: " + astr)
+ else:
+ return eval(str_)
def _convert_from_string(data):
rows = data.split(';')
diff --git a/numpy/matrixlib/tests/test_defmatrix.py b/numpy/matrixlib/tests/test_defmatrix.py
index bc2b747e7..0cf284b64 100644
--- a/numpy/matrixlib/tests/test_defmatrix.py
+++ b/numpy/matrixlib/tests/test_defmatrix.py
@@ -31,6 +31,10 @@ class TestCtor(TestCase):
mvec = matrix(vec)
assert_(mvec.shape == (1,5))
+ def test_exceptions(self):
+ # Check for TypeError when called with invalid string data.
+ assert_raises(TypeError, matrix, "invalid")
+
def test_bmat_nondefault_str(self):
A = array([[1,2],[3,4]])
B = array([[5,6],[7,8]])