diff --git a/src/prompt_toolkit/key_binding/key_bindings.py b/src/prompt_toolkit/key_binding/key_bindings.py index 5fd56394b..cfb5eb13c 100644 --- a/src/prompt_toolkit/key_binding/key_bindings.py +++ b/src/prompt_toolkit/key_binding/key_bindings.py @@ -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 diff --git a/tests/test_key_binding.py b/tests/test_key_binding.py index 479559c61..118e7ca13 100644 --- a/tests/test_key_binding.py +++ b/tests/test_key_binding.py @@ -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 @@ -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]