search_hooks.py
1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
"""Helpers for preserving app-module search monkeypatch hooks."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Callable, MutableMapping, Protocol, runtime_checkable
SearchDispatcher = Callable[..., dict[str, Any]]
SearchQueryResolver = Callable[..., tuple[str, str]]
ModuleNamespace = MutableMapping[str, Any]
@runtime_checkable
class SearchHookSource(Protocol):
"""Mutable object that exposes search hook callables."""
resolve_search_query: SearchQueryResolver
dispatch_search_request: SearchDispatcher
@dataclass(frozen=True)
class SearchHookBindings:
"""Wrappers that resolve search callables from the app module namespace."""
resolve_search_query: SearchQueryResolver
dispatch_search_request: SearchDispatcher
def _resolve_hook_callable(
hook_source: SearchHookSource | ModuleNamespace,
name: str,
) -> Callable[..., Any]:
if isinstance(hook_source, MutableMapping):
return hook_source[name]
return getattr(hook_source, name)
def _bind_hook_callable(
hook_source: SearchHookSource | ModuleNamespace,
name: str,
) -> Callable[..., Any]:
"""Resolve the latest callable from the hook source at call time."""
def _call(**kwargs):
target = _resolve_hook_callable(hook_source, name)
return target(**kwargs)
return _call
def build_search_hook_bindings(
hook_source: SearchHookSource | ModuleNamespace,
) -> SearchHookBindings:
"""Build monkeypatch-compatible search wrappers for the app entrypoint."""
return SearchHookBindings(
resolve_search_query=_bind_hook_callable(hook_source, "resolve_search_query"),
dispatch_search_request=_bind_hook_callable(hook_source, "dispatch_search_request"),
)
__all__ = [
"SearchHookBindings",
"build_search_hook_bindings",
]