bpo-35224: Reverse evaluation order of key: value in dict comprehensions (GH-14139)
… as proposed in PEP 572; key is now evaluated before value.
https://bugs.python.org/issue35224
diff --git a/Lib/test/test_dictcomps.py b/Lib/test/test_dictcomps.py
index afe68a8..927e310 100644
--- a/Lib/test/test_dictcomps.py
+++ b/Lib/test/test_dictcomps.py
@@ -81,6 +81,35 @@
compile("{x: y for y, x in ((1, 2), (3, 4))} += 5", "<test>",
"exec")
+ def test_evaluation_order(self):
+ expected = {
+ 'H': 'W',
+ 'e': 'o',
+ 'l': 'l',
+ 'o': 'd',
+ }
+
+ expected_calls = [
+ ('key', 'H'), ('value', 'W'),
+ ('key', 'e'), ('value', 'o'),
+ ('key', 'l'), ('value', 'r'),
+ ('key', 'l'), ('value', 'l'),
+ ('key', 'o'), ('value', 'd'),
+ ]
+
+ actual_calls = []
+
+ def add_call(pos, value):
+ actual_calls.append((pos, value))
+ return value
+
+ actual = {
+ add_call('key', k): add_call('value', v)
+ for k, v in zip('Hello', 'World')
+ }
+
+ self.assertEqual(actual, expected)
+ self.assertEqual(actual_calls, expected_calls)
if __name__ == "__main__":
unittest.main()
diff --git a/Lib/test/test_named_expressions.py b/Lib/test/test_named_expressions.py
index e15111c..f73e6fe 100644
--- a/Lib/test/test_named_expressions.py
+++ b/Lib/test/test_named_expressions.py
@@ -212,6 +212,11 @@
self.assertEqual(a, False)
+ def test_named_expression_assignment_16(self):
+ a, b = 1, 2
+ fib = {(c := a): (a := b) + (b := a + c) - b for __ in range(6)}
+ self.assertEqual(fib, {1: 2, 2: 3, 3: 5, 5: 8, 8: 13, 13: 21})
+
class NamedExpressionScopeTest(unittest.TestCase):
diff --git a/Lib/test/test_parser.py b/Lib/test/test_parser.py
index b830459..e5285c6 100644
--- a/Lib/test/test_parser.py
+++ b/Lib/test/test_parser.py
@@ -473,6 +473,8 @@
self.check_suite("foo(b := 2, a=1)")
self.check_suite("foo((b := 2), a=1)")
self.check_suite("foo(c=(b := 2), a=1)")
+ self.check_suite("{(x := C(i)).q: x for i in y}")
+
#
# Second, we take *invalid* trees and make sure we get ParserError