Skip to content
Reference

Queries, results and items

Lookup selects available members by a searched Python type. A query can retrieve an object directly, return an Item describing one member, or return a Result through which the caller reads and observes the matching members. All three interfaces are available from the package root:

Import query interfaces
from lookups import Item, Lookup, NoneLookupError, Result

Lookup queries

In the signatures below, cls is the searched Python class and T is the type of its matching instances. Matching includes subclasses, allowing a consumer to query a shared parent type. It follows inheritance rather than a general structural-protocol search.

Query Return value when members match Absence
lookup.lookup(cls) One matching instance None
lookup(cls) The same query as lookup.lookup(cls) None
lookup.lookup_expected(cls) One non-None matching instance Raises NoneLookupError
lookup.lookup_all(cls) An immutable sequence of current matching instances Empty sequence
lookup.lookup_item(cls) One matching item description None
lookup.lookup_result(cls) A result for the searched type A result with empty collections

The single-instance queries do not define a universal priority between competing members. Fixed lookups preserve argument order, while generic lookup storage uses a set and does not guarantee registration order. Ordering and duplicate handling for collections also depend on the source, and the common result interface permits duplicates.

Instance retrieval can construct deferred members. lookup_result() does not itself retrieve all matching instances, and standard dynamic item and class metadata queries can describe deferred members without constructing them. If a source, provider or convertor raises an exception, it propagates to the query caller instead of being reported as an absent match.

Required and inherited methods

A Lookup subclass must implement lookup() and lookup_result(). The inherited queries delegate as follows and may be overridden for efficiency:

Inherited method Delegation
__call__(cls) Calls lookup(cls).
lookup_expected(cls) Calls lookup(cls) and raises only if the answer is None.
lookup_item(cls) Returns the first item from lookup_result(cls).all_items(), or None.
lookup_all(cls) Returns lookup_result(cls).all_instances().

The abstract interface has no constructor options of its own. Source-specific construction and supported extension hooks appear in the corresponding reference pages, with implementation guidance in Extend Lookups.

Lookup

Bases: ABC

Find available objects through a searched Python type.

Consumers use this interface without needing the owner's membership handle. Subclasses implement lookup and lookup_result, which provide the basis for the inherited queries. Those queries can be overridden for efficiency. Matching includes parent types, but priority among several matches depends on the implementation.

Methods:

get_default classmethod
get_default()

Resolve the application's common lookup from installed contributions.

Initial resolution constructs an EntryPointLookup for lookup.default. A contributed Lookup takes precedence over a plain LookupProvider. If that lookup is also a provider, its get_lookup() supplies the answer on each subsequent call. A plain contributed lookup is cached directly, while a provider without a contributed lookup is wrapped in DelegatedLookup. Otherwise a ProxyLookup over the entry-point source is cached.

Loading and construction errors propagate. There is no public reset API, and experimental GlobalLookup does not participate in resolution.

Returns:

Type Description
Lookup

The resolved lookup, or the cached provider's current lookup.

lookup abstractmethod
lookup(cls)

Return one instance matching the searched type, or None.

A deferred member may be constructed by this call. When several members match, selection follows the source implementation. Generic storage uses no registration-order priority.

Parameters:

Name Type Description Default
cls type[T]

The Python type to search for, including a parent type.

required

Returns:

Type Description
T | None

A matching instance, or None when no instance is available.

__call__
__call__(cls)

Query this lookup using the same semantics as lookup(cls).

lookup_expected
lookup_expected(cls)

Return a matching instance, raising when the query returns None.

False-valued instances still satisfy this query. Exceptions from the source or a convertor propagate without being translated into absence.

Parameters:

Name Type Description Default
cls type[T]

The Python type to search for.

required

Returns:

Type Description
T

A non-None matching instance.

Raises:

Type Description
NoneLookupError

No matching instance is available.

lookup_result abstractmethod
lookup_result(cls)

Return a live view of members matching the searched type.

A result can be retained before any members match, allowing a consumer to observe later availability. Creating it does not retrieve all instances. Subclasses implement this method.

Parameters:

Name Type Description Default
cls type[T]

The Python type to search for.

required

Returns:

Type Description
Result[T]

A result for cls, including when no members match.

lookup_item
lookup_item(cls)

Return one matching item description, or None.

The inherited implementation selects the first item in the result's current collection. Item metadata can describe a deferred member without constructing its instance.

Parameters:

Name Type Description Default
cls type[T]

The Python type to search for.

required

Returns:

Type Description
Item[T] | None

A matching item, or None when none is available.

lookup_all
lookup_all(cls)

Retrieve matching instances as an immutable sequence.

Calls lookup_result(cls).all_instances(), which can construct deferred members. Ordering and duplicate handling follow the source implementation.

Parameters:

Name Type Description Default
cls type[T]

The Python type to search for.

required

Returns:

Type Description
Sequence[T]

Matching instances, or an empty sequence when none are available.

Lookup.get_default() resolves the application's common lookup. Its discovery rules, caching and initialisation effects are specified in Entry points and the default lookup.

NoneLookupError

Bases: Exception

Raised when a required lookup query finds no matching instance.

Result

A Result[T] represents the members matching one searched type, including an empty view before a dynamic source has any matching members. Its for_class property remains the searched type, which may be a parent of the classes reported by its members.

Member Value and effects
for_class: type[T] The searched type.
all_classes() -> Set[type[T]] An immutable set of represented types, with duplicate types removed.
all_instances() -> Sequence[T] An immutable sequence of matching instances. Retrieving them can construct deferred members.
all_items() -> Sequence[Item[T]] An immutable sequence of matching item descriptions.
listeners A registry for callbacks receiving this result when its membership may have changed.

A collection read describes the current view. An earlier returned collection does not gain or lose members when the source changes, although the objects within it remain mutable. Implementations may cache collections, and an instance collection can keep retrieved objects alive. For deferred members, all_classes() can report an advertised superclass before the object is constructed. Conversion and retention rules are covered in Dynamic membership and conversion.

Listeners and lifetime

The registry type is Listeners[Callable[[Result[T]], Any]]. Add a callback with result.listeners += callback and remove it with result.listeners -= callback. A callback receives the result as its sole argument, allowing it to read the matching members again. The argument contains no membership difference.

A result callback
def changed(result: Result[str]) -> None:
    print(result.all_instances())

Subscription does not deliver an initial snapshot. A notification indicates a possible change, so a caller reads the result again to obtain its current state. Fixed results expose the same registration interface but do not automatically publish change notifications.

Keep a strong reference to the result and to the callback or callback owner for the duration of observation. Retain the result you subscribed to for cleanup, because repeated queries need not return the same result object across all implementations. Observe results shows this ownership and cleanup pattern.

Notification policy depends on the source and its dispatcher:

Concern Common interface
Delivery No universal ordering or exactly-once guarantee.
Nested or concurrent access No common reentrant mutation or thread-safety policy.
Callback failures Error handling belongs to the dispatcher. Standard dynamic implementations use the Listeners default, which logs and suppresses ordinary callback Exceptions.

Lifetime and change notifications relates these policies to dispatch and application coordination.

Implementation requirements

A result implementation must provide the for_class property, all three collection methods and a listeners registry. Returned collections must be immutable, with empty collections for a query that has no matching members. Subclasses supply their own notification dispatcher.

Result

Bases: ABC, Generic[T]

Provide a live view of members matching one searched type.

Each collection read describes the view at that time. Earlier collections keep their contents when membership changes, and duplicates are permitted. Subclasses implement the collection methods and for_class, and supply a listeners registry whose callbacks receive this result.

Keep the result and callback or callback owner alive while observing. A notification signals possible change, so read the result again to refresh the consumer's state.

Attributes

for_class abstractmethod property
for_class

Return the searched type, which may be a parent of the represented types.

listeners instance-attribute
listeners

Subscribe to possible changes with += callback; unsubscribe with -=.

Callbacks receive this result, not a membership difference. Retain the result and callback or callback owner throughout observation, and read initial state explicitly because subscription does not deliver an initial snapshot.

Methods:

all_classes abstractmethod
all_classes()

Return an immutable set of the represented types.

Duplicate types are omitted. Deferred members can advertise their type without constructing their instances.

all_instances abstractmethod
all_instances()

Retrieve current matching instances as an immutable sequence.

Instance access can construct deferred members. Implementations may cache the sequence and thereby retain its instances strongly. Duplicates are permitted, and an empty view returns an empty sequence.

all_items abstractmethod
all_items()

Return an immutable sequence of the current matching item descriptions.

Item

An Item[T] describes one member independently of retrieving its object. Its metadata can therefore be useful while a deferred member has not yet been constructed.

Method Return value and limits
get_instance() -> T \| None The represented object, constructing it if necessary. The abstract interface permits None when no object can be supplied. Construction errors can raise an exception.
get_type() -> type[T] The represented type without requiring instance access. A converted item may report an advertised superclass before construction and the concrete class afterwards.
get_id() -> str A source-defined item identifier.
get_display_name() -> str Text suitable for presenting the item to a person.
str(item) -> str The value of get_id().

An item identifier is descriptive metadata, not a public lookup key. Standard direct items use str(instance) unless an explicit identifier is supplied, and use that identifier as their display name. Identifiers have no universal uniqueness or persistence guarantee. The public query interface searches by type, with no query by item identifier or Lookup.Template API.

An Item subclass must implement all four get_* methods. It inherits __str__(), which delegates to get_id(), and has no constructor options defined by the abstract interface.

Item

Bases: ABC, Generic[T]

Describe one member and provide access to its instance.

Metadata can be inspected separately from construction. Subclasses implement all four abstract methods. The source supplies the item's identifier and its display name.

Methods:

get_display_name abstractmethod
get_display_name()

Return a human-readable name suitable for presenting this item.

get_id abstractmethod
get_id()

Return the source-defined identifier for this item.

Standard direct items use str(instance) unless an explicit identifier is supplied. A convertor supplies identifiers for its deferred members.

get_instance abstractmethod
get_instance()

Retrieve the represented instance, constructing it when necessary.

Returns:

Type Description
T | None

The instance, or None when the implementation cannot supply it. Construction errors may propagate instead of returning None.

get_type abstractmethod
get_type()

Return the represented type without requiring instance access.

A deferred member can advertise its class or a superclass before its object has been constructed.

__str__
__str__()

Return the item identifier for display or debugging.