Let's catch SyntaxError and turn it into an appropriate ValueError.

This commit is contained in:
Jeremy Fincher 2004-08-25 05:17:37 +00:00
parent 6b72890679
commit ec55e86c61
2 changed files with 8 additions and 1 deletions

View File

@ -491,7 +491,10 @@ def safeEval(s, namespace={'True': True, 'False': False, 'None': None}):
"""Evaluates s, safely. Useful for turning strings into tuples/lists/etc.
without unsafely using eval()."""
#print s, '::', stackTrace()
node = compiler.parse(s)
try:
node = compiler.parse(s)
except SyntaxError, e:
raise ValueError, 'Invalid string: %s.' % e
nodes = compiler.parse(s).node.nodes
if not nodes:
if node.__class__ is compiler.ast.Module:

View File

@ -341,6 +341,10 @@ class UtilsTest(SupyTestCase):
for s in ['lambda: 2', 'import foo', 'foo.bar']:
self.assertRaises(ValueError, utils.safeEval, s)
def testSafeEvalTurnsSyntaxErrorIntoValueError(self):
self.assertRaises(ValueError, utils.safeEval, '/usr/local/')
def testLines(self):
L = ['foo', 'bar', '#baz', ' ', 'biff']
self.assertEqual(list(utils.nonEmptyLines(L)),