Skip to content
Reference

Composition and providers

ProxyLookup combines several source lookups, while DelegatedLookup presents one provider-supplied source that can be replaced. Both implement the common query and result interfaces and keep retained results connected when their sources change. The three composition interfaces are package-root exports:

Composition imports
from lookups import DelegatedLookup, LookupProvider, ProxyLookup

See Public API for the complete exported surface.

Proxy lookup

Construction and source management

Call Behaviour
ProxyLookup(*lookups) Combines zero or more source lookups in argument order. No sources gives an empty composite.
proxy.add_lookup(lookup) -> None Appends a source and connects retained results to its matching results.
proxy.remove_lookup(lookup) -> None Removes a source and disconnects its result subscriptions. An absent source raises ValueError.

Sources are separate positional arguments: ProxyLookup(first, second), rather than a list passed as one argument. These operations change the composite's sources. Membership within each source remains under its lookup owner's control.

Source order and retained results
from lookups import ProxyLookup, singleton

first = singleton("first")
second = singleton("second")
proxy = ProxyLookup(first, second)
result = proxy.lookup_result(str)

assert proxy.lookup(str) == "first"
assert result.all_instances() == ("first", "second")

proxy.remove_lookup(first)
assert proxy.lookup_result(str) is result
assert proxy.lookup(str) == "second"
assert result.all_instances() == ("second",)

proxy.add_lookup(first)
assert result.all_instances() == ("second", "first")

Queries and collections

lookup(cls) searches sources in order and returns the first non-None match. lookup_item(cls) similarly returns the first matching source item. Neither query examines later sources after a match, and a false-valued object still counts as a match.

For distinct sources, all_instances() and all_items() concatenate source collections in source order, preserving each source's ordering and repetitions. They retain objects exposed by more than one source. all_classes() unites source class collections into a frozenset.

Result continuity and notifications

A retained result stays attached to the proxy when sources are added or removed, so callers can keep using that result and its existing listeners. Repeated lookup_result(cls) calls reuse that result while it remains alive. Keep a strong reference to it throughout observation.

When an outer result has listeners, it subscribes to its source results. A source notification is forwarded as callback(outer_result), so the callback receives the proxy result, not the individual source result. Adding or removing a source can also notify listeners when that source's matching result reports a non-empty all_classes() collection. This check uses class metadata without deliberately retrieving deferred instances.

Removing the last outer listener disconnects the underlying subscriptions. Notifications indicate a possible change rather than a membership difference. See Observation constraints for lifetime and concurrency requirements.

ProxyLookup

Bases: Lookup

Combine source lookups behind one consumer-facing interface.

Direct queries search sources in order. Retained results combine their matching members and follow changes within those sources.

Methods:

__init__
__init__(*lookups)

Create a composite from zero or more source lookups.

Parameters:

Name Type Description Default
lookups Lookup

Initial sources in direct-query order.

()
add_lookup
add_lookup(lookup)

Append a source and update retained results.

Matching non-empty sources can trigger possible-change notifications. Source metadata is inspected without deliberately retrieving instances.

remove_lookup
remove_lookup(lookup)

Remove a source and disconnect its result subscriptions.

Raises:

Type Description
ValueError

The source is not registered with this proxy.

lookup
lookup(cls)
lookup_item
lookup_item(cls)
lookup_result
lookup_result(cls)

Source requirements

Concern Requirement or behaviour
Source identity Use distinct sources that compare unequal. Repeated or equal sources have no defined multiplicity behaviour.
Hashing Sources must be hashable so that proxy results can track them.
Removal Remove a registered source. An absent source raises ValueError.
Membership ownership Adding a source exposes its members without transferring control of its membership.

Delegated lookup

Construction and explicit refresh

Interface Behaviour
DelegatedLookup(provider) Immediately calls provider.get_lookup() and retains the supplied lookup as its delegate.
delegated.delegate: Lookup Read-only property returning the current delegate without consulting the provider.
delegated.lookup_updated() -> None Calls the original provider again and transfers retained results if the supplied lookup compares unequal to the current delegate.

Ordinary queries use the retained delegate. Changing what the provider returns has no effect on those queries until lookup_updated() is called. There is no operation to replace the provider itself.

Explicit provider refresh
from lookups import DelegatedLookup, Lookup, LookupProvider, Result, singleton


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

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


provider = Selection(singleton("old"))
delegated = DelegatedLookup(provider)
result = delegated.lookup_result(str)
notifications: list[Result[str]] = []


def changed(updated: Result[str]) -> None:
    notifications.append(updated)


result.listeners += changed
provider.current = singleton("new")
assert delegated.lookup(str) == "old"

delegated.lookup_updated()
assert delegated.delegate is provider.current
assert delegated.lookup(str) == "new"
assert delegated.lookup_result(str) is result
assert result.all_instances() == ("new",)
assert notifications == [result]
result.listeners -= changed

Result transfer

On refresh, each retained outer result obtains a result for its searched type from the new delegate. If that result compares unequal to its previous source result, its subscription moves to the new result. Existing outer listeners remain registered. A transfer can notify them if either source result reports non-empty class metadata, even when both expose the same members. Subsequent source notifications also pass the outer result to callbacks.

Equality affects both delegate replacement and result transfer: an equal replacement need not be adopted. Calling refresh with the unchanged delegate does not force result reconstruction or notification. Changes within the current delegate follow that source's normal notification behaviour.

Provider and refresh requirements

Concern Requirement or behaviour
Supplied source The provider must return an initialised Lookup. None has no fallback interpretation.
Refresh ownership The provider or its application owner calls lookup_updated() after changing the supplied source.
Errors Provider and source errors can propagate from construction, queries or refresh.
Observer completion With the default Listeners strategy, ordinary callback Exceptions are logged and suppressed. A completed refresh does not establish that every observer succeeded.

DelegatedLookup

Bases: Lookup

Forward queries to a provider-supplied source that can be replaced.

Retained results remain attached to this outer lookup across source changes. After changing what the provider supplies, call lookup_updated() to move those results and their subscriptions. Ordinary queries do not refresh the provider automatically.

Attributes

delegate property
delegate

Return the current delegate without refreshing the provider.

Methods:

__init__
__init__(provider)

Ask the provider for the initial lookup immediately.

Parameters:

Name Type Description Default
provider LookupProvider

The original source of this and subsequent delegates.

required

The provider must return an initialised Lookup. Exceptions raised while obtaining it propagate to the caller.

lookup_updated
lookup_updated()

Ask the provider for its lookup and refresh the delegate.

When the provider supplies a different lookup, retained results and their subscriptions move to that source. Call this after changing the provider's selection.

lookup
lookup(cls)
lookup_result
lookup_result(cls)

Lookup provider

LookupProvider is an abstract interface for an object that supplies an associated lookup. Implement get_lookup() -> Lookup and return an initialised lookup on every call. The interface has no constructor options or inherited refresh, membership-management or notification mechanism.

Initialise provider state before constructing a DelegatedLookup, because its constructor calls get_lookup() immediately. The provider or its application owner controls later refreshes, as specified above. Providing a lookup does not itself grant the right to mutate its members.

A provider can also be a lookup subclass, including supplying itself as the provider to a delegated subclass, provided its source state is ready before the delegated constructor runs. Default lookup discovery also accepts providers, with selection rules specified in Entry points and the default lookup.

LookupProvider

Bases: ABC

Supply an associated lookup through get_lookup().

A provider supplies an associated lookup without necessarily owning its membership. DelegatedLookup asks it for a replacement only on explicit refresh.

Methods:

get_lookup abstractmethod
get_lookup()

Return an initialised lookup associated with this provider.

Observation constraints

Both composition families keep retained results connected to their sources. Observation has the following lifetime and concurrency constraints:

Concern Constraint
Lifetime Retain the observed result and its callback or callback owner while observing.
Cleanup Remove callbacks when observation ends. Removing the last outer listener disconnects source subscriptions.
Concurrent access General thread safety, concurrent source changes and reentrant mutation are unspecified.
Notifications Callback ordering and exactly-once delivery are unspecified.
Collection reads A read is not an atomic snapshot across several sources or during a source-management call.

See Lifetime and change notifications for the observation model.