Skip to content
How-to guide

Combine and switch lookups

Keep one consumer-facing lookup while its sources change. Use ProxyLookup to combine several sources, or DelegatedLookup when an application selects one source at a time. Consumers can retain their results and callbacks in either case. Use the subscription pattern in Observe results.

Combine distinct sources

Pass each source as a separate argument to ProxyLookup. Put sources in the order in which a single-object query should search them: lookup() returns the first matching object, while a result exposes matches from all sources.

This complete example combines application-wide objects with a changing document selection, then temporarily adds another source. It retains one result throughout and verifies that changes within the selection still reach its callback after the temporary source is removed.

combine_sources.py
from lookups import GenericLookup, InstanceContent, ProxyLookup, Result, singleton

content = InstanceContent()
selection = GenericLookup(content)
content.add("report.txt")
application = singleton("application")
combined = ProxyLookup(application, selection)
result = combined.lookup_result(str)
views: list[tuple[str, ...]] = []


def record_view(changed: Result[str]) -> None:
    assert changed is result
    views.append(tuple(changed.all_instances()))


result.listeners += record_view
try:
    record_view(result)
    assert views[-1] == ("application", "report.txt")
    assert combined.lookup(str) == "application"

    temporary = singleton("preview")
    combined.add_lookup(temporary)
    assert result.all_instances() == ("application", "report.txt", "preview")

    combined.remove_lookup(temporary)
    assert result.all_instances() == ("application", "report.txt")
    assert combined.lookup_result(str) is result

    content.set(["chart.svg"])
    assert views[-1] == ("application", "chart.svg")
finally:
    result.listeners -= record_view

recorded = len(views)
content.set(["notes.txt"])
assert len(views) == recorded
assert result.all_instances() == ("application", "notes.txt")

Use add_lookup() to append a distinct source and remove_lookup() when it no longer belongs in the composite. To change the objects within a source, use its owner, such as InstanceContent in Manage membership. Removing a source from the composite leaves it usable independently.

Replace a provider's supplied lookup

Implement LookupProvider.get_lookup() to return the currently selected, initialised Lookup. Set that state before constructing DelegatedLookup, because its constructor asks the provider for a source immediately. After changing the provider's selection, call lookup_updated() on the delegated lookup explicitly so that queries and retained results follow the new source.

The following complete example switches between two document selections. It checks that the retained result follows the new source, that the old source no longer notifies it, and that the new source does.

switch_selection.py
from typing_extensions import override

from lookups import DelegatedLookup, GenericLookup, InstanceContent, Lookup, LookupProvider, Result


class SelectionProvider(LookupProvider):
    def __init__(self, current: Lookup) -> None:
        super().__init__()
        self.current = current

    @override
    def get_lookup(self) -> Lookup:
        return self.current


old_content = InstanceContent()
old_selection = GenericLookup(old_content)
old_content.add("report.txt")
new_content = InstanceContent()
new_selection = GenericLookup(new_content)
new_content.add("chart.svg")

provider = SelectionProvider(old_selection)
selected = DelegatedLookup(provider)
result = selected.lookup_result(str)
views: list[tuple[str, ...]] = []


def record_view(changed: Result[str]) -> None:
    assert changed is result
    views.append(tuple(sorted(changed.all_instances())))


result.listeners += record_view
try:
    record_view(result)
    assert views[-1] == ("report.txt",)

    provider.current = new_selection
    assert selected.lookup(str) == "report.txt"
    selected.lookup_updated()
    assert selected.delegate is new_selection
    assert selected.lookup_result(str) is result
    assert result.all_instances() == ("chart.svg",)
    assert views[-1] == ("chart.svg",)

    recorded = len(views)
    old_content.add("old-notes.txt")
    assert len(views) == recorded

    new_content.add("diagram.svg")
    assert views[-1] == ("chart.svg", "diagram.svg")
finally:
    result.listeners -= record_view

recorded = len(views)
new_content.add("notes.txt")
assert len(views) == recorded
assert set(result.all_instances()) == {"chart.svg", "diagram.svg", "notes.txt"}

Place the provider assignment and lookup_updated() call together in the application's selection-change handler. For later replacements, update that same provider and refresh again. If no source is selected, have the provider return EmptyLookup() rather than None.

Changes within the selected source use its normal notifications, so the example changes new_content without another refresh. Only replacing the source requires lookup_updated().

End observation in the consumer's cleanup path

Retain both the outer result and its callback or callback owner while observing, as explained in Lifetime and change notifications. Subscribe once to that result, which maintains its source subscriptions as you add or remove proxy sources or refresh a changed delegate. Registration does not deliver an initial view, so both examples read it explicitly.

Remove the callback when its consumer closes, as the finally blocks do above. Removing the last outer listener disconnects the result's underlying source subscriptions. The result remains available for explicit reads, which the final assertions check. If you dispatch generic notifications through an executor, follow the shutdown sequence in Observe results.