Skip to content
Open
Show file tree
Hide file tree
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
6 changes: 4 additions & 2 deletions src/prompt_toolkit/key_binding/key_bindings.py
Original file line number Diff line number Diff line change
Expand Up @@ -628,13 +628,15 @@ class DynamicKeyBindings(_Proxy):
def __init__(self, get_key_bindings: Callable[[], KeyBindingsBase | None]) -> None:
self.get_key_bindings = get_key_bindings
self.__version = 0
self._last_child_version = None
self._dummy = KeyBindings() # Empty key bindings.
self._bindings2 = self._dummy

def _update_cache(self) -> None:
key_bindings = self.get_key_bindings() or self._dummy
assert isinstance(key_bindings, KeyBindingsBase)
version = id(key_bindings), key_bindings._version
if key_bindings is not self._bindings2:
self.__version += 1
version = self.__version, key_bindings._version

self._bindings2 = key_bindings
self._last_version = version
Expand Down
30 changes: 29 additions & 1 deletion tests/test_key_binding.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@
from prompt_toolkit.application import Application
from prompt_toolkit.application.current import set_app
from prompt_toolkit.input.defaults import create_pipe_input
from prompt_toolkit.key_binding.key_bindings import KeyBindings
from prompt_toolkit.key_binding.key_bindings import (
DynamicKeyBindings,
KeyBindings,
merge_key_bindings,
)
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyProcessor
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout import Layout, Window
Expand Down Expand Up @@ -202,3 +206,27 @@ def handler(event):
assert events[1].previous_key_sequence[0].data == "a"
assert events[1].previous_key_sequence[1].key == "a"
assert events[1].previous_key_sequence[1].data == "a"


def test_dynamic_key_bindings_cache_with_reused_id(monkeypatch):
"""
DynamicKeyBindings must not serve stale bindings when a new KeyBindings object reuses the address of a previous one
"""
monkeypatch.setattr(
"prompt_toolkit.key_binding.key_bindings.id", lambda _: 0, raising=False
)

pretend_database = [0]

def build():
kb = KeyBindings()
value = pretend_database[0]
kb.add("a")(lambda _: value)
return kb

merged = merge_key_bindings([DynamicKeyBindings(build)])
lookups = []
for value in range(3):
pretend_database[0] = value
lookups.append(merged.get_bindings_for_keys(("a",))[-1].handler(None))
assert lookups == [0, 1, 2]
Loading