bpo-36290: Fix keytword collision handling in AST node constructors (GH-12382)
(cherry picked from commit c73914a562580ae72048876cb42ed8e76e2c83f9)
Co-authored-by: Rémi Lapeyre <remi.lapeyre@lenstra.fr>
diff --git a/Lib/ast.py b/Lib/ast.py
index 0c88bcf..99a1148 100644
--- a/Lib/ast.py
+++ b/Lib/ast.py
@@ -483,6 +483,13 @@
return type.__instancecheck__(cls, inst)
def _new(cls, *args, **kwargs):
+ for key in kwargs:
+ if key not in cls._fields:
+ # arbitrary keyword arguments are accepted
+ continue
+ pos = cls._fields.index(key)
+ if pos < len(args):
+ raise TypeError(f"{cls.__name__} got multiple values for argument {key!r}")
if cls in _const_types:
return Constant(*args, **kwargs)
return Constant.__new__(cls, *args, **kwargs)
diff --git a/Lib/test/test_ast.py b/Lib/test/test_ast.py
index 8887558..486f2aa 100644
--- a/Lib/test/test_ast.py
+++ b/Lib/test/test_ast.py
@@ -387,6 +387,15 @@
self.assertRaises(TypeError, ast.Num, 1, None, 2)
self.assertRaises(TypeError, ast.Num, 1, None, 2, lineno=0)
+ # Arbitrary keyword arguments are supported
+ self.assertEqual(ast.Constant(1, foo='bar').foo, 'bar')
+ self.assertEqual(ast.Num(1, foo='bar').foo, 'bar')
+
+ with self.assertRaisesRegex(TypeError, "Num got multiple values for argument 'n'"):
+ ast.Num(1, n=2)
+ with self.assertRaisesRegex(TypeError, "Constant got multiple values for argument 'value'"):
+ ast.Constant(1, value=2)
+
self.assertEqual(ast.Num(42).n, 42)
self.assertEqual(ast.Num(4.25).n, 4.25)
self.assertEqual(ast.Num(4.25j).n, 4.25j)