-
Notifications
You must be signed in to change notification settings - Fork 240
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
allow enabling queued/async iterator with PYGLOSSARY_ASYNC_ITER_SIZE env
- Loading branch information
Showing
2 changed files
with
41 additions
and
0 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
from __future__ import annotations | ||
|
||
import queue | ||
import threading | ||
from typing import TYPE_CHECKING, Any | ||
|
||
if TYPE_CHECKING: | ||
from collections.abc import Iterator | ||
|
||
|
||
class QueuedIterator: | ||
def __init__( | ||
self, | ||
iterator: Iterator, | ||
max_size: int, | ||
) -> None: | ||
self.iterator = iterator | ||
self.queue = queue.Queue(max_size) | ||
self.thread = threading.Thread(target=self._background_job) | ||
self.thread.start() | ||
|
||
def _background_job(self) -> None: | ||
for item in self.iterator: | ||
self.queue.put(item) | ||
self.queue.put(StopIteration) | ||
|
||
def __iter__(self) -> Iterator: | ||
return self | ||
|
||
def __next__(self) -> Any: | ||
item = self.queue.get() | ||
if item is StopIteration: | ||
raise StopIteration | ||
return item |