Debian Codegraph @

mypyc/test-data/run-generators.test

raw
1 # Test cases for generators and yield (compile and run)
2
3 [case testYield]
4 from typing import Generator, Iterable, Union, Tuple, Dict
5
6 def yield_three_times() -> Iterable[int]:
7 yield 1
8 yield 2
9 yield 3
10
11 def yield_twice_and_return() -> Generator[int, None, int]:
12 yield 1
13 yield 2
14 return 4
15
16 def yield_while_loop() -> Generator[int, None, int]:
17 i = 0
18 while i < 5:
19 if i == 3:
20 return i
21 yield i
22 i += 1
23 return -1
24
25 def yield_for_loop() -> Iterable[int]:
26 l = [i for i in range(3)]
27 for i in l:
28 yield i
29
30 d = {k: None for k in range(3)}
31 for k in d:
32 yield k
33
34 for i in range(3):
35 yield i
36
37 for i in range(three()):
38 yield i
39
40 def yield_with_except() -> Generator[int, None, None]:
41 yield 10
42 try:
43 return
44 except:
45 print('Caught exception inside generator function')
46
47 def complex_yield(a: int, b: str, c: float) -> Generator[Union[str, int], None, float]:
48 x = 2
49 while x < a:
50 if x % 2 == 0:
51 dummy_var = 1
52 yield str(x) + ' ' + b
53 dummy_var = 1
54 else:
55 dummy_var = 1
56 yield x
57 dummy_var = 1
58 x += 1
59 return c
60
61 def yield_with_default(x: bool = False) -> Iterable[int]:
62 if x:
63 yield 0
64
65 def yield_dict_methods(d1: Dict[int, int],
66 d2: Dict[int, int],
67 d3: Dict[int, int]) -> Iterable[int]:
68 for k in d1.keys():
69 yield k
70 for k, v in d2.items():
71 yield k
72 yield v
73 for v in d3.values():
74 yield v
75
76 def three() -> int:
77 return 3
78
79 class A(object):
80 def __init__(self, x: int) -> None:
81 self.x = x
82
83 def generator(self) -> Iterable[int]:
84 yield self.x
85
86 def return_tuple() -> Generator[int, None, Tuple[int, int]]:
87 yield 0
88 return 1, 2
89
90 [file driver.py]
91 from native import (
92 yield_three_times,
93 yield_twice_and_return,
94 yield_while_loop,
95 yield_for_loop,
96 yield_with_except,
97 complex_yield,
98 yield_with_default,
99 A,
100 return_tuple,
101 yield_dict_methods,
102 )
103 from testutil import run_generator
104 from collections import defaultdict
105
106 assert run_generator(yield_three_times()) == ((1, 2, 3), None)
107 assert run_generator(yield_twice_and_return()) == ((1, 2), 4)
108 assert run_generator(yield_while_loop()) == ((0, 1, 2), 3)
109 assert run_generator(yield_for_loop()) == (tuple(4 * [i for i in range(3)]), None)
110 assert run_generator(yield_with_except()) == ((10,), None)
111 assert run_generator(complex_yield(5, 'foo', 1.0)) == (('2 foo', 3, '4 foo'), 1.0)
112 assert run_generator(yield_with_default()) == ((), None)
113 assert run_generator(A(0).generator()) == ((0,), None)
114 assert run_generator(return_tuple()) == ((0,), (1, 2))
115 assert run_generator(yield_dict_methods({}, {}, {})) == ((), None)
116 assert run_generator(yield_dict_methods({1: 2}, {3: 4}, {5: 6})) == ((1, 3, 4, 6), None)
117 dd = defaultdict(int, {0: 1})
118 assert run_generator(yield_dict_methods(dd, dd, dd)) == ((0, 0, 1, 1), None)
119
120 for i in yield_twice_and_return():
121 print(i)
122
123 for i in yield_while_loop():
124 print(i)
125
126 [out]
127 1
128 2
129 0
130 1
131 2
132
133 [case testYieldTryFinallyWith]
134 from typing import Generator, Any
135
136 class Thing:
137 def __init__(self, x: str) -> None:
138 self.x = x
139 def __enter__(self) -> str:
140 print('enter!', self.x)
141 if self.x == 'crash':
142 raise Exception('ohno')
143 return self.x
144 def __exit__(self, x: Any, y: Any, z: Any) -> None:
145 print('exit!', self.x, y)
146
147 def yield_try_finally() -> Generator[int, None, str]:
148 try:
149 yield 1
150 yield 2
151 return 'lol'
152 except Exception:
153 raise
154 finally:
155 print('goodbye!')
156
157 def yield_with(i: int) -> Generator[int, None, int]:
158 with Thing('a') as x:
159 yield 1
160 print("yooo?", x)
161 if i == 0:
162 yield 2
163 return 10
164 elif i == 1:
165 raise Exception('exception!')
166 return -1
167
168 [file driver.py]
169 from native import yield_try_finally, yield_with
170 from testutil import run_generator
171
172 print(run_generator(yield_try_finally(), p=True))
173 print(run_generator(yield_with(0), p=True))
174 print(run_generator(yield_with(1), p=True))
175 [out]
176 1
177 2
178 goodbye!
179 ((1, 2), 'lol')
180 enter! a
181 1
182 yooo? a
183 2
184 exit! a None
185 ((1, 2), 10)
186 enter! a
187 1
188 yooo? a
189 exit! a exception!
190 ((1,), 'exception!')
191
192 [case testYieldNested]
193 from typing import Callable, Generator, Iterator, TypeVar, overload
194
195 from testutil import run_generator
196
197 def normal(a: int, b: float) -> Callable:
198 def generator(x: int, y: str) -> Generator:
199 yield a
200 yield b
201 yield x
202 yield y
203 return generator
204
205 def generator(a: int) -> Generator:
206 def normal(x: int) -> int:
207 return a + x
208 for i in range(3):
209 yield normal(i)
210
211 def triple() -> Callable:
212 def generator() -> Generator:
213 x = 0
214 def inner() -> int:
215 x += 1
216 return x
217 while x < 3:
218 yield inner()
219 return generator
220
221 def another_triple() -> Callable:
222 def generator() -> Generator:
223 x = 0
224 def inner_generator() -> Generator:
225 x += 1
226 yield x
227 yield next(inner_generator())
228 return generator
229
230 def outer() -> Generator:
231 def recursive(n: int) -> Generator:
232 if n < 10:
233 for i in range(n):
234 yield i
235 return
236 for i in recursive(5):
237 yield i
238 return recursive(10)
239
240 def test_return_nested_generator() -> None:
241 assert run_generator(normal(1, 2.0)(3, '4.00')) == ((1, 2.0, 3, '4.00'), None)
242 assert run_generator(generator(1)) == ((1, 2, 3), None)
243 assert run_generator(triple()()) == ((1, 2, 3), None)
244 assert run_generator(another_triple()()) == ((1,), None)
245 assert run_generator(outer()) == ((0, 1, 2, 3, 4), None)
246
247 def call_nested(x: int) -> list[int]:
248 def generator() -> Iterator[int]:
249 n = int() + 2
250 yield x
251 yield n * x
252
253 a = []
254 for x in generator():
255 a.append(x)
256 return a
257
258 T = TypeVar("T")
259
260 def deco(f: T) -> T:
261 return f
262
263 def call_nested_decorated(x: int) -> list[int]:
264 @deco
265 def generator() -> Iterator[int]:
266 n = int() + 3
267 yield x
268 yield n * x
269
270 a = []
271 for x in generator():
272 a.append(x)
273 return a
274
275 def call_nested_recursive(x: int) -> Iterator:
276 def recursive(x: int) -> Iterator:
277 if x > 0:
278 yield from recursive(x - 1)
279 yield x
280
281 yield from recursive(x)
282
283 def test_call_nested_generator_in_function() -> None:
284 assert call_nested_decorated(5) == [5, 15]
285 assert list(call_nested_recursive(5)) == [0, 1, 2, 3, 4, 5]
286
287 [case testYieldThrow]
288 from typing import Generator, Iterable, Any, Union
289 from traceback import print_tb
290 from contextlib import contextmanager
291 import wrapsys
292
293 def generator() -> Generator[int, None, Union[int, None]]:
294 try:
295 yield 1
296 yield 2
297 yield 3
298 except Exception as e:
299 print_tb(wrapsys.exc_info()[2])
300 s = str(e)
301 if s:
302 print('caught exception with value ' + s)
303 else:
304 print('caught exception without value')
305 return 0
306 return None
307
308 def no_except() -> Iterable[int]:
309 yield 1
310 yield 2
311
312 def raise_something() -> Iterable[int]:
313 yield 1
314 yield 2
315 raise Exception('failure')
316
317 def wrapper(x: Any) -> Any:
318 return (yield from x)
319
320 def foo() -> Generator[int, None, None]:
321 try:
322 yield 1
323 except Exception as e:
324 print(str(e))
325 finally:
326 print('goodbye')
327
328 ctx_manager = contextmanager(foo)
329
330 [file wrapsys.py]
331 # This is a gross hack around some limitations of the test system/mypyc.
332 from typing import Any
333 import sys
334 def exc_info() -> Any:
335 return sys.exc_info() # type: ignore
336
337 [file driver.py]
338 import sys
339 from typing import Generator, Tuple, TypeVar, Sequence
340 from native import generator, ctx_manager, wrapper, no_except, raise_something
341
342 T = TypeVar('T')
343 U = TypeVar('U')
344
345 def run_generator_and_throw(gen: Generator[T, None, U],
346 num_times: int,
347 value: object = None,
348 traceback: object = None) -> Tuple[Sequence[T], U]:
349 res = []
350 try:
351 for i in range(num_times):
352 res.append(next(gen))
353 if value is not None and traceback is not None:
354 gen.throw(Exception, value, traceback)
355 elif value is not None:
356 gen.throw(Exception, value)
357 else:
358 gen.throw(Exception)
359 except StopIteration as e:
360 return (tuple(res), e.value)
361 except Exception as e:
362 return (tuple(res), str(e))
363
364 assert run_generator_and_throw(generator(), 0, 'hello') == ((), 'hello')
365 assert run_generator_and_throw(generator(), 3) == ((1, 2, 3), 0)
366 assert run_generator_and_throw(generator(), 2, 'some string') == ((1, 2), 0)
367 try:
368 raise Exception
369 except Exception as e:
370 tb = sys.exc_info()[2]
371 assert run_generator_and_throw(generator(), 1, 'some other string', tb) == ((1,), 0)
372
373 assert run_generator_and_throw(wrapper(generator()), 0, 'hello') == ((), 'hello')
374 assert run_generator_and_throw(wrapper(generator()), 3) == ((1, 2, 3), 0)
375 assert run_generator_and_throw(wrapper(generator()), 2, 'some string') == ((1, 2), 0)
376 # Make sure we aren't leaking exc_info
377 assert sys.exc_info()[0] is None
378
379 assert run_generator_and_throw(wrapper([1, 2, 3]), 3, 'lol') == ((1, 2, 3), 'lol')
380 assert run_generator_and_throw(wrapper(no_except()), 2, 'lol') == ((1, 2), 'lol')
381
382 assert run_generator_and_throw(wrapper(raise_something()), 3) == ((1, 2), 'failure')
383
384 with ctx_manager() as c:
385 raise Exception('exception')
386
387 [out]
388 File "native.py", line 10, in generator
389 yield 3
390 File "native.py", line 9, in generator
391 yield 2
392 File "native.py", line 8, in generator
393 yield 1
394 File "driver.py", line 31, in <module>
395 raise Exception
396 File "native.py", line 10, in generator
397 yield 3
398 File "native.py", line 31, in wrapper
399 return (yield from x)
400 File "native.py", line 9, in generator
401 yield 2
402 File "native.py", line 31, in wrapper
403 return (yield from x)
404 caught exception without value
405 caught exception with value some string
406 caught exception with value some other string
407 caught exception without value
408 caught exception with value some string
409 exception
410 goodbye
411
412 [case testYieldSend]
413 from typing import Generator
414
415 def basic() -> Generator[int, int, int]:
416 x = yield 1
417 y = yield (x + 1)
418 return y
419
420 def use_from() -> Generator[int, int, int]:
421 return (yield from basic())
422
423 [file driver.py]
424 from native import basic, use_from
425 from testutil import run_generator
426
427 assert run_generator(basic(), [5, 50]) == ((1, 6), 50)
428 assert run_generator(use_from(), [5, 50]) == ((1, 6), 50)
429
430 [case testYieldFrom]
431 from typing import Generator, Iterator, List
432
433 def basic() -> Iterator[int]:
434 yield from [1, 2, 3]
435
436 def call_next() -> int:
437 x = [] # type: List[int]
438 return next(iter(x))
439
440 def inner(b: bool) -> Generator[int, None, int]:
441 if b:
442 yield from [1, 2, 3]
443 return 10
444
445 def with_return(b: bool) -> Generator[int, None, int]:
446 x = yield from inner(b)
447 for a in [1, 2]:
448 pass
449 return x
450
451 [file driver.py]
452 from native import basic, call_next, with_return
453 from testutil import run_generator, assertRaises
454
455 assert run_generator(basic()) == ((1, 2, 3), None)
456
457 with assertRaises(StopIteration):
458 call_next()
459
460 assert run_generator(with_return(True)) == ((1, 2, 3), 10)
461 assert run_generator(with_return(False)) == ((), 10)
462
463 [case testNextGenerator]
464 from typing import Iterable
465
466 def f(x: int) -> int:
467 print(x)
468 return x
469
470 def call_next_loud(l: Iterable[int], val: int) -> int:
471 return next(i for i in l if f(i) == val)
472
473 def call_next_default(l: Iterable[int], val: int) -> int:
474 return next((i*2 for i in l if i == val), -1)
475
476 def call_next_default_list(l: Iterable[int], val: int) -> int:
477 return next((i*2 for i in l if i == val), -1)
478 [file driver.py]
479 from native import call_next_loud, call_next_default, call_next_default_list
480 from testutil import assertRaises
481
482 assert call_next_default([0, 1, 2], 0) == 0
483 assert call_next_default([0, 1, 2], 1) == 2
484 assert call_next_default([0, 1, 2], 2) == 4
485 assert call_next_default([0, 1, 2], 3) == -1
486 assert call_next_default([], 0) == -1
487 assert call_next_default_list([0, 1, 2], 0) == 0
488 assert call_next_default_list([0, 1, 2], 1) == 2
489 assert call_next_default_list([0, 1, 2], 2) == 4
490 assert call_next_default_list([0, 1, 2], 3) == -1
491 assert call_next_default_list([], 0) == -1
492
493 assert call_next_loud([0, 1, 2], 0) == 0
494 assert call_next_loud([0, 1, 2], 1) == 1
495 assert call_next_loud([0, 1, 2], 2) == 2
496 with assertRaises(StopIteration):
497 call_next_loud([42], 3)
498 with assertRaises(StopIteration):
499 call_next_loud([], 3)
500
501 [out]
502 0
503 0
504 1
505 0
506 1
507 2
508 42
509
510 [case testGeneratorSuper]
511 from typing import Iterator, Callable, Any
512
513 class A():
514 def testA(self) -> int:
515 return 2
516
517 class B(A):
518 def testB(self) -> Iterator[int]:
519 x = super().testA()
520 while True:
521 yield x
522
523 def testAsserts():
524 b = B()
525 b_gen = b.testB()
526 assert next(b_gen) == 2
527
528 [file driver.py]
529 from native import testAsserts
530
531 testAsserts()
532
533 [case testNameClashIssues]
534 class A:
535 def foo(self) -> object:
536 yield
537 class B:
538 def foo(self) -> object:
539 yield
540
541 class C:
542 def foo(self) -> None:
543 def bar(self) -> None:
544 pass
545
546 def C___foo() -> None: pass
547
548 class D:
549 def foo(self) -> None:
550 def bar(self) -> None:
551 pass
552
553 class E:
554 default: int
555 switch: int
556
557 [file driver.py]
558 # really I only care it builds
559
560 [case testCloseStopIterationRaised]
561 def g() -> object:
562 try:
563 yield 1
564 except GeneratorExit:
565 raise
566
567 [file driver.py]
568 from native import g
569
570 gen = g()
571 next(gen)
572 gen.close()
573
574 [case testCloseGeneratorExitRaised]
575 def g() -> object:
576 yield 1
577
578 [file driver.py]
579 from native import g
580
581 gen = g()
582 next(gen)
583 gen.close()
584
585 [case testCloseGeneratorExitIgnored]
586 def g() -> object:
587 try:
588 yield 1
589 except GeneratorExit:
590 pass
591
592 yield 2
593
594 [file driver.py]
595 from native import g
596
597 gen = g()
598 next(gen)
599 try:
600 gen.close()
601 except RuntimeError as e:
602 assert str(e) == 'generator ignored GeneratorExit'
603 else:
604 assert False
605
606 [case testCloseGeneratorRaisesAnotherException]
607 def g() -> object:
608 try:
609 yield 1
610 except GeneratorExit:
611 raise RuntimeError("error")
612
613 [file driver.py]
614 from native import g
615
616 gen = g()
617 next(gen)
618 try:
619 gen.close()
620 except RuntimeError as e:
621 assert str(e) == 'error'
622 else:
623 assert False
624
625 [case testBorrowingInGeneratorNearYield]
626 from typing import Iterator
627
628 class Foo:
629 flag = False
630
631 class C:
632 foo = Foo()
633
634 def genf(self) -> Iterator[None]:
635 self.foo.flag = True
636 yield
637 self.foo.flag = False
638
639 def test_near_yield() -> None:
640 c = C()
641 for x in c.genf():
642 pass
643 assert c.foo.flag == False
644
645 [case testGeneratorEarlyReturnWithBorrows]
646 from typing import Iterator
647 class Bar:
648 bar = 0
649 class Foo:
650 bar = Bar()
651 def f(self) -> Iterator[int]:
652 if self:
653 self.bar.bar += 1
654 return
655 yield 0
656
657 def test_early_return() -> None:
658 foo = Foo()
659 for x in foo.f():
660 pass
661 assert foo.bar.bar == 1
662
663 [case testBorrowingInGeneratorInTupleAssignment]
664 from typing import Iterator
665
666 class Foo:
667 flag1: bool
668 flag2: bool
669
670 class C:
671 foo: Foo
672
673 def genf(self) -> Iterator[None]:
674 self.foo.flag1, self.foo.flag2 = True, True
675 yield
676 self.foo.flag1, self.foo.flag2 = False, False
677
678 def test_generator() -> None:
679 c = C()
680 c.foo = Foo()
681 gen = c.genf()
682 next(gen)
683 assert c.foo.flag1 == c.foo.flag2 == True
684 assert list(gen) == []
685 assert c.foo.flag1 == c.foo.flag2 == False
686
687
688 [case testYieldInFinally]
689 from typing import Generator
690
691 def finally_yield() -> Generator[str, None, str]:
692 try:
693 return 'test'
694 finally:
695 yield 'x'
696
697
698 [file driver.py]
699 from native import finally_yield
700 from testutil import run_generator
701
702 yields, val = run_generator(finally_yield())
703 assert yields == ('x',)
704 assert val == 'test', val
705
706 [case testUnreachableComprehensionNoCrash]
707 from typing import List
708
709 def list_comp() -> List[int]:
710 if True:
711 return [5]
712 return [i for i in [5]]
713
714 [file driver.py]
715 from native import list_comp
716 assert list_comp() == [5]
717
718 [case testWithNative]
719 class DummyContext:
720 def __init__(self) -> None:
721 self.x = 0
722
723 def __enter__(self) -> None:
724 self.x += 1
725
726 def __exit__(self, exc_type, exc_value, exc_tb) -> None:
727 self.x -= 1
728
729 def test_basic() -> None:
730 context = DummyContext()
731 with context:
732 assert context.x == 1
733 assert context.x == 0
734
735 [case testYieldSpill]
736 from typing import Generator
737 from testutil import run_generator
738
739 def f() -> int:
740 return 1
741
742 def yield_spill() -> Generator[str, int, int]:
743 return f() + (yield "foo")
744
745 def test_basic() -> None:
746 x = run_generator(yield_spill(), [2])
747 yields, val = x
748 assert yields == ('foo',)
749 assert val == 3, val
750
751 [case testGeneratorReuse]
752 from typing import Iterator, Any
753
754 def gen(x: list[int]) -> Iterator[list[int]]:
755 y = [9]
756 for z in x:
757 yield y + [z]
758 yield y
759
760 def gen_range(n: int) -> Iterator[int]:
761 for x in range(n):
762 yield x
763
764 def test_use_generator_multiple_times_one_at_a_time() -> None:
765 for i in range(100):
766 a = []
767 for x in gen([2, i]):
768 a.append(x)
769 assert a == [[9, 2], [9, i], [9]]
770
771 def test_use_multiple_generator_instances_at_same_time() -> None:
772 a = []
773 for x in gen([2]):
774 a.append(x)
775 for y in gen([3, 4]):
776 a.append(y)
777 assert a == [[9, 2], [9, 3], [9, 4], [9], [9], [9, 3], [9, 4], [9]]
778
779 def test_use_multiple_generator_instances_at_same_time_2() -> None:
780 a = []
781 for x in gen_range(2):
782 a.append(x)
783 b = []
784 for y in gen_range(3):
785 b.append(y)
786 c = []
787 for z in gen_range(4):
788 c.append(z)
789 assert c == [0, 1, 2, 3]
790 assert b == [0, 1, 2]
791 assert a == [0, 1]
792 assert list(gen_range(5)) == list(range(5))
793
794 def gen_a(x: int) -> Iterator[int]:
795 yield x + 1
796
797 def gen_b(x: int) -> Iterator[int]:
798 yield x + 2
799
800 def test_generator_identities() -> None:
801 # Sanity check: two distinct live objects can't reuse the same memory location
802 g1 = gen_a(1)
803 g2 = gen_a(1)
804 assert g1 is not g2
805
806 # If two generators have non-overlapping lifetimes, they should reuse a memory location
807 g3 = gen_b(1)
808 id1 = id(g3)
809 g3 = gen_b(1)
810 assert id(g3) == id1
811
812 # More complex case of reuse: allocate other objects in between
813 g4: Any = gen_a(1)
814 id2 = id(g4)
815 g4 = gen_b(1)
816 g4 = [gen_b(n) for n in range(100)]
817 g4 = gen_a(1)
818 assert id(g4) == id2
819
820 [case testGeneratorReuseWithGilDisabled]
821 import sys
822 import threading
823 from typing import Iterator
824
825 def gen() -> Iterator[int]:
826 yield 1
827
828 def is_gil_disabled() -> bool:
829 return hasattr(sys, "_is_gil_enabled") and not sys._is_gil_enabled()
830
831 def test_each_thread_gets_separate_instance() -> None:
832 if not is_gil_disabled():
833 # This only makes sense if GIL is disabled
834 return
835
836 g = gen()
837 id1 = id(g)
838
839 id2 = 0
840
841 def run() -> None:
842 nonlocal id2
843 g = gen()
844 id2 = id(g)
845
846 t = threading.Thread(target=run)
847 t.start()
848 t.join()
849
850 # Each thread should get a separate reused instance
851 assert id1 != id2
852
853 [case testGeneratorWithUndefinedLocalInEnvironment]
854 from typing import Iterator
855
856 from testutil import assertRaises
857
858 def gen(set: bool) -> Iterator[float]:
859 if set:
860 y = float("-113.0")
861 yield 1.0
862 yield y
863
864 def test_bitmap_is_cleared_when_object_is_reused() -> None:
865 # This updates the bitmap of the shared instance.
866 list(gen(True))
867
868 # Ensure bitmap has been cleared.
869 with assertRaises(AttributeError): # TODO: Should be UnboundLocalError
870 list(gen(False))
871
872 def gen2(set: bool) -> Iterator[int]:
873 if set:
874 y = int("5")
875 yield 1
876 yield y
877
878 def test_undefined_int_in_environment() -> None:
879 list(gen2(True))
880
881 with assertRaises(AttributeError): # TODO: Should be UnboundLocalError
882 list(gen2(False))
883
884 [case testVariableWithSameNameAsHelperMethod]
885 from testutil import assertRaises
886 from typing import Iterator
887
888 def gen_send() -> Iterator[int]:
889 send = 1
890 yield send + 1
891
892 def gen_throw() -> Iterator[int]:
893 throw = 42
894 yield throw * 2
895
896 def undefined() -> Iterator[int]:
897 if int():
898 send = 1
899 yield send + 1
900
901 def test_same_names() -> None:
902 assert list(gen_send()) == [2]
903 assert list(gen_throw()) == [84]
904
905 with assertRaises(AttributeError, "attribute 'send' of 'undefined_gen' undefined"):
906 # TODO: Should be UnboundLocalError, this test verifies that the attribute name
907 # matches the variable name in the input code, since internally it's generated
908 # with a prefix.
909 list(undefined())
910
911 [case testGeneratorInheritance]
912 from typing import Iterator
913
914 class Base1:
915 def foo(self) -> Iterator[int]:
916 yield 1
917
918 class Derived1(Base1):
919 def foo(self) -> Iterator[int]:
920 yield 2
921 yield 3
922
923 def base1_foo(b: Base1) -> list[int]:
924 a = []
925 for x in b.foo():
926 a.append(x)
927 return a
928
929 def derived1_foo(b: Derived1) -> list[int]:
930 a = []
931 for x in b.foo():
932 a.append(x)
933 return a
934
935 def test_generator_override() -> None:
936 assert base1_foo(Base1()) == [1]
937 assert base1_foo(Derived1()) == [2, 3]
938 assert derived1_foo(Derived1()) == [2, 3]
939
940 [case testGeneratorEmptyTuple]
941 from collections.abc import Generator
942 from typing import Optional, Union
943
944 def test_compiledGeneratorEmptyTuple() -> None:
945 jobs: Generator[Optional[str], None, None] = (_ for _ in ())
946 assert list(jobs) == []