Debian Codegraph @

mypyc/test-data/run-functions.test

raw
1 # Test cases for functions and calls (compile and run)
2
3 [case testCallTrivialFunction]
4 def f(x: int) -> int:
5 return x
6 [file driver.py]
7 from native import f
8 print(f(3))
9 print(f(-157))
10 print(f(10**20))
11 print(f(-10**20))
12 [out]
13 3
14 -157
15 100000000000000000000
16 -100000000000000000000
17
18 [case testRecursiveFibonacci]
19 def fib(n: int) -> int:
20 if n <= 1:
21 return 1
22 else:
23 return fib(n - 1) + fib(n - 2)
24 [file driver.py]
25 from native import fib
26 print(fib(0))
27 print(fib(1))
28 print(fib(2))
29 print(fib(6))
30 [out]
31 1
32 1
33 2
34 13
35
36 [case testNestedFunctions]
37 from typing import Callable, List
38
39 def a() -> Callable[[], object]:
40 def inner() -> object:
41 return None
42 return inner
43
44 def b() -> Callable[[], Callable[[], str]]:
45 def first() -> Callable[[], str]:
46 def second() -> str:
47 return 'b.first.second: nested function'
48 return second
49 return first
50
51 def c(num: float) -> Callable[[str], str]:
52 def inner(s: str) -> str:
53 return s + '!'
54 return inner
55
56 def d(num: float) -> str:
57 def inner(s: str) -> str:
58 return s + '?'
59 a = inner('one')
60 b = inner('two')
61 return a
62
63 def e() -> int:
64 return 0
65
66 def f() -> int:
67 def inner() -> int:
68 return e()
69 return inner()
70
71 def g() -> Callable[[], Callable[[], int]]:
72 def inner() -> Callable[[], int]:
73 return e
74 return inner
75
76 def h(num: int) -> int:
77 def inner() -> int:
78 return num
79 return inner()
80
81 def i() -> int:
82 num = 3
83 def inner() -> int:
84 return num
85 return inner()
86
87 def j(num: int) -> int:
88 x = 1
89 y = 2
90 def inner() -> int:
91 nonlocal x
92 x = 3
93 return num + x + y
94 return inner()
95
96 def k() -> int:
97 num = 3
98 def inner() -> int:
99 nonlocal num
100 num = 5
101 return num
102 return inner() + num
103
104 def l() -> int:
105 num = 3
106 def inner() -> int:
107 num = 5
108 return num
109 return inner() + num
110
111 def m() -> Callable[[], int]:
112 num = 1
113 def inner() -> int:
114 num += 1
115 return num
116 num += 1
117 return inner
118
119 def n() -> int:
120 x = 1
121 def add_one() -> None:
122 x += 1
123 def add_two() -> None:
124 x += 2
125 add_one()
126 add_two()
127 return x
128
129 def triple(a: int) -> Callable[[], Callable[[int], int]]:
130 x = 1
131 def outer() -> Callable[[int], int]:
132 nonlocal x
133 x += 1
134 x += a
135 a += 1
136 def inner(b: int) -> int:
137 x += b
138 return x
139 return inner
140 return outer
141
142 def if_else(flag: int) -> str:
143 def dummy_function() -> str:
144 return 'if_else.dummy_function'
145
146 if flag < 0:
147 def inner() -> str:
148 return 'if_else.inner: first definition'
149 elif flag > 0:
150 def inner() -> str:
151 return 'if_else.inner: second definition'
152 else:
153 def inner() -> str:
154 return 'if_else.inner: third definition'
155 return inner()
156
157 def wrap(f: Callable[[], str]):
158 def inner():
159 return 'wrapped ' + f()
160 return inner
161
162 def if_else_all_decorated(flag: int) -> str:
163 def dummy_function() -> str:
164 return 'if_else.dummy_function'
165
166 if flag < 0:
167 @wrap
168 def inner() -> str:
169 return 'if_else.inner: first definition'
170 elif flag > 0:
171 @wrap
172 def inner() -> str:
173 return 'if_else.inner: second definition'
174 else:
175 @wrap
176 def inner() -> str:
177 return 'if_else.inner: third definition'
178 return inner()
179
180 def if_else_first_decorated(flag: int) -> str:
181 def dummy_function() -> str:
182 return 'if_else.dummy_function'
183
184 if flag < 0:
185 @wrap
186 def inner() -> str:
187 return 'if_else.inner: first definition'
188 elif flag > 0:
189 def inner() -> str:
190 return 'if_else.inner: second definition'
191 else:
192 def inner() -> str:
193 return 'if_else.inner: third definition'
194 return inner()
195
196 def if_else_all_but_first_decorated(flag: int) -> str:
197 def dummy_function() -> str:
198 return 'if_else.dummy_function'
199
200 if flag < 0:
201 def inner() -> str:
202 return 'if_else.inner: first definition'
203 elif flag > 0:
204 @wrap
205 def inner() -> str:
206 return 'if_else.inner: second definition'
207 else:
208 @wrap
209 def inner() -> str:
210 return 'if_else.inner: third definition'
211 return inner()
212
213 def for_loop() -> int:
214 def dummy_function() -> str:
215 return 'for_loop.dummy_function'
216
217 for i in range(5):
218 def inner(i: int) -> int:
219 return i
220 if i == 3:
221 return inner(i)
222 return 0
223
224 def while_loop() -> int:
225 def dummy_function() -> str:
226 return 'while_loop.dummy_function'
227
228 i = 0
229 while i < 5:
230 def inner(i: int) -> int:
231 return i
232 if i == 3:
233 return inner(i)
234 i += 1
235 return 0
236
237 def free_vars(foo: int, bar: int) -> int:
238 x = 1
239 y = 2
240 def g(): # type: ignore # missing type annotation for testing
241 nonlocal y
242 y = 3
243 nonlocal bar
244 bar += y
245 z = 3
246 g()
247 return bar
248
249 def lambdas(x: int, y: int) -> int:
250 s = lambda a, b: a + b + x + y
251 return s(1, 2)
252
253 def outer() -> str:
254 return 'outer: normal function'
255
256 def inner() -> str:
257 return 'inner: normal function'
258
259 class A:
260 def __init__(self, x: int) -> None:
261 self.x = x
262
263 def outer(self, num: int) -> int:
264 y = 5
265 def inner() -> int:
266 return self.x + y + num
267 return inner()
268
269 def o() -> int:
270 a = [0, 0]
271 b = 0
272 def b_incr() -> List[int]:
273 b += 10
274 return a
275 c = 0
276 def c_incr() -> int:
277 c += 1
278 return c
279
280 # x = 1, y = 1
281 x = y = c_incr()
282
283 # a = [2, 2], b = 20
284 b_incr()[0] = b_incr()[1] = c_incr()
285 # Should return 26.
286 return x + y + a[0] + a[1] + b
287
288 global_upvar = 20
289
290 toplevel_lambda = lambda x: 10 + global_upvar + x
291
292 [file driver.py]
293 from native import (
294 a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, triple, if_else, if_else_all_decorated,
295 if_else_first_decorated, if_else_all_but_first_decorated,
296 for_loop, while_loop, free_vars, lambdas, outer, inner, A, toplevel_lambda
297 )
298
299 assert a()() == None
300 assert b()()() == 'b.first.second: nested function'
301 assert c(5.0)('c') == 'c!'
302 assert d(4.0) == 'one?'
303 assert e() == 0
304 assert f() == 0
305 assert g()()() == 0
306 assert h(3) == 3
307 assert i() == 3
308 assert j(3) == 8
309 assert k() == 10
310 assert l() == 8
311 assert m()() == 3
312 assert n() == 4
313 assert o() == 26
314
315 triple_outer = triple(2)
316 triple_inner = triple_outer()
317
318 assert triple_inner(4) == 8
319 assert triple_inner(4) == 12
320 assert triple_outer()(4) == 20
321
322 assert if_else(-1) == 'if_else.inner: first definition'
323 assert if_else(1) == 'if_else.inner: second definition'
324 assert if_else(0) == 'if_else.inner: third definition'
325
326 assert if_else_all_decorated(-1) == 'wrapped if_else.inner: first definition'
327 assert if_else_all_decorated(1) == 'wrapped if_else.inner: second definition'
328 assert if_else_all_decorated(0) == 'wrapped if_else.inner: third definition'
329
330 assert if_else_first_decorated(-1) == 'wrapped if_else.inner: first definition'
331 assert if_else_first_decorated(1) == 'if_else.inner: second definition'
332 assert if_else_first_decorated(0) == 'if_else.inner: third definition'
333
334 assert if_else_all_but_first_decorated(-1) == 'if_else.inner: first definition'
335 assert if_else_all_but_first_decorated(1) == 'wrapped if_else.inner: second definition'
336 assert if_else_all_but_first_decorated(0) == 'wrapped if_else.inner: third definition'
337
338 assert for_loop() == 3
339 assert while_loop() == 3
340
341 assert free_vars(1, 2) == 5
342 assert lambdas(3, 4) == 10
343
344 assert outer() == 'outer: normal function'
345 assert inner() == 'inner: normal function'
346
347 assert A(3).outer(4) == 12
348
349 assert toplevel_lambda(5) == 35
350
351 [case testNestedFunctions2]
352 from typing import Callable
353
354 def outer() -> Callable[[], object]:
355 def inner() -> object:
356 return None
357 return inner
358
359 def first() -> Callable[[], Callable[[], str]]:
360 def second() -> Callable[[], str]:
361 def third() -> str:
362 return 'third: nested function'
363 return third
364 return second
365
366 def f1() -> int:
367 x = 1
368 def f2() -> int:
369 y = 2
370 def f3() -> int:
371 z = 3
372 return y
373 return f3()
374 return f2()
375
376 def outer_func() -> int:
377 def inner_func() -> int:
378 return x
379 x = 1
380 return inner_func()
381
382 def mutual_recursion(start : int) -> int:
383 def f1(k : int) -> int:
384 if k <= 0:
385 return 0
386 k -= 1
387 return f2(k)
388
389 def f2(k : int) -> int:
390 if k <= 0:
391 return 0
392 k -= 1
393 return f1(k)
394 return f1(start)
395
396 def topLayer() -> int:
397 def middleLayer() -> int:
398 def bottomLayer() -> int:
399 return x
400
401 return bottomLayer()
402
403 x = 1
404 return middleLayer()
405
406 def nest1() -> str:
407 def nest2() -> str:
408 def nest3() -> str:
409 def mut1(val: int) -> str:
410 if val <= 0:
411 return "bottomed"
412 val -= 1
413 return mut2(val)
414 def mut2(val: int) -> str:
415 if val <= 0:
416 return "bottomed"
417 val -= 1
418 return mut1(val)
419 return mut1(start)
420 return nest3()
421 start = 3
422 return nest2()
423
424 def uno(num: float) -> Callable[[str], str]:
425 def dos(s: str) -> str:
426 return s + '!'
427 return dos
428
429 def eins(num: float) -> str:
430 def zwei(s: str) -> str:
431 return s + '?'
432 a = zwei('eins')
433 b = zwei('zwei')
434 return a
435
436 def call_other_inner_func(a: int) -> int:
437 def foo() -> int:
438 return a + 1
439
440 def bar() -> int:
441 return foo()
442
443 def baz(n: int) -> int:
444 if n == 0:
445 return 0
446 return n + baz(n - 1)
447
448 return bar() + baz(a)
449
450 def inner() -> str:
451 return 'inner: normal function'
452
453 def second() -> str:
454 return 'second: normal function'
455
456 def third() -> str:
457 return 'third: normal function'
458
459 [file driver.py]
460 from native import (outer, inner, first, uno, eins, call_other_inner_func,
461 second, third, f1, outer_func, mutual_recursion, topLayer, nest1)
462
463 assert outer()() == None
464 assert inner() == 'inner: normal function'
465 assert first()()() == 'third: nested function'
466 assert uno(5.0)('uno') == 'uno!'
467 assert eins(4.0) == 'eins?'
468 assert call_other_inner_func(5) == 21
469 assert second() == 'second: normal function'
470 assert third() == 'third: normal function'
471 assert f1() == 2
472 assert outer_func() == 1
473 assert mutual_recursion(5) == 0
474 assert topLayer() == 1
475 assert nest1() == "bottomed"
476
477 [case testFunctionCallWithDefaultArgs]
478 from typing import Tuple, List, Optional, Callable, Any
479 def f(x: int, y: int = 3, s: str = "test", z: object = 5) -> Tuple[int, str]:
480 def inner() -> int:
481 return x + y
482 return inner(), s
483 def g() -> None:
484 assert f(2) == (5, "test")
485 assert f(s = "123", x = -2) == (1, "123")
486 def h(a: Optional[object] = None, b: Optional[str] = None) -> Tuple[object, Optional[str]]:
487 return (a, b)
488
489 def same(x: object = object()) -> object:
490 return x
491
492 a_lambda: Callable[..., Any] = lambda n=20: n
493
494 def nested_funcs(n: int) -> List[Callable[..., Any]]:
495 ls: List[Callable[..., Any]] = []
496 for i in range(n):
497 def f(i: int = i) -> int:
498 return i
499 ls.append(f)
500 return ls
501
502 def bool_default(x: bool = False, y: bool = True) -> str:
503 return str(x) + '-' + str(y)
504
505 [file driver.py]
506 from native import f, g, h, same, nested_funcs, a_lambda, bool_default
507 g()
508 assert f(2) == (5, "test")
509 assert f(s = "123", x = -2) == (1, "123")
510 assert h() == (None, None)
511 assert h(10) == (10, None)
512 assert h(b='a') == (None, 'a')
513 assert h(10, 'a') == (10, 'a')
514 assert same() == same()
515
516 assert [f() for f in nested_funcs(10)] == list(range(10))
517
518 assert a_lambda(10) == 10
519 assert a_lambda() == 20
520
521 assert bool_default() == 'False-True'
522 assert bool_default(True) == 'True-True'
523 assert bool_default(True, False) == 'True-False'
524
525 [case testMethodCallWithDefaultArgs]
526 from typing import Tuple, List
527 class A:
528 def f(self, x: int, y: int = 3, s: str = "test") -> Tuple[int, str]:
529 def inner() -> int:
530 return x + y
531 return inner(), s
532 def g() -> None:
533 a = A()
534 assert a.f(2) == (5, "test")
535 assert a.f(s = "123", x = -2) == (1, "123")
536 [file driver.py]
537 from native import A, g
538 g()
539 a = A()
540 assert a.f(2) == (5, "test")
541 assert a.f(s = "123", x = -2) == (1, "123")
542
543 [case testMethodCallOrdering]
544 class A:
545 def __init__(self, s: str) -> None:
546 print(s)
547 def f(self, x: 'A', y: 'A') -> None:
548 pass
549
550 def g() -> None:
551 A('A!').f(A('hello'), A('world'))
552 [file driver.py]
553 from native import g
554 g()
555 [out]
556 A!
557 hello
558 world
559
560 [case testPyMethodCall]
561 from typing import List
562 def f(x: List[int]) -> int:
563 return x.pop()
564 def g(x: List[int], y: List[int]) -> None:
565 x.extend(y)
566 [file driver.py]
567 from native import f, g
568 l = [1, 2]
569 assert f(l) == 2
570 g(l, [10])
571 assert l == [1, 10]
572 assert f(l) == 10
573 assert f(l) == 1
574 g(l, [11, 12])
575 assert l == [11, 12]
576
577 [case testMethodCallWithKeywordArgs]
578 from typing import Tuple
579 import testmodule
580 class A:
581 def echo(self, a: int, b: int, c: int) -> Tuple[int, int, int]:
582 return a, b, c
583 def test_native_method_call_with_kwargs() -> None:
584 a = A()
585 assert a.echo(1, c=3, b=2) == (1, 2, 3)
586 assert a.echo(c = 3, a = 1, b = 2) == (1, 2, 3)
587 def test_module_method_call_with_kwargs() -> None:
588 a = testmodule.A()
589 assert a.echo(1, c=3, b=2) == (1, 2, 3)
590 assert a.echo(c = 3, a = 1, b = 2) == (1, 2, 3)
591 [file testmodule.py]
592 from typing import Tuple
593 class A:
594 def echo(self, a: int, b: int, c: int) -> Tuple[int, int, int]:
595 return a, b, c
596 [file driver.py]
597 import native
598 native.test_native_method_call_with_kwargs()
599 native.test_module_method_call_with_kwargs()
600
601 [case testAnyCall]
602 from typing import Any
603 def call(f: Any) -> Any:
604 return f(1, 'x')
605 [file driver.py]
606 from native import call
607 def f(x, y):
608 return (x, y)
609 def g(x): pass
610
611 assert call(f) == (1, 'x')
612 for bad in g, 1:
613 try:
614 call(bad)
615 except TypeError:
616 pass
617 else:
618 assert False, bad
619
620 [case testCallableTypes]
621 from typing import Callable
622 def absolute_value(x: int) -> int:
623 return x if x > 0 else -x
624
625 def call_native_function(x: int) -> int:
626 return absolute_value(x)
627
628 def call_python_function(x: int) -> int:
629 return int(x)
630
631 def return_float() -> float:
632 return 5.0
633
634 def return_callable_type() -> Callable[[], float]:
635 return return_float
636
637 def call_callable_type() -> float:
638 f = return_callable_type()
639 return f()
640
641 def return_passed_in_callable_type(f: Callable[[], float]) -> Callable[[], float]:
642 return f
643
644 def call_passed_in_callable_type(f: Callable[[], float]) -> float:
645 return f()
646
647 [file driver.py]
648 from native import call_native_function, call_python_function, return_float, return_callable_type, call_callable_type, return_passed_in_callable_type, call_passed_in_callable_type
649 a = call_native_function(1)
650 b = call_python_function(1)
651 c = return_callable_type()
652 d = call_callable_type()
653 e = return_passed_in_callable_type(return_float)
654 f = call_passed_in_callable_type(return_float)
655 assert a == 1
656 assert b == 1
657 assert c() == 5.0
658 assert d == 5.0
659 assert e() == 5.0
660 assert f == 5.0
661
662 [case testKeywordArgs]
663 from typing import Tuple
664 import testmodule
665
666 def g(a: int, b: int, c: int) -> Tuple[int, int, int]:
667 return a, b, c
668
669 def test_call_native_function_with_keyword_args() -> None:
670 assert g(1, c = 3, b = 2) == (1, 2, 3)
671 assert g(c = 3, a = 1, b = 2) == (1, 2, 3)
672
673 def test_call_module_function_with_keyword_args() -> None:
674 assert testmodule.g(1, c = 3, b = 2) == (1, 2, 3)
675 assert testmodule.g(c = 3, a = 1, b = 2) == (1, 2, 3)
676
677 def test_call_python_function_with_keyword_args() -> None:
678 assert int("11", base=2) == 3
679
680 def test_call_lambda_function_with_keyword_args() -> None:
681 g = testmodule.get_lambda_function()
682 assert g(1, c = 3, b = 2) == (1, 2, 3)
683 assert g(c = 3, a = 1, b = 2) == (1, 2, 3)
684
685 [file testmodule.py]
686 from typing import Tuple
687
688 def g(a: int, b: int, c: int) -> Tuple[int, int, int]:
689 return a, b, c
690
691 def get_lambda_function():
692 return (lambda a, b, c: (a, b, c))
693
694 [file driver.py]
695 import native
696 native.test_call_native_function_with_keyword_args()
697 native.test_call_module_function_with_keyword_args()
698 native.test_call_python_function_with_keyword_args()
699 native.test_call_lambda_function_with_keyword_args()
700
701 [case testStarArgs]
702 from typing import Tuple
703
704 def g(a: int, b: int, c: int) -> Tuple[int, int, int]:
705 return a, b, c
706
707 def test_star_args() -> None:
708 assert g(*[1, 2, 3]) == (1, 2, 3)
709 assert g(*(1, 2, 3)) == (1, 2, 3)
710 assert g(*(1,), *[2, 3]) == (1, 2, 3)
711 assert g(*(), *(1,), *(), *(2,), *(3,), *()) == (1, 2, 3)
712 assert g(*range(3)) == (0, 1, 2)
713
714 [file driver.py]
715 import native
716 native.test_star_args()
717
718 [case testStar2Args]
719 from typing import Tuple
720
721 def g(a: int, b: int, c: int) -> Tuple[int, int, int]:
722 return a, b, c
723
724 def test_star2_args() -> None:
725 assert g(**{'a': 1, 'b': 2, 'c': 3}) == (1, 2, 3)
726 assert g(**{'c': 3, 'a': 1, 'b': 2}) == (1, 2, 3)
727 assert g(b=2, **{'a': 1, 'c': 3}) == (1, 2, 3)
728
729 def test_star2_args_bad(v: dict) -> bool:
730 return g(a=1, b=2, **v) == (1, 2, 3)
731 [file driver.py]
732 import native
733 native.test_star2_args()
734
735 # this should raise TypeError due to duplicate kwarg, but currently it doesn't
736 assert native.test_star2_args_bad({'b': 2, 'c': 3})
737
738 [case testStarAndStar2Args]
739 from typing import Tuple
740 def g(a: int, b: int, c: int) -> Tuple[int, int, int]:
741 return a, b, c
742
743 class C:
744 def g(self, a: int, b: int, c: int) -> Tuple[int, int, int]:
745 return a, b, c
746
747 def test_star_and_star2_args() -> None:
748 assert g(1, *(2,), **{'c': 3}) == (1, 2, 3)
749 assert g(*[1], **{'b': 2, 'c': 3}) == (1, 2, 3)
750 c = C()
751 assert c.g(1, *(2,), **{'c': 3}) == (1, 2, 3)
752 assert c.g(*[1], **{'b': 2, 'c': 3}) == (1, 2, 3)
753
754 [file driver.py]
755 import native
756 native.test_star_and_star2_args()
757
758 [case testAllTheArgCombinations]
759 from typing import Tuple
760 def g(a: int, b: int, c: int, d: int = -1) -> Tuple[int, int, int, int]:
761 return a, b, c, d
762
763 class C:
764 def g(self, a: int, b: int, c: int, d: int = -1) -> Tuple[int, int, int, int]:
765 return a, b, c, d
766
767 def test_all_the_arg_combinations() -> None:
768 assert g(1, *(2,), **{'c': 3}) == (1, 2, 3, -1)
769 assert g(*[1], **{'b': 2, 'c': 3, 'd': 4}) == (1, 2, 3, 4)
770 c = C()
771 assert c.g(1, *(2,), **{'c': 3}) == (1, 2, 3, -1)
772 assert c.g(*[1], **{'b': 2, 'c': 3, 'd': 4}) == (1, 2, 3, 4)
773
774 [file driver.py]
775 import native
776 native.test_all_the_arg_combinations()
777
778 [case testOverloads]
779 from typing import overload, Union, Tuple
780
781 @overload
782 def foo(x: int) -> int: ...
783
784 @overload
785 def foo(x: str) -> str: ...
786
787 def foo(x: Union[int, str]) -> Union[int, str]:
788 return x
789
790 class A:
791 @overload
792 def foo(self, x: int) -> int: ...
793
794 @overload
795 def foo(self, x: str) -> str: ...
796
797 def foo(self, x: Union[int, str]) -> Union[int, str]:
798 return x
799
800 def call1() -> Tuple[int, str]:
801 return (foo(10), foo('10'))
802 def call2() -> Tuple[int, str]:
803 x = A()
804 return (x.foo(10), x.foo('10'))
805
806 [file driver.py]
807 from native import *
808 assert call1() == (10, '10')
809 assert call2() == (10, '10')
810
811 [case testDecorators1]
812 from typing import Generator, Callable, Iterator
813 from contextlib import contextmanager
814
815 def a(f: Callable[[], None]) -> Callable[[], None]:
816 def g() -> None:
817 print('Entering')
818 f()
819 print('Exited')
820 return g
821
822 def b(f: Callable[[], None]) -> Callable[[], None]:
823 def g() -> None:
824 print('***')
825 f()
826 print('***')
827 return g
828
829 @contextmanager
830 def foo() -> Iterator[int]:
831 try:
832 print('started')
833 yield 0
834 finally:
835 print('finished')
836
837 @contextmanager
838 def catch() -> Iterator[None]:
839 try:
840 print('started')
841 yield
842 except IndexError:
843 print('index')
844 raise
845 except Exception:
846 print('lol')
847
848 def thing() -> None:
849 c()
850
851 @a
852 @b
853 def c() -> None:
854 @a
855 @b
856 def d() -> None:
857 print('d')
858 print('c')
859 d()
860
861 def hm() -> None:
862 x = [1]
863 with catch():
864 x[2]
865
866 [file driver.py]
867 from native import foo, c, thing, hm
868
869 with foo() as f:
870 print('hello')
871
872 c()
873 thing()
874 print('==')
875 try:
876 hm()
877 except IndexError:
878 pass
879 else:
880 assert False
881
882 [out]
883 started
884 hello
885 finished
886 Entering
887 ***
888 c
889 Entering
890 ***
891 d
892 ***
893 Exited
894 ***
895 Exited
896 Entering
897 ***
898 c
899 Entering
900 ***
901 d
902 ***
903 Exited
904 ***
905 Exited
906 ==
907 started
908 index
909
910 [case testDecoratorsMethods]
911 from typing import Any, Callable, Iterator, TypeVar
912 from contextlib import contextmanager
913
914 T = TypeVar('T')
915 def dec(f: T) -> T:
916 return f
917
918 def a(f: Callable[[Any], None]) -> Callable[[Any], None]:
919 def g(a: Any) -> None:
920 print('Entering')
921 f(a)
922 print('Exited')
923 return g
924
925 class A:
926 @a
927 def foo(self) -> None:
928 print('foo')
929
930 @contextmanager
931 def generator(self) -> Iterator[int]:
932 try:
933 print('contextmanager: entering')
934 yield 0
935 finally:
936 print('contextmanager: exited')
937
938 class Lol:
939 @staticmethod
940 def foo() -> None:
941 Lol.bar()
942 Lol.baz()
943
944 @staticmethod
945 @dec
946 def bar() -> None:
947 pass
948
949 @classmethod
950 @dec
951 def baz(cls) -> None:
952 pass
953
954 def inside() -> None:
955 with A().generator() as g:
956 print('hello!')
957
958 with A().generator() as g:
959 print('hello!')
960
961 def lol() -> None:
962 with A().generator() as g:
963 raise Exception
964
965 [file driver.py]
966 from native import A, lol
967
968 A.foo(A())
969 A().foo()
970 with A().generator() as g:
971 print('hello!')
972 try:
973 lol()
974 except:
975 pass
976 else:
977 assert False
978
979 [out]
980 contextmanager: entering
981 hello!
982 contextmanager: exited
983 Entering
984 foo
985 Exited
986 Entering
987 foo
988 Exited
989 contextmanager: entering
990 hello!
991 contextmanager: exited
992 contextmanager: entering
993 contextmanager: exited
994
995 [case testUnannotatedFunction]
996 def g(x: int) -> int:
997 return x * 2
998
999 def f(x):
1000 return g(x)
1001 [file driver.py]
1002 from native import f
1003 assert f(3) == 6
1004
1005 [case testUnannotatedModuleLevelInitFunction]
1006 # Ensure that adding an implicit `-> None` annotation only applies to `__init__`
1007 # _methods_ specifically (not module-level `__init__` functions).
1008 def __init__():
1009 return 42
1010 [file driver.py]
1011 from native import __init__
1012 assert __init__() == 42
1013
1014 [case testDifferentArgCountsFromInterpreted]
1015 # Test various signatures from interpreted code.
1016 def noargs() -> int:
1017 return 5
1018
1019 def onearg(x: int) -> int:
1020 return x + 1
1021
1022 def twoargs(x: int, y: str) -> int:
1023 return x + len(y)
1024
1025 def one_or_two(x: int, y: str = 'a') -> int:
1026 return x + len(y)
1027
1028 [file driver.py]
1029 from native import noargs, onearg, twoargs, one_or_two
1030 from testutil import assertRaises
1031
1032 assert noargs() == 5
1033 t = ()
1034 assert noargs(*t) == 5
1035 d = {}
1036 assert noargs(**d) == 5
1037 assert noargs(*t, **d) == 5
1038
1039 assert onearg(12) == 13
1040 assert onearg(x=8) == 9
1041 t = (1,)
1042 assert onearg(*t) == 2
1043 d = {'x': 5}
1044 assert onearg(**d) == 6
1045
1046 # Test a bogus call to twoargs before any correct calls are made
1047 with assertRaises(TypeError, "twoargs() missing required argument 'x' (pos 1)"):
1048 twoargs()
1049
1050 assert twoargs(5, 'foo') == 8
1051 assert twoargs(4, y='foo') == 7
1052 assert twoargs(y='foo', x=7) == 10
1053 t = (1, 'xy')
1054 assert twoargs(*t) == 3
1055 d = {'y': 'xy'}
1056 assert twoargs(2, **d) == 4
1057
1058 assert one_or_two(5) == 6
1059 assert one_or_two(x=3) == 4
1060 assert one_or_two(6, 'xy') == 8
1061 assert one_or_two(7, y='xy') == 9
1062 assert one_or_two(y='xy', x=2) == 4
1063 assert one_or_two(*t) == 3
1064 d = {'x': 5}
1065 assert one_or_two(**d) == 6
1066 assert one_or_two(y='xx', **d) == 7
1067 d = {'y': 'abc'}
1068 assert one_or_two(1, **d) == 4
1069
1070 with assertRaises(TypeError, 'noargs() takes at most 0 arguments (1 given)'):
1071 noargs(1)
1072 with assertRaises(TypeError, 'noargs() takes at most 0 keyword arguments (1 given)'):
1073 noargs(x=1)
1074
1075 with assertRaises(TypeError, "onearg() missing required argument 'x' (pos 1)"):
1076 onearg()
1077 with assertRaises(TypeError, 'onearg() takes at most 1 argument (2 given)'):
1078 onearg(1, 2)
1079 with assertRaises(TypeError, "onearg() missing required argument 'x' (pos 1)"):
1080 onearg(y=1)
1081 with assertRaises(TypeError, "onearg() takes at most 1 argument (2 given)"):
1082 onearg(1, y=1)
1083
1084 with assertRaises(TypeError, "twoargs() missing required argument 'x' (pos 1)"):
1085 twoargs()
1086 with assertRaises(TypeError, "twoargs() missing required argument 'y' (pos 2)"):
1087 twoargs(1)
1088 with assertRaises(TypeError, 'twoargs() takes at most 2 arguments (3 given)'):
1089 twoargs(1, 'x', 2)
1090 with assertRaises(TypeError, 'twoargs() takes at most 2 arguments (3 given)'):
1091 twoargs(1, 'x', y=2)
1092
1093 with assertRaises(TypeError, "one_or_two() missing required argument 'x' (pos 1)"):
1094 one_or_two()
1095 with assertRaises(TypeError, 'one_or_two() takes at most 2 arguments (3 given)'):
1096 one_or_two(1, 'x', 2)
1097 with assertRaises(TypeError, 'one_or_two() takes at most 2 arguments (3 given)'):
1098 one_or_two(1, 'x', y=2)
1099
1100 [case testComplicatedArgs]
1101 from typing import Tuple, Dict
1102
1103 def kwonly1(x: int = 0, *, y: int) -> Tuple[int, int]:
1104 return x, y
1105
1106 def kwonly2(*, x: int = 0, y: int) -> Tuple[int, int]:
1107 return x, y
1108
1109 def kwonly3(a: int, b: int = 0, *, y: int, x: int = 1) -> Tuple[int, int, int, int]:
1110 return a, b, x, y
1111
1112 def kwonly4(*, x: int, y: int) -> Tuple[int, int]:
1113 return x, y
1114
1115 def varargs1(*args: int) -> Tuple[int, ...]:
1116 return args
1117
1118 def varargs2(*args: int, **kwargs: int) -> Tuple[Tuple[int, ...], Dict[str, int]]:
1119 return args, kwargs
1120
1121 def varargs3(**kwargs: int) -> Dict[str, int]:
1122 return kwargs
1123
1124 def varargs4(a: int, b: int = 0,
1125 *args: int, y: int, x: int = 1,
1126 **kwargs: int) -> Tuple[Tuple[int, ...], Dict[str, int]]:
1127 return (a, b, *args), {'x': x, 'y': y, **kwargs}
1128
1129 class A:
1130 def f(self, x: int) -> Tuple[int, ...]:
1131 return (x,)
1132 def g(self, x: int) -> Tuple[Tuple[int, ...], Dict[str, int]]:
1133 return (x,), {}
1134
1135 class B(A):
1136 def f(self, *args: int) -> Tuple[int, ...]:
1137 return args
1138 def g(self, *args: int, **kwargs: int) -> Tuple[Tuple[int, ...], Dict[str, int]]:
1139 return args, kwargs
1140
1141 [file other.py]
1142 # This file is imported in both compiled and interpreted mode in order to
1143 # test both native calls and calls via the C API.
1144
1145 from native import (
1146 kwonly1, kwonly2, kwonly3, kwonly4,
1147 varargs1, varargs2, varargs3, varargs4,
1148 A, B
1149 )
1150
1151 # kwonly arg tests
1152 assert kwonly1(10, y=20) == (10, 20)
1153 assert kwonly1(y=20) == (0, 20)
1154
1155 assert kwonly2(x=10, y=20) == (10, 20)
1156 assert kwonly2(y=20) == (0, 20)
1157
1158 assert kwonly3(10, y=20) == (10, 0, 1, 20)
1159 assert kwonly3(a=10, y=20) == (10, 0, 1, 20)
1160 assert kwonly3(10, 30, y=20) == (10, 30, 1, 20)
1161 assert kwonly3(10, b=30, y=20) == (10, 30, 1, 20)
1162 assert kwonly3(a=10, b=30, y=20) == (10, 30, 1, 20)
1163
1164 assert kwonly3(10, x=40, y=20) == (10, 0, 40, 20)
1165 assert kwonly3(a=10, x=40, y=20) == (10, 0, 40, 20)
1166 assert kwonly3(10, 30, x=40, y=20) == (10, 30, 40, 20)
1167 assert kwonly3(10, b=30, x=40, y=20) == (10, 30, 40, 20)
1168 assert kwonly3(a=10, b=30, x=40, y=20) == (10, 30, 40, 20)
1169
1170 assert kwonly4(x=1, y=2) == (1, 2)
1171 assert kwonly4(y=2, x=1) == (1, 2)
1172
1173 # varargs tests
1174 assert varargs1() == ()
1175 assert varargs1(1, 2, 3) == (1, 2, 3)
1176 assert varargs1(1, *[2, 3, 4], 5, *[6, 7, 8], 9) == (1, 2, 3, 4, 5, 6, 7, 8, 9)
1177 assert varargs2(1, 2, 3) == ((1, 2, 3), {})
1178 assert varargs2(1, 2, 3, x=4) == ((1, 2, 3), {'x': 4})
1179 assert varargs2(x=4) == ((), {'x': 4})
1180 assert varargs3() == {}
1181 assert varargs3(x=4) == {'x': 4}
1182 assert varargs3(x=4, y=5) == {'x': 4, 'y': 5}
1183
1184 assert varargs4(-1, y=2) == ((-1, 0), {'x': 1, 'y': 2})
1185 assert varargs4(-1, 2, y=2) == ((-1, 2), {'x': 1, 'y': 2})
1186 assert varargs4(-1, 2, 3, y=2) == ((-1, 2, 3), {'x': 1, 'y': 2})
1187 assert varargs4(-1, 2, 3, x=10, y=2) == ((-1, 2, 3), {'x': 10, 'y': 2})
1188 assert varargs4(-1, x=10, y=2) == ((-1, 0), {'x': 10, 'y': 2})
1189 assert varargs4(-1, y=2, z=20) == ((-1, 0), {'x': 1, 'y': 2, 'z': 20})
1190 assert varargs4(-1, 2, y=2, z=20) == ((-1, 2), {'x': 1, 'y': 2, 'z': 20})
1191 assert varargs4(-1, 2, 3, y=2, z=20) == ((-1, 2, 3), {'x': 1, 'y': 2, 'z': 20})
1192 assert varargs4(-1, 2, 3, x=10, y=2, z=20) == ((-1, 2, 3), {'x': 10, 'y': 2, 'z': 20})
1193 assert varargs4(-1, x=10, y=2, z=20) == ((-1, 0), {'x': 10, 'y': 2, 'z': 20})
1194
1195 x = B() # type: A
1196 assert x.f(1) == (1,)
1197 assert x.g(1) == ((1,), {})
1198 # This one is really funny! When we make native calls we lose
1199 # track of which arguments are positional or keyword, so the glue
1200 # calls them all positional unless they are keyword only...
1201 # It would be possible to fix this by dynamically tracking which
1202 # arguments were passed by keyword (for example, by passing a bitmask
1203 # to functions indicating this), but paying a speed, size, and complexity
1204 # cost for something so deeply marginal seems like a bad choice.
1205 # assert x.g(x=1) == ((), {'x': 1})
1206
1207 [file driver.py]
1208 from testutil import assertRaises
1209 from native import (
1210 kwonly1, kwonly2, kwonly3, kwonly4,
1211 varargs1, varargs2, varargs3, varargs4,
1212 )
1213
1214 # Run the non-exceptional tests in both interpreted and compiled mode
1215 import other
1216 import other_interpreted
1217
1218
1219 # And the tests for errors at the interfaces in interpreted only
1220 with assertRaises(TypeError, "missing required keyword-only argument 'y'"):
1221 kwonly1()
1222 with assertRaises(TypeError, "takes at most 1 positional argument (2 given)"):
1223 kwonly1(10, 20)
1224
1225 with assertRaises(TypeError, "missing required keyword-only argument 'y'"):
1226 kwonly2()
1227 with assertRaises(TypeError, "takes no positional arguments"):
1228 kwonly2(10, 20)
1229
1230 with assertRaises(TypeError, "missing required argument 'a'"):
1231 kwonly3(b=30, x=40, y=20)
1232 with assertRaises(TypeError, "missing required keyword-only argument 'y'"):
1233 kwonly3(10)
1234
1235 with assertRaises(TypeError, "missing required keyword-only argument 'y'"):
1236 kwonly4(x=1)
1237 with assertRaises(TypeError, "missing required keyword-only argument 'x'"):
1238 kwonly4(y=1)
1239 with assertRaises(TypeError, "missing required keyword-only argument 'x'"):
1240 kwonly4()
1241
1242 with assertRaises(TypeError, "'x' is an invalid keyword argument for varargs1()"):
1243 varargs1(x=10)
1244 with assertRaises(TypeError, "'x' is an invalid keyword argument for varargs1()"):
1245 varargs1(1, x=10)
1246 with assertRaises(TypeError, "varargs3() takes no positional arguments"):
1247 varargs3(10)
1248 with assertRaises(TypeError, "varargs3() takes no positional arguments"):
1249 varargs3(10, x=10)
1250
1251 with assertRaises(TypeError, "varargs4() missing required argument 'a' (pos 1)"):
1252 varargs4()
1253 with assertRaises(TypeError, "varargs4() missing required keyword-only argument 'y'"):
1254 varargs4(1, 2)
1255 with assertRaises(TypeError, "varargs4() missing required keyword-only argument 'y'"):
1256 varargs4(1, 2, x=1)
1257 with assertRaises(TypeError, "varargs4() missing required keyword-only argument 'y'"):
1258 varargs4(1, 2, 3)
1259 with assertRaises(TypeError, "varargs4() missing required argument 'a' (pos 1)"):
1260 varargs4(y=20)
1261
1262 [case testDecoratorName]
1263 def dec(f): return f
1264
1265 @dec
1266 def foo(): pass
1267
1268 def test_decorator_name():
1269 assert foo.__name__ == "foo"
1270
1271 [case testLambdaArgToOverloaded]
1272 from lib import sub
1273
1274 def test_str_overload() -> None:
1275 assert sub('x', lambda m: m) == 'x'
1276
1277 def test_bytes_overload() -> None:
1278 assert sub(b'x', lambda m: m) == b'x'
1279
1280 [file lib.py]
1281 from typing import overload, Callable, TypeVar, Generic
1282
1283 T = TypeVar("T")
1284
1285 class Match(Generic[T]):
1286 def __init__(self, x: T) -> None:
1287 self.x = x
1288
1289 def group(self, n: int) -> T:
1290 return self.x
1291
1292 @overload
1293 def sub(s: str, f: Callable[[str], str]) -> str: ...
1294 @overload
1295 def sub(s: bytes, f: Callable[[bytes], bytes]) -> bytes: ...
1296 def sub(s, f):
1297 return f(s)
1298
1299 [case testContextManagerSpecialCase]
1300 from typing import Generator, Callable, Iterator
1301 from contextlib import contextmanager
1302
1303 @contextmanager
1304 def f() -> Iterator[None]:
1305 yield
1306
1307 def test_special_case() -> None:
1308 a = ['']
1309 with f():
1310 a.pop()
1311
1312 [case testUnpackKwargsCompiled]
1313 from typing import TypedDict
1314 from typing_extensions import Unpack
1315
1316 class Person(TypedDict):
1317 name: str
1318 age: int
1319
1320 def foo(**kwargs: Unpack[Person]) -> None:
1321 print(kwargs["name"])
1322
1323 def test_unpack() -> None:
1324 # This is not really supported yet, just test that we behave reasonably.
1325 foo(name='Jennifer', age=38)
1326 [typing fixtures/typing-full.pyi]
1327 [out]
1328 Jennifer
1329
1330 [case testNestedFunctionDunderDict312]
1331 import sys
1332
1333 def foo() -> None:
1334 def inner() -> str: return "bar"
1335 print(inner.__dict__) # type: ignore[attr-defined]
1336 inner.__dict__.update({"x": 1}) # type: ignore[attr-defined]
1337 print(inner.__dict__) # type: ignore[attr-defined]
1338 print(inner.x) # type: ignore[attr-defined]
1339
1340 def test_nested() -> None:
1341 if sys.version_info >= (3, 12): # type: ignore
1342 foo()
1343 [out]
1344 [out version>=3.12]
1345 {}
1346 {'x': 1}
1347 1
1348
1349 [case testFunctoolsUpdateWrapper]
1350 import functools
1351
1352 def bar() -> None:
1353 def inner() -> str: return "bar"
1354 functools.update_wrapper(inner, bar) # type: ignore
1355 print(inner.__dict__) # type: ignore
1356
1357 def test_update() -> None:
1358 bar()
1359 [typing fixtures/typing-full.pyi]
1360 [out]
1361 {'__module__': 'native', '__name__': 'bar', '__qualname__': 'bar', '__doc__': None, '__wrapped__': <built-in function bar>}
1362
1363 [case testCallNestedFunctionWithNamed]
1364 def f() -> None:
1365 def a() -> None:
1366 pass
1367 def b() -> None:
1368 a()
1369 b()
1370 [file driver.py]
1371 from native import f
1372 f()
1373
1374 [case testCallNestedFunctionWithLambda]
1375 def f(x: int) -> int:
1376 def inc(x: int) -> int:
1377 return x + 1
1378 return (lambda x: inc(x))(1)
1379 [file driver.py]
1380 from native import f
1381 print(f(1))
1382 [out]
1383 2
1384
1385 [case testStarArgFastPaths]
1386 from typing import Any, Mapping
1387 def fn(x: str, y: int) -> str:
1388 return x * y
1389 def star_tuple(*args: Any) -> str:
1390 return fn(*args)
1391 def star_list(args: list[Any]) -> str:
1392 return fn(*args)
1393 def star_generic(args: dict[Any, Any]) -> str:
1394 return fn(*args)
1395 def star2(**kwargs: Any) -> str:
1396 return fn(**kwargs)
1397 def star2_generic(kwargs: Mapping[Any, Any]) -> str:
1398 return fn(**kwargs)
1399
1400 def test_star_fastpath_tuple() -> None:
1401 assert star_tuple("a", 3) == "aaa"
1402 def test_star_fastpath_list() -> None:
1403 assert star_list(["a", 3]) == "aaa"
1404 def test_star_fastpath_generic() -> None:
1405 assert star_generic({"a": None, 3: None}) == "aaa"
1406 def test_star2_fastpath() -> None:
1407 assert star2(x="a", y=3) == "aaa"
1408 def test_star2_fastpath_generic() -> None:
1409 assert star2_generic({"x": "a", "y": 3}) == "aaa"
1410
1411 [case testLambdaInListComprehension]
1412 # Lambda inside list comprehension at module level
1413 funcs_list = [lambda x, i=i: x + i for i in range(3)]
1414
1415 def test_module_level() -> None:
1416 assert [f(10) for f in funcs_list] == [10, 11, 12]
1417
1418 def test_in_function() -> None:
1419 funcs = [lambda x, i=i: x + i for i in range(3)]
1420 assert [f(10) for f in funcs] == [10, 11, 12]
1421 # Different parameter name than loop variable
1422 funcs2 = [lambda x, n=i: x + n for i in range(3)]
1423 assert [f(10) for f in funcs2] == [10, 11, 12]
1424
1425 [case testLambdaInDictComprehension]
1426 # Lambda inside dict comprehension at module level
1427 funcs_dict = {k: lambda x, k=k: x + k for k in range(3)}
1428
1429 def test_module_level() -> None:
1430 assert funcs_dict[0](10) == 10
1431 assert funcs_dict[1](10) == 11
1432 assert funcs_dict[2](10) == 12
1433
1434 def test_in_function() -> None:
1435 d = {k: (lambda k=k: k * 2) for k in range(3)}
1436 assert d[0]() == 0
1437 assert d[1]() == 2
1438 assert d[2]() == 4
1439 # Different parameter name than loop variable
1440 d2 = {k: (lambda n=k: n * 2) for k in range(3)}
1441 assert d2[0]() == 0
1442 assert d2[1]() == 2
1443 assert d2[2]() == 4
1444
1445 [case testLambdaInSetComprehension]
1446 def test_set_comp() -> None:
1447 funcs = {(lambda i=i: i) for i in range(3)}
1448 results = {f() for f in funcs}
1449 assert results == {0, 1, 2}
1450 # Different parameter name than loop variable
1451 funcs2 = {(lambda n=i: n) for i in range(3)}
1452 results2 = {f() for f in funcs2}
1453 assert results2 == {0, 1, 2}
1454
1455 [case testLambdaInComprehensionCaptureOuter]
1456 # Lambda capturing both loop var and outer function var
1457 def test_capture_outer_and_loop() -> None:
1458 base = 100
1459 funcs = [lambda i=i: i + base for i in range(3)]
1460 assert funcs[0]() == 100
1461 assert funcs[1]() == 101
1462 assert funcs[2]() == 102
1463 # Different parameter name than loop variable
1464 funcs2 = [lambda n=i: n + base for i in range(3)]
1465 assert funcs2[0]() == 100
1466 assert funcs2[1]() == 101
1467 assert funcs2[2]() == 102
1468
1469 [case testLambdaInDictComprehensionLateBind]
1470 # Dict comprehension with late-binding lambda (no default arg)
1471 def test_dict_comp_late_bind() -> None:
1472 d = {name: (lambda: name) for name in ("a", "b")}
1473 # Late binding: all lambdas see the final value of 'name'
1474 assert d["a"]() == "b"
1475 assert d["b"]() == "b"
1476
1477 [case testLambdaInComprehensionClassLevel]
1478 # Lambda inside comprehension at class level
1479 from typing import ClassVar
1480 class Foo:
1481 A: ClassVar[object] = {name: (lambda: name) for name in ("a", "b")}
1482
1483 [file driver.py]
1484 from native import Foo
1485 assert Foo.A["a"]() == "b"
1486 assert Foo.A["b"]() == "b"
1487
1488 [case testLambdaInGeneratorExpression]
1489 def test_generator_with_lambda_default() -> None:
1490 result = list((lambda i=i: i * 2) for i in range(4))
1491 assert [f() for f in result] == [0, 2, 4, 6]
1492 # Different parameter name than loop variable
1493 result2 = list((lambda n=i: n * 2) for i in range(4))
1494 assert [f() for f in result2] == [0, 2, 4, 6]
1495
1496 [case testLambdaInComprehensionWithParamIterable]
1497 # Lambda inside comprehension where the iterable is a function parameter.
1498 # The comprehension scope must be able to read variables from the enclosing
1499 # function scope (not just the comprehension's own env class).
1500 from typing import List, Callable
1501
1502 def transform(items: List[int]) -> List[Callable[[], int]]:
1503 return [(lambda i=i: i * 2) for i in items] # type: ignore[misc]
1504
1505 def transform_different_name(items: List[int]) -> List[Callable[[], int]]:
1506 return [(lambda n=i: n * 2) for i in items] # type: ignore[misc]
1507
1508 def uses_multiple_params(items: List[str], sep: str) -> List[Callable[[], str]]:
1509 return [(lambda s=s: s + sep) for s in items] # type: ignore[misc]
1510
1511 def uses_multiple_params_different_name(items: List[str], sep: str) -> List[Callable[[], str]]:
1512 return [(lambda t=s: t + sep) for s in items] # type: ignore[misc]
1513
1514 def test_param_iterable() -> None:
1515 funcs = transform([1, 2, 3])
1516 assert [f() for f in funcs] == [2, 4, 6]
1517 # Different parameter name than loop variable
1518 funcs2 = transform_different_name([1, 2, 3])
1519 assert [f() for f in funcs2] == [2, 4, 6]
1520
1521 def test_multiple_params() -> None:
1522 funcs = uses_multiple_params(["a", "b"], "!")
1523 assert [f() for f in funcs] == ["a!", "b!"]
1524 # Different parameter name than loop variable
1525 funcs2 = uses_multiple_params_different_name(["a", "b"], "!")
1526 assert [f() for f in funcs2] == ["a!", "b!"]
1527
1528 [case testConcurrentFirstCallWithKeywordArgs]
1529 # Regression test for a free-threading data race in argument parser
1530 # initialization. The first call to a compiled function with keyword arguments
1531 # lazily initializes a static CPyArg_Parser and pushes it onto a global list.
1532 # When many threads race that first call on a free-threaded build, the
1533 # initialization and list insertion must be synchronized, or the runtime hits
1534 # a failed assertion (parser->next == NULL) and aborts.
1535 import sys
1536 import threading
1537
1538 # A pool of distinct functions, none of which is called before the concurrent
1539 # test. Each function's first call lazily initializes a static CPyArg_Parser,
1540 # and the test races that initialization across threads. Keyword arguments
1541 # force the call through the slow path that runs parser_init. Using many
1542 # functions gives many independent races per run, so the test reliably triggers
1543 # the bug on an unfixed free-threaded build instead of depending on a single
1544 # narrow timing window.
1545 def g0(a: int, b: int, c: int) -> int: return a + b + c
1546 def g1(a: int, b: int, c: int) -> int: return a + b + c
1547 def g2(a: int, b: int, c: int) -> int: return a + b + c
1548 def g3(a: int, b: int, c: int) -> int: return a + b + c
1549 def g4(a: int, b: int, c: int) -> int: return a + b + c
1550 def g5(a: int, b: int, c: int) -> int: return a + b + c
1551 def g6(a: int, b: int, c: int) -> int: return a + b + c
1552 def g7(a: int, b: int, c: int) -> int: return a + b + c
1553 def g8(a: int, b: int, c: int) -> int: return a + b + c
1554 def g9(a: int, b: int, c: int) -> int: return a + b + c
1555 def g10(a: int, b: int, c: int) -> int: return a + b + c
1556 def g11(a: int, b: int, c: int) -> int: return a + b + c
1557 def g12(a: int, b: int, c: int) -> int: return a + b + c
1558 def g13(a: int, b: int, c: int) -> int: return a + b + c
1559 def g14(a: int, b: int, c: int) -> int: return a + b + c
1560 def g15(a: int, b: int, c: int) -> int: return a + b + c
1561 def g16(a: int, b: int, c: int) -> int: return a + b + c
1562 def g17(a: int, b: int, c: int) -> int: return a + b + c
1563 def g18(a: int, b: int, c: int) -> int: return a + b + c
1564 def g19(a: int, b: int, c: int) -> int: return a + b + c
1565 def g20(a: int, b: int, c: int) -> int: return a + b + c
1566 def g21(a: int, b: int, c: int) -> int: return a + b + c
1567 def g22(a: int, b: int, c: int) -> int: return a + b + c
1568 def g23(a: int, b: int, c: int) -> int: return a + b + c
1569 def g24(a: int, b: int, c: int) -> int: return a + b + c
1570 def g25(a: int, b: int, c: int) -> int: return a + b + c
1571 def g26(a: int, b: int, c: int) -> int: return a + b + c
1572 def g27(a: int, b: int, c: int) -> int: return a + b + c
1573 def g28(a: int, b: int, c: int) -> int: return a + b + c
1574 def g29(a: int, b: int, c: int) -> int: return a + b + c
1575
1576 FUNCS = [g0, g1, g2, g3, g4, g5, g6, g7, g8, g9, g10, g11, g12, g13, g14,
1577 g15, g16, g17, g18, g19, g20, g21, g22, g23, g24, g25, g26, g27,
1578 g28, g29]
1579
1580 def is_gil_disabled() -> bool:
1581 return hasattr(sys, "_is_gil_enabled") and not sys._is_gil_enabled()
1582
1583 def test_concurrent_first_call() -> None:
1584 if not is_gil_disabled():
1585 # The race can only happen without the GIL.
1586 return
1587
1588 num_threads = 16
1589 barrier = threading.Barrier(num_threads)
1590 errors: list[str] = []
1591
1592 def run() -> None:
1593 # Line up all threads, then let them race freely through the list. The
1594 # first call to each function lazily initializes its parser, so every
1595 # function is a fresh race under real parallel pressure.
1596 barrier.wait()
1597 try:
1598 for fn in FUNCS:
1599 assert fn(a=1, b=2, c=3) == 6
1600 except BaseException as e:
1601 errors.append(repr(e))
1602
1603 threads = [threading.Thread(target=run) for _ in range(num_threads)]
1604 for t in threads:
1605 t.start()
1606 for t in threads:
1607 t.join()
1608
1609 assert not errors, errors