bpo-39158: ast.literal_eval() doesn't support empty sets (GH-17742)

This commit is contained in:
Raymond Hettinger 2020-01-02 22:21:18 -07:00 committed by GitHub
parent 32f1443aa9
commit 4fcf5c12a3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 8 additions and 0 deletions

View File

@ -194,6 +194,9 @@ and classes for traversing abstract syntax trees:
.. versionchanged:: 3.2
Now allows bytes and set literals.
.. versionchanged:: 3.9
Now supports creating empty sets with ``'set()'``.
.. function:: get_docstring(node, clean=True)

View File

@ -83,6 +83,9 @@ def literal_eval(node_or_string):
return list(map(_convert, node.elts))
elif isinstance(node, Set):
return set(map(_convert, node.elts))
elif (isinstance(node, Call) and isinstance(node.func, Name) and
node.func.id == 'set' and node.args == node.keywords == []):
return set()
elif isinstance(node, Dict):
return dict(zip(map(_convert, node.keys),
map(_convert, node.values)))

View File

@ -891,6 +891,7 @@ Module(
self.assertEqual(ast.literal_eval('(True, False, None)'), (True, False, None))
self.assertEqual(ast.literal_eval('{1, 2, 3}'), {1, 2, 3})
self.assertEqual(ast.literal_eval('b"hi"'), b"hi")
self.assertEqual(ast.literal_eval('set()'), set())
self.assertRaises(ValueError, ast.literal_eval, 'foo()')
self.assertEqual(ast.literal_eval('6'), 6)
self.assertEqual(ast.literal_eval('+6'), 6)

View File

@ -0,0 +1 @@
ast.literal_eval() now supports empty sets.