File tree Expand file tree Collapse file tree 1 file changed +27
-1
lines changed Expand file tree Collapse file tree 1 file changed +27
-1
lines changed Original file line number Diff line number Diff line change @@ -698,7 +698,7 @@ def test_basic() -> None:
698698 assert val == 3, val
699699
700700[case testGeneratorReuse]
701- from typing import Iterator
701+ from typing import Iterator, Any
702702
703703def gen(x: list[int]) -> Iterator[list[int]]:
704704 y = [9]
@@ -740,3 +740,29 @@ def test_use_multiple_generator_instances_at_same_time_2() -> None:
740740 assert a == [0, 1]
741741 assert list(gen_range(5)) == list(range(5))
742742
743+ def gen_a(x: int) -> Iterator[int]:
744+ yield x + 1
745+
746+ def gen_b(x: int) -> Iterator[int]:
747+ yield x + 2
748+
749+ def test_generator_identities() -> None:
750+ # Sanity check: two distinct live objects can't reuse the same memory location
751+ g1 = gen_a(1)
752+ g2 = gen_a(1)
753+ assert g1 is not g2
754+
755+ # If two generators have non-overlapping lifetimes, they should reuse a memory location
756+ g3 = gen_b(1)
757+ id1 = id(g3)
758+ g3 = gen_b(1)
759+ assert id(g3) == id1
760+
761+ # More complex case of reuse: allocate other objects in between
762+ g4: Any = gen_a(1)
763+ id2 = id(g4)
764+ g4 = gen_b(1)
765+ g4 = [gen_b(n) for n in range(100)]
766+ g4 = gen_a(1)
767+ assert id(g4) == id2
768+
You can’t perform that action at this time.
0 commit comments