Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added a Completer that throttles superfluous calls #1918

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions src/prompt_toolkit/completion/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"ThreadedCompleter",
"DummyCompleter",
"DynamicCompleter",
"ThrottledCompleter",
"CompleteEvent",
"ConditionalCompleter",
"merge_completers",
Expand Down Expand Up @@ -316,6 +317,46 @@ def __repr__(self) -> str:
return f"DynamicCompleter({self.get_completer!r} -> {self.get_completer()!r})"


class ThrottledCompleter(Completer):
"""
Completer that throttles completion requests to prevent rapid successive calls.

:param completer: :class:`.Completer` instance.
:param delay: Delay in seconds between completions. Default is 0.3.
"""

def __init__(self, completer: Completer, delay: float = 0.3):
self.completer = completer
self.delay = delay
self._last_completion_time = 0
self._semaphore = asyncio.Semaphore(1)

def get_completions(
self, document: Document, complete_event: CompleteEvent
) -> Iterable[Completion]:
"""Get completions without throttling."""
yield from self.completer.get_completions(document, complete_event)

async def get_completions_async(
self, document: Document, complete_event: CompleteEvent
) -> AsyncGenerator[Completion, None]:
"""Get completions asynchronously, applying throttle delay."""
async with self._semaphore:
current_time = asyncio.get_running_loop().time()
time_since_last_completion = current_time - self._last_completion_time

if time_since_last_completion < self.delay:
await asyncio.sleep(self.delay - time_since_last_completion)

self._last_completion_time = asyncio.get_running_loop().time()

async with aclosing(
self.completer.get_completions_async(document, complete_event)
) as async_generator:
async for item in async_generator:
yield item


class ConditionalCompleter(Completer):
"""
Wrapper around any other completer that will enable/disable the completions
Expand Down
Loading