bpo-31778: Make ast.literal_eval() more strict. by serhiy-storchaka · Pull Request #4035 · python/cpython

@serhiy-storchaka

@serhiy-storchaka

Addition and subtraction of arbitrary numbers no longer allowed.

@serhiy-storchaka

dbieber

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks good to me. Two test suggestions inline.

I'm the one who filed https://bugs.python.org/issue31778, but I'm not a Python contributor, so presumably someone else needs to review this too.

right = _convert(node.right)
if isinstance(left, _NUM_TYPES) and isinstance(right, _NUM_TYPES):
left = _convert_signed_num(node.left)
right = _convert_num(node.right)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps it would be useful to add to the test assertRaises(ValueError, ast.literal_eval, '3 + (0 + 2j)') to catch unintended behavior changes to _convert_num in future edits.

self.assertEqual(ast.literal_eval('+6'), 6)
self.assertEqual(ast.literal_eval('-6'), -6)
self.assertEqual(ast.literal_eval('-6j+3'), 3-6j)
self.assertEqual(ast.literal_eval('3.25'), 3.25)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps it would also be useful to assertRaises(ValueError for an expression such as 1j+2j or 1+2j+3j.

@serhiy-storchaka

@serhiy-storchaka