Extend Lookups¶
Use this guide when an application needs to adapt a source of available objects. Choose the smallest extension that fits the source, then check its queries, notifications and lifetime before giving the lookup to consumers. The common lookup model and query interfaces supply the vocabulary used here.
Choose an extension point¶
| If you need to… | Start with… |
|---|---|
| Change which existing objects are available | InstanceContent and GenericLookup, as described in Manage membership. |
| Describe an object now and construct it on demand | Convertor, implementing its four methods with Defer object creation. |
| Supply an associated lookup or select a different source | LookupProvider.get_lookup() with DelegatedLookup and explicitly call lookup_updated() when the source changes. See Combine and switch lookups. |
| Prepare membership at first use or before queries | A GenericLookup subclass with protected hooks and pair helpers, as below. |
| Implement query and result behaviour that generic membership cannot express | Custom Lookup, Result and Item implementations. |
Prefer composition when an existing lookup already represents your source.
A provider supplies an existing lookup without needing to implement queries or manage
result notifications itself. Its get_lookup() must return an initialised
lookup, including an empty lookup when nothing is available.
Prepare membership in a generic subclass¶
Keep the inherited query implementations and use the pair helpers to change membership. The example below exposes one string, then applies a queued replacement before the next query or retained-result read. Its pair holds the string strongly and uses the default object identity for equality and hashing.
Pair is a module-level support import, rather than a package-root export.
Implement its four item methods and both predicates even though current generic
storage selects matches using issubclass(pair.get_type(), searched_type).
from lookups import GenericLookup
from lookups.generic_lookup import Pair
from typing_extensions import override
class TextPair(Pair[str]):
def __init__(self, text: str) -> None:
super().__init__()
self._text = text
@override
def get_instance(self) -> str:
return self._text
@override
def get_type(self) -> type[str]:
return str
@override
def get_id(self) -> str:
return self._text
@override
def get_display_name(self) -> str:
return self._text
@override
def instance_of(self, cls: type[object]) -> bool:
return issubclass(str, cls)
@override
def creator_of(self, obj: object) -> bool:
return obj is self._text
class TextLookup(GenericLookup):
def __init__(self) -> None:
self._pending: TextPair | None = None
super().__init__()
@override
def _initialise(self) -> None:
self._add_pair(TextPair("ready"))
def queue_text(self, text: str) -> None:
self._pending = TextPair(text)
@override
def _before_lookup(self, cls: type[object]) -> None:
if (pair := self._pending) is not None:
self._pending = None
self._set_pairs((pair,))
lookup = TextLookup()
assert lookup.lookup(str) == "ready"
result = lookup.lookup_result(str)
assert result.all_instances() == ("ready",)
lookup.queue_text("updated")
assert result.all_instances() == ("updated",)
assert lookup.lookup(object) == "updated"
assert lookup.lookup(int) is None
queue_text() schedules the replacement for the next read, leaving membership
unchanged and sending no notification in the meantime. Clear _pending before
calling _set_pairs(): a listener notified by that call may immediately read the
result again, and the nested read must not attempt the same pending replacement
recursively. This example has no background refresh or thread-safety policy.
Use _remove_pair() when withdrawing an individual registered pair. Keep pairs
hashable, with equality and hashes that remain stable while registered. Generic
lookup membership has no registration-order priority. The exact signatures, executor argument and error
conditions are in the subclass hook reference.
Arrange hook state before calling the base constructor¶
Set every field used by a hook before super().__init__(). Storage is created on
first use, and that first use need not be a query. In particular, attaching
content with buffered members creates storage during the base constructor and
calls _initialise() before control returns to your constructor. The buffered
content replacement then follows initialisation, so it can replace pairs added
by the hook. Avoid combining two competing sources of initial membership.
Account for these call paths when implementing hooks:
- A query through
lookup_item()orlookup_result()calls_before_lookup(cls)before entering storage. On first use, storage is then created and_initialise()runs. If_before_lookup()itself uses a pair helper, that helper can cause initialisation first. - A pair mutation or non-empty content attachment can create storage and run
_initialise()without calling_before_lookup(). - Every collection read on a retained generic result calls
_before_lookup()again, including reads that can reuse cached collections. For example,lookup_all()reaches the hook through both result acquisition and its instance collection read.
Keep preparation independent of lookup queries
Do not issue another query on the same lookup from _before_lookup():
it invokes the hook again. Queries from _initialise() can reach partially
populated storage because storage already exists when the hook runs.
Prepare pairs from your source directly, and make repeated preparation safe.
This also avoids entering an active storage modification recursively, which
can raise RuntimeError.
Adapt an owner-side content handle¶
If the owner needs domain-specific mutation methods rather than query hooks,
subclass Content from lookups.generic_lookup and translate those methods into
_add_pair(), _remove_pair() and _set_pairs(). Pass the content object to
GenericLookup(content) to attach it. These helpers buffer changes before
attachment and forward them once a lookup attaches. Each content object belongs to one
lookup, with no public detach or reattach operation.
Content(notify_in=...) accepts a notification executor at construction. Its
helpers use that executor rather than taking a per-call executor argument.
Keep ownership and shutdown of the executor in your application. The
Content reference specifies the helpers and
their attachment requirements.
The documented facilities of Content and Pair support these extensions.
Internal storage and transaction classes are not extension interfaces.
Implement a custom source when the hooks are insufficient¶
For custom matching or source behaviour, implement the common interfaces directly
rather than changing pair predicates alone. GenericLookup uses
get_type() and issubclass() for matching and affected-result selection, so it
does not dispatch those decisions through instance_of() or creator_of().
A predicate that claims extra matches therefore does not make them discoverable
or arrange their notifications.
Build the source against these obligations, using the linked reference for full signatures:
| Interface | Implement | Inherited facilities |
|---|---|---|
Lookup |
lookup() and lookup_result(). Return None only for absent instances and a result even for an empty selection. |
__call__() and lookup_expected() use lookup(), while lookup_item() and lookup_all() use the result. Override them only when the source needs a different implementation. |
Result |
for_class, all_classes(), all_instances(), all_items() and a listeners registry. Keep the searched type and return immutable collections, including empty ones. |
No notification dispatcher or collection implementation is supplied. |
Item |
get_instance(), get_type(), get_id() and get_display_name(). Keep metadata usable without requiring instance retrieval. |
str(item) calls get_id(). |
For a changing source, make held results reflect later membership, invalidate
any affected caches and notify their listeners with the affected result as the
argument. A notification signals possible change, inviting a new read of the
result rather than supplying a membership difference.
A custom result can retain a typed listeners.Observable and expose its
.listeners registry, following the standard dynamic implementations. Those
implementations dispatch through the current Listeners default, which logs and
suppresses ordinary callback Exceptions. Do not assume those exceptions return
to the mutation caller. Choose and document your source's dispatch behaviour
without promising ordering or general thread safety on behalf of Lookups.
Choose whether an item retains its member or constructs it on demand, and document that lifetime. An instance collection or result cache can keep a retrieved member alive even when the item itself uses a weak reference. Consumers can retain objects after withdrawal, so agree with the application owner when their resources may be disposed of.
Decide which objects keep the source and results alive. Retain results and
callbacks or their owners throughout observation, because weak references do not
keep subscriptions active. If your adapter subscribes to upstream results, keep
those results and callbacks alive too, and remove the callbacks when switching
sources or closing the adapter. Provide application-level cleanup for external
subscriptions and resources: the abstract interfaces supply no common close()
method. Remove consumer callbacks when observation ends and shut down any
executor you own. See Observe results and
Lifetime and change notifications.
Check the extension before exposing it¶
Run the complete example above as a starting check, then exercise your extension with an exact type, a parent type and an absent type. For a changing source, retain an initially empty result, add and remove a member, and confirm that both its collections and listener notifications reflect those changes. Check that item metadata does not accidentally construct deferred members and that false-valued members remain available.
Test repeated hook calls, first use through a mutation and, if accepted by your constructor, buffered content attachment. Check cleanup by ending observation and changing the upstream source again. Type-check the implementation and run the relevant integration tests using the development workflow.