Debian Codegraph @

lib-python/3/test/test_named_expressions.py

raw symbols SCIP
1 import unittest
2
3 GLOBAL_VAR = None
4
5 class NamedExpressionInvalidTest(unittest.TestCase):
6
7 def test_named_expression_invalid_01(self):
8 code = """x := 0"""
9
10 with self.assertRaisesRegex(SyntaxError, "invalid syntax"):
11 exec(code, {}, {})
12
13 def test_named_expression_invalid_02(self):
14 code = """x = y := 0"""
15
16 with self.assertRaisesRegex(SyntaxError, "invalid syntax"):
17 exec(code, {}, {})
18
19 def test_named_expression_invalid_03(self):
20 code = """y := f(x)"""
21
22 with self.assertRaisesRegex(SyntaxError, "invalid syntax"):
23 exec(code, {}, {})
24
25 def test_named_expression_invalid_04(self):
26 code = """y0 = y1 := f(x)"""
27
28 with self.assertRaisesRegex(SyntaxError, "invalid syntax"):
29 exec(code, {}, {})
30
31 def test_named_expression_invalid_06(self):
32 code = """((a, b) := (1, 2))"""
33
34 with self.assertRaisesRegex(SyntaxError, "cannot use assignment expressions with tuple"):
35 exec(code, {}, {})
36
37 def test_named_expression_invalid_07(self):
38 code = """def spam(a = b := 42): pass"""
39
40 with self.assertRaisesRegex(SyntaxError, "invalid syntax"):
41 exec(code, {}, {})
42
43 def test_named_expression_invalid_08(self):
44 code = """def spam(a: b := 42 = 5): pass"""
45
46 with self.assertRaisesRegex(SyntaxError, "invalid syntax"):
47 exec(code, {}, {})
48
49 def test_named_expression_invalid_09(self):
50 code = """spam(a=b := 'c')"""
51
52 with self.assertRaisesRegex(SyntaxError, "invalid syntax"):
53 exec(code, {}, {})
54
55 def test_named_expression_invalid_10(self):
56 code = """spam(x = y := f(x))"""
57
58 with self.assertRaisesRegex(SyntaxError, "invalid syntax"):
59 exec(code, {}, {})
60
61 def test_named_expression_invalid_11(self):
62 code = """spam(a=1, b := 2)"""
63
64 with self.assertRaisesRegex(SyntaxError,
65 "positional argument follows keyword argument"):
66 exec(code, {}, {})
67
68 def test_named_expression_invalid_12(self):
69 code = """spam(a=1, (b := 2))"""
70
71 with self.assertRaisesRegex(SyntaxError,
72 "positional argument follows keyword argument"):
73 exec(code, {}, {})
74
75 def test_named_expression_invalid_13(self):
76 code = """spam(a=1, (b := 2))"""
77
78 with self.assertRaisesRegex(SyntaxError,
79 "positional argument follows keyword argument"):
80 exec(code, {}, {})
81
82 def test_named_expression_invalid_14(self):
83 code = """(x := lambda: y := 1)"""
84
85 with self.assertRaisesRegex(SyntaxError, "invalid syntax"):
86 exec(code, {}, {})
87
88 def test_named_expression_invalid_15(self):
89 code = """(lambda: x := 1)"""
90
91 with self.assertRaisesRegex(SyntaxError,
92 "cannot use assignment expressions with lambda"):
93 exec(code, {}, {})
94
95 def test_named_expression_invalid_16(self):
96 code = "[i + 1 for i in i := [1,2]]"
97
98 with self.assertRaisesRegex(SyntaxError, "invalid syntax"):
99 exec(code, {}, {})
100
101 def test_named_expression_invalid_17(self):
102 code = "[i := 0, j := 1 for i, j in [(1, 2), (3, 4)]]"
103
104 with self.assertRaisesRegex(SyntaxError,
105 "did you forget parentheses around the comprehension target?"):
106 exec(code, {}, {})
107
108 def test_named_expression_invalid_in_class_body(self):
109 code = """class Foo():
110 [(42, 1 + ((( j := i )))) for i in range(5)]
111 """
112
113 with self.assertRaisesRegex(SyntaxError,
114 "assignment expression within a comprehension cannot be used in a class body"):
115 exec(code, {}, {})
116
117 def test_named_expression_invalid_rebinding_list_comprehension_iteration_variable(self):
118 cases = [
119 ("Local reuse", 'i', "[i := 0 for i in range(5)]"),
120 ("Nested reuse", 'j', "[[(j := 0) for i in range(5)] for j in range(5)]"),
121 ("Reuse inner loop target", 'j', "[(j := 0) for i in range(5) for j in range(5)]"),
122 ("Unpacking reuse", 'i', "[i := 0 for i, j in [(0, 1)]]"),
123 ("Reuse in loop condition", 'i', "[i+1 for i in range(5) if (i := 0)]"),
124 ("Unreachable reuse", 'i', "[False or (i:=0) for i in range(5)]"),
125 ("Unreachable nested reuse", 'i',
126 "[(i, j) for i in range(5) for j in range(5) if True or (i:=10)]"),
127 ]
128 for case, target, code in cases:
129 msg = f"assignment expression cannot rebind comprehension iteration variable '{target}'"
130 with self.subTest(case=case):
131 with self.assertRaisesRegex(SyntaxError, msg):
132 exec(code, {}, {})
133
134 def test_named_expression_invalid_rebinding_list_comprehension_inner_loop(self):
135 cases = [
136 ("Inner reuse", 'j', "[i for i in range(5) if (j := 0) for j in range(5)]"),
137 ("Inner unpacking reuse", 'j', "[i for i in range(5) if (j := 0) for j, k in [(0, 1)]]"),
138 ]
139 for case, target, code in cases:
140 msg = f"comprehension inner loop cannot rebind assignment expression target '{target}'"
141 with self.subTest(case=case):
142 with self.assertRaisesRegex(SyntaxError, msg):
143 exec(code, {}) # Module scope
144 with self.assertRaisesRegex(SyntaxError, msg):
145 exec(code, {}, {}) # Class scope
146 with self.assertRaisesRegex(SyntaxError, msg):
147 exec(f"lambda: {code}", {}) # Function scope
148
149 def test_named_expression_invalid_list_comprehension_iterable_expression(self):
150 cases = [
151 ("Top level", "[i for i in (i := range(5))]"),
152 ("Inside tuple", "[i for i in (2, 3, i := range(5))]"),
153 ("Inside list", "[i for i in [2, 3, i := range(5)]]"),
154 ("Different name", "[i for i in (j := range(5))]"),
155 ("Lambda expression", "[i for i in (lambda:(j := range(5)))()]"),
156 ("Inner loop", "[i for i in range(5) for j in (i := range(5))]"),
157 ("Nested comprehension", "[i for i in [j for j in (k := range(5))]]"),
158 ("Nested comprehension condition", "[i for i in [j for j in range(5) if (j := True)]]"),
159 ("Nested comprehension body", "[i for i in [(j := True) for j in range(5)]]"),
160 ]
161 msg = "assignment expression cannot be used in a comprehension iterable expression"
162 for case, code in cases:
163 with self.subTest(case=case):
164 with self.assertRaisesRegex(SyntaxError, msg):
165 exec(code, {}) # Module scope
166 with self.assertRaisesRegex(SyntaxError, msg):
167 exec(code, {}, {}) # Class scope
168 with self.assertRaisesRegex(SyntaxError, msg):
169 exec(f"lambda: {code}", {}) # Function scope
170
171 def test_named_expression_invalid_rebinding_set_comprehension_iteration_variable(self):
172 cases = [
173 ("Local reuse", 'i', "{i := 0 for i in range(5)}"),
174 ("Nested reuse", 'j', "{{(j := 0) for i in range(5)} for j in range(5)}"),
175 ("Reuse inner loop target", 'j', "{(j := 0) for i in range(5) for j in range(5)}"),
176 ("Unpacking reuse", 'i', "{i := 0 for i, j in {(0, 1)}}"),
177 ("Reuse in loop condition", 'i', "{i+1 for i in range(5) if (i := 0)}"),
178 ("Unreachable reuse", 'i', "{False or (i:=0) for i in range(5)}"),
179 ("Unreachable nested reuse", 'i',
180 "{(i, j) for i in range(5) for j in range(5) if True or (i:=10)}"),
181 ]
182 for case, target, code in cases:
183 msg = f"assignment expression cannot rebind comprehension iteration variable '{target}'"
184 with self.subTest(case=case):
185 with self.assertRaisesRegex(SyntaxError, msg):
186 exec(code, {}, {})
187
188 def test_named_expression_invalid_rebinding_set_comprehension_inner_loop(self):
189 cases = [
190 ("Inner reuse", 'j', "{i for i in range(5) if (j := 0) for j in range(5)}"),
191 ("Inner unpacking reuse", 'j', "{i for i in range(5) if (j := 0) for j, k in {(0, 1)}}"),
192 ]
193 for case, target, code in cases:
194 msg = f"comprehension inner loop cannot rebind assignment expression target '{target}'"
195 with self.subTest(case=case):
196 with self.assertRaisesRegex(SyntaxError, msg):
197 exec(code, {}) # Module scope
198 with self.assertRaisesRegex(SyntaxError, msg):
199 exec(code, {}, {}) # Class scope
200 with self.assertRaisesRegex(SyntaxError, msg):
201 exec(f"lambda: {code}", {}) # Function scope
202
203 def test_named_expression_invalid_set_comprehension_iterable_expression(self):
204 cases = [
205 ("Top level", "{i for i in (i := range(5))}"),
206 ("Inside tuple", "{i for i in (2, 3, i := range(5))}"),
207 ("Inside list", "{i for i in {2, 3, i := range(5)}}"),
208 ("Different name", "{i for i in (j := range(5))}"),
209 ("Lambda expression", "{i for i in (lambda:(j := range(5)))()}"),
210 ("Inner loop", "{i for i in range(5) for j in (i := range(5))}"),
211 ("Nested comprehension", "{i for i in {j for j in (k := range(5))}}"),
212 ("Nested comprehension condition", "{i for i in {j for j in range(5) if (j := True)}}"),
213 ("Nested comprehension body", "{i for i in {(j := True) for j in range(5)}}"),
214 ]
215 msg = "assignment expression cannot be used in a comprehension iterable expression"
216 for case, code in cases:
217 with self.subTest(case=case):
218 with self.assertRaisesRegex(SyntaxError, msg):
219 exec(code, {}) # Module scope
220 with self.assertRaisesRegex(SyntaxError, msg):
221 exec(code, {}, {}) # Class scope
222 with self.assertRaisesRegex(SyntaxError, msg):
223 exec(f"lambda: {code}", {}) # Function scope
224
225 def test_named_expression_invalid_mangled_class_variables(self):
226 code = """class Foo:
227 def bar(self):
228 [[(__x:=2) for _ in range(2)] for __x in range(2)]
229 """
230
231 with self.assertRaisesRegex(SyntaxError,
232 "assignment expression cannot rebind comprehension iteration variable '__x'"):
233 exec(code, {}, {})
234
235
236 class NamedExpressionAssignmentTest(unittest.TestCase):
237
238 def test_named_expression_assignment_01(self):
239 (a := 10)
240
241 self.assertEqual(a, 10)
242
243 def test_named_expression_assignment_02(self):
244 a = 20
245 (a := a)
246
247 self.assertEqual(a, 20)
248
249 def test_named_expression_assignment_03(self):
250 (total := 1 + 2)
251
252 self.assertEqual(total, 3)
253
254 def test_named_expression_assignment_04(self):
255 (info := (1, 2, 3))
256
257 self.assertEqual(info, (1, 2, 3))
258
259 def test_named_expression_assignment_05(self):
260 (x := 1, 2)
261
262 self.assertEqual(x, 1)
263
264 def test_named_expression_assignment_06(self):
265 (z := (y := (x := 0)))
266
267 self.assertEqual(x, 0)
268 self.assertEqual(y, 0)
269 self.assertEqual(z, 0)
270
271 def test_named_expression_assignment_07(self):
272 (loc := (1, 2))
273
274 self.assertEqual(loc, (1, 2))
275
276 def test_named_expression_assignment_08(self):
277 if spam := "eggs":
278 self.assertEqual(spam, "eggs")
279 else: self.fail("variable was not assigned using named expression")
280
281 def test_named_expression_assignment_09(self):
282 if True and (spam := True):
283 self.assertTrue(spam)
284 else: self.fail("variable was not assigned using named expression")
285
286 def test_named_expression_assignment_10(self):
287 if (match := 10) == 10:
288 pass
289 else: self.fail("variable was not assigned using named expression")
290
291 def test_named_expression_assignment_11(self):
292 def spam(a):
293 return a
294 input_data = [1, 2, 3]
295 res = [(x, y, x/y) for x in input_data if (y := spam(x)) > 0]
296
297 self.assertEqual(res, [(1, 1, 1.0), (2, 2, 1.0), (3, 3, 1.0)])
298
299 def test_named_expression_assignment_12(self):
300 def spam(a):
301 return a
302 res = [[y := spam(x), x/y] for x in range(1, 5)]
303
304 self.assertEqual(res, [[1, 1.0], [2, 1.0], [3, 1.0], [4, 1.0]])
305
306 def test_named_expression_assignment_13(self):
307 length = len(lines := [1, 2])
308
309 self.assertEqual(length, 2)
310 self.assertEqual(lines, [1,2])
311
312 def test_named_expression_assignment_14(self):
313 """
314 Where all variables are positive integers, and a is at least as large
315 as the n'th root of x, this algorithm returns the floor of the n'th
316 root of x (and roughly doubling the number of accurate bits per
317 iteration):
318 """
319 a = 9
320 n = 2
321 x = 3
322
323 while a > (d := x // a**(n-1)):
324 a = ((n-1)*a + d) // n
325
326 self.assertEqual(a, 1)
327
328 def test_named_expression_assignment_15(self):
329 while a := False:
330 pass # This will not run
331
332 self.assertEqual(a, False)
333
334 def test_named_expression_assignment_16(self):
335 a, b = 1, 2
336 fib = {(c := a): (a := b) + (b := a + c) - b for __ in range(6)}
337 self.assertEqual(fib, {1: 2, 2: 3, 3: 5, 5: 8, 8: 13, 13: 21})
338
339 def test_named_expression_assignment_17(self):
340 a = [1]
341 element = a[b:=0]
342 self.assertEqual(b, 0)
343 self.assertEqual(element, a[0])
344
345 def test_named_expression_assignment_18(self):
346 class TwoDimensionalList:
347 def __init__(self, two_dimensional_list):
348 self.two_dimensional_list = two_dimensional_list
349
350 def __getitem__(self, index):
351 return self.two_dimensional_list[index[0]][index[1]]
352
353 a = TwoDimensionalList([[1], [2]])
354 element = a[b:=0, c:=0]
355 self.assertEqual(b, 0)
356 self.assertEqual(c, 0)
357 self.assertEqual(element, a.two_dimensional_list[b][c])
358
359
360
361 class NamedExpressionScopeTest(unittest.TestCase):
362
363 def test_named_expression_scope_01(self):
364 code = """def spam():
365 (a := 5)
366 print(a)"""
367
368 with self.assertRaisesRegex(NameError, "name 'a' is not defined"):
369 exec(code, {}, {})
370
371 def test_named_expression_scope_02(self):
372 total = 0
373 partial_sums = [total := total + v for v in range(5)]
374
375 self.assertEqual(partial_sums, [0, 1, 3, 6, 10])
376 self.assertEqual(total, 10)
377
378 def test_named_expression_scope_03(self):
379 containsOne = any((lastNum := num) == 1 for num in [1, 2, 3])
380
381 self.assertTrue(containsOne)
382 self.assertEqual(lastNum, 1)
383
384 def test_named_expression_scope_04(self):
385 def spam(a):
386 return a
387 res = [[y := spam(x), x/y] for x in range(1, 5)]
388
389 self.assertEqual(y, 4)
390
391 def test_named_expression_scope_05(self):
392 def spam(a):
393 return a
394 input_data = [1, 2, 3]
395 res = [(x, y, x/y) for x in input_data if (y := spam(x)) > 0]
396
397 self.assertEqual(res, [(1, 1, 1.0), (2, 2, 1.0), (3, 3, 1.0)])
398 self.assertEqual(y, 3)
399
400 def test_named_expression_scope_06(self):
401 res = [[spam := i for i in range(3)] for j in range(2)]
402
403 self.assertEqual(res, [[0, 1, 2], [0, 1, 2]])
404 self.assertEqual(spam, 2)
405
406 def test_named_expression_scope_07(self):
407 len(lines := [1, 2])
408
409 self.assertEqual(lines, [1, 2])
410
411 def test_named_expression_scope_08(self):
412 def spam(a):
413 return a
414
415 def eggs(b):
416 return b * 2
417
418 res = [spam(a := eggs(b := h)) for h in range(2)]
419
420 self.assertEqual(res, [0, 2])
421 self.assertEqual(a, 2)
422 self.assertEqual(b, 1)
423
424 def test_named_expression_scope_09(self):
425 def spam(a):
426 return a
427
428 def eggs(b):
429 return b * 2
430
431 res = [spam(a := eggs(a := h)) for h in range(2)]
432
433 self.assertEqual(res, [0, 2])
434 self.assertEqual(a, 2)
435
436 def test_named_expression_scope_10(self):
437 res = [b := [a := 1 for i in range(2)] for j in range(2)]
438
439 self.assertEqual(res, [[1, 1], [1, 1]])
440 self.assertEqual(a, 1)
441 self.assertEqual(b, [1, 1])
442
443 def test_named_expression_scope_11(self):
444 res = [j := i for i in range(5)]
445
446 self.assertEqual(res, [0, 1, 2, 3, 4])
447 self.assertEqual(j, 4)
448
449 def test_named_expression_scope_17(self):
450 b = 0
451 res = [b := i + b for i in range(5)]
452
453 self.assertEqual(res, [0, 1, 3, 6, 10])
454 self.assertEqual(b, 10)
455
456 def test_named_expression_scope_18(self):
457 def spam(a):
458 return a
459
460 res = spam(b := 2)
461
462 self.assertEqual(res, 2)
463 self.assertEqual(b, 2)
464
465 def test_named_expression_scope_19(self):
466 def spam(a):
467 return a
468
469 res = spam((b := 2))
470
471 self.assertEqual(res, 2)
472 self.assertEqual(b, 2)
473
474 def test_named_expression_scope_20(self):
475 def spam(a):
476 return a
477
478 res = spam(a=(b := 2))
479
480 self.assertEqual(res, 2)
481 self.assertEqual(b, 2)
482
483 def test_named_expression_scope_21(self):
484 def spam(a, b):
485 return a + b
486
487 res = spam(c := 2, b=1)
488
489 self.assertEqual(res, 3)
490 self.assertEqual(c, 2)
491
492 def test_named_expression_scope_22(self):
493 def spam(a, b):
494 return a + b
495
496 res = spam((c := 2), b=1)
497
498 self.assertEqual(res, 3)
499 self.assertEqual(c, 2)
500
501 def test_named_expression_scope_23(self):
502 def spam(a, b):
503 return a + b
504
505 res = spam(b=(c := 2), a=1)
506
507 self.assertEqual(res, 3)
508 self.assertEqual(c, 2)
509
510 def test_named_expression_scope_24(self):
511 a = 10
512 def spam():
513 nonlocal a
514 (a := 20)
515 spam()
516
517 self.assertEqual(a, 20)
518
519 def test_named_expression_scope_25(self):
520 ns = {}
521 code = """a = 10
522 def spam():
523 global a
524 (a := 20)
525 spam()"""
526
527 exec(code, ns, {})
528
529 self.assertEqual(ns["a"], 20)
530
531 def test_named_expression_variable_reuse_in_comprehensions(self):
532 # The compiler is expected to raise syntax error for comprehension
533 # iteration variables, but should be fine with rebinding of other
534 # names (e.g. globals, nonlocals, other assignment expressions)
535
536 # The cases are all defined to produce the same expected result
537 # Each comprehension is checked at both function scope and module scope
538 rebinding = "[x := i for i in range(3) if (x := i) or not x]"
539 filter_ref = "[x := i for i in range(3) if x or not x]"
540 body_ref = "[x for i in range(3) if (x := i) or not x]"
541 nested_ref = "[j for i in range(3) if x or not x for j in range(3) if (x := i)][:-3]"
542 cases = [
543 ("Rebind global", f"x = 1; result = {rebinding}"),
544 ("Rebind nonlocal", f"result, x = (lambda x=1: ({rebinding}, x))()"),
545 ("Filter global", f"x = 1; result = {filter_ref}"),
546 ("Filter nonlocal", f"result, x = (lambda x=1: ({filter_ref}, x))()"),
547 ("Body global", f"x = 1; result = {body_ref}"),
548 ("Body nonlocal", f"result, x = (lambda x=1: ({body_ref}, x))()"),
549 ("Nested global", f"x = 1; result = {nested_ref}"),
550 ("Nested nonlocal", f"result, x = (lambda x=1: ({nested_ref}, x))()"),
551 ]
552 for case, code in cases:
553 with self.subTest(case=case):
554 ns = {}
555 exec(code, ns)
556 self.assertEqual(ns["x"], 2)
557 self.assertEqual(ns["result"], [0, 1, 2])
558
559 def test_named_expression_global_scope(self):
560 sentinel = object()
561 global GLOBAL_VAR
562 def f():
563 global GLOBAL_VAR
564 [GLOBAL_VAR := sentinel for _ in range(1)]
565 self.assertEqual(GLOBAL_VAR, sentinel)
566 try:
567 f()
568 self.assertEqual(GLOBAL_VAR, sentinel)
569 finally:
570 GLOBAL_VAR = None
571
572 def test_named_expression_global_scope_no_global_keyword(self):
573 sentinel = object()
574 def f():
575 GLOBAL_VAR = None
576 [GLOBAL_VAR := sentinel for _ in range(1)]
577 self.assertEqual(GLOBAL_VAR, sentinel)
578 f()
579 self.assertEqual(GLOBAL_VAR, None)
580
581 def test_named_expression_nonlocal_scope(self):
582 sentinel = object()
583 def f():
584 nonlocal_var = None
585 def g():
586 nonlocal nonlocal_var
587 [nonlocal_var := sentinel for _ in range(1)]
588 g()
589 self.assertEqual(nonlocal_var, sentinel)
590 f()
591
592 def test_named_expression_nonlocal_scope_no_nonlocal_keyword(self):
593 sentinel = object()
594 def f():
595 nonlocal_var = None
596 def g():
597 [nonlocal_var := sentinel for _ in range(1)]
598 g()
599 self.assertEqual(nonlocal_var, None)
600 f()
601
602 def test_named_expression_scope_in_genexp(self):
603 a = 1
604 b = [1, 2, 3, 4]
605 genexp = (c := i + a for i in b)
606
607 self.assertNotIn("c", locals())
608 for idx, elem in enumerate(genexp):
609 self.assertEqual(elem, b[idx] + a)
610
611 def test_named_expression_scope_mangled_names(self):
612 class Foo:
613 def f(self_):
614 global __x1
615 __x1 = 0
616 [_Foo__x1 := 1 for a in [2]]
617 self.assertEqual(__x1, 1)
618 [__x1 := 2 for a in [3]]
619 self.assertEqual(__x1, 2)
620
621 Foo().f()
622 self.assertEqual(_Foo__x1, 2)
623
624 if __name__ == "__main__":
625 unittest.main()