Created
October 28, 2022 18:18
-
-
Save rkhullar/bb14dd60c02f42230b8549b83734d9bc to your computer and use it in GitHub Desktop.
captured iteration - yield and return
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections.abc import Iterator | |
from dataclasses import dataclass, field | |
from typing import Generic, Optional, TypeVar | |
T = TypeVar('T') | |
V = TypeVar('V') | |
@dataclass | |
class CapturedIteration(Generic[T, V]): | |
generator: Iterator = field(repr=False) | |
return_context: Optional[V] = None | |
def __call__(self) -> Iterator[T]: | |
while True: | |
try: | |
yield next(self.generator) | |
except StopIteration as err: | |
if err.args: | |
self.return_context = err.args[0] | |
break | |
if __name__ == '__main__': | |
# TODO: convert to unit test | |
def fn(): | |
yield 'a' | |
yield 'b' | |
return 1 | |
dut: CapturedIteration[str, int] = CapturedIteration(generator=fn()) | |
for x in dut(): | |
print(x) | |
print(dut.return_context) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment