Dynamic membership and conversion¶
GenericLookup exposes changing membership to consumers. Its owner changes that
membership through an attached InstanceContent, which can hold existing objects
or conversion keys for objects created on demand. Consumers use the common
query, result and item interfaces.
from lookups import GenericLookup, InstanceContent
content = InstanceContent()
lookup = GenericLookup(content)
content.add("available")
assert lookup.lookup(str) == "available"
GenericLookup¶
GenericLookup(content=None) accepts an optional owner-side content handle.
Without content, a subclass can supply membership through the protected pair
helpers described below. AbstractLookup is an alias of GenericLookup, so both
names have the same constructor and extension hooks.
Storage is created on first use, which can be a mutation or a query. Attaching
content with buffered registrations also creates storage to transfer them. A
content object attaches to one lookup only: another attachment raises
RuntimeError, including another attempt with the same lookup. There is no
public detach or reattach operation.
Matching uses the member's reported type, including its superclasses. Storage uses a set, so neither single-member selection nor collection order has a registration-order guarantee. Keep application priority separate from the order in which members are added.
Subclass hooks¶
The hooks have no required overrides. A subclass can override either hook and use the pair helpers without implementing the common queries itself.
| Hook | Call conditions and facilities |
|---|---|
_initialise() -> None |
Runs once when storage is first created. Storage already exists, so the hook can populate it with pair helpers. |
_before_lookup(cls: type[object]) -> None |
Runs before lookup_item() and lookup_result(), and through them the other common queries. It also runs before each result collection read, including reads from a retained result. |
_add_pair(pair, notify_in=None) -> bool |
Adds a pair, returning True when new and False when an equal pair exists. |
_remove_pair(pair, notify_in=None) -> None |
Removes an equal pair, raising KeyError when absent. |
_set_pairs(pairs, notify_in=None) -> None |
Replaces membership with a collection of pairs. |
_initialise() runs as part of the first storage operation, rather than after a
fixed constructor phase. In particular, passing non-empty content to the base
constructor can invoke it before the subclass constructor resumes. Fields needed
by the hook must already exist. Because the first query can call _before_lookup() before
storage has been created, overrides must not assume that _initialise() has
already run.
Avoid recursive queries that depend on initialisation having finished or that
invoke the same pre-query hook again.
The pair helpers notify affected held results. Their optional notify_in
argument accepts an executor, with None selecting synchronous dispatch. A
nested mutation during an active storage modification can raise RuntimeError.
Reentrant queries and changes have no general safety guarantee.
GenericLookup ¶
Bases: Lookup
Expose changing membership while keeping owner-side changes separate.
Consumers query this object while its owner changes availability through an
attached InstanceContent. Subclasses can instead supply pairs through protected
helpers and prepare data in _initialise or _before_lookup.
Storage is created on first use and uses a set, so competing matches have no
registration-order guarantee. AbstractLookup is an alias of this class.
Methods:¶
__init__ ¶
__init__(content=None)
Create a lookup and optionally attach its owner-side content.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
Content | None
|
The content handle to attach, or |
None
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
The content is already attached to a lookup. |
_initialise ¶
_initialise()
Populate initial pairs when storage is first created.
This hook runs once on first storage use. Pair helpers are available because storage already exists. Avoid recursive queries that depend on initialisation having finished.
_before_lookup ¶
_before_lookup(cls)
Prepare membership before a query or a result collection read.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
type[object]
|
The searched type. |
required |
This hook can run repeatedly, including on a retained result. Avoid recursively issuing a query that invokes the same hook.
_add_pair ¶
_add_pair(pair, notify_in=None)
Register a pair and notify affected results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pair
|
Pair[T]
|
The item and matching metadata to register. |
required |
notify_in
|
Executor | None
|
Notification executor, or |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
|
_remove_pair ¶
_remove_pair(pair, notify_in=None)
Remove a registered pair and notify affected held results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pair
|
Pair[T]
|
Pair to remove according to storage equality. |
required |
notify_in
|
Executor | None
|
Notification executor, or |
None
|
Raises:
| Type | Description |
|---|---|
KeyError
|
No equal pair exists in current storage. |
_set_pairs ¶
_set_pairs(pairs, notify_in=None)
Replace all registered pairs and notify affected held results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pairs
|
Collection[Pair[T]]
|
The replacement collection. |
required |
notify_in
|
Executor | None
|
Notification executor, or |
None
|
InstanceContent¶
InstanceContent(notify_in=None) creates an empty, unattached content handle. It
inherits this constructor from Content.
Changes made before attachment are buffered until GenericLookup(content)
transfers them into lookup storage. Keep the content handle with the
owner and give consumers the lookup when they need query access only.
Use the content handle to register members or replace the complete collection. The lookup remains the consumer-facing query interface.
| Operation | Behaviour |
|---|---|
add(instance, convertor=None) -> bool |
Registers an object, or a key with a convertor. Returns True for a new registration and False when an equal member was present. |
remove(instance, convertor=None) -> None |
Removes a registration using the member or key and convertor supplied to add(). An absent registration raises KeyError after attachment or ValueError before attachment. |
set(instances, convertor=None) -> None |
Replaces membership with the supplied collection. An empty collection clears it. |
instance in content -> bool |
Tests direct-member membership using equality. For deferred members, retain the key and convertor used to register them. |
Members and conversion keys must be non-None. Passing None raises ValueError.
Membership equality¶
Direct registrations use object equality. Adding an equal direct member replaces its registration without a membership notification. Converted registrations are identified by their conversion keys, so use a distinct key for each member you want to expose.
Notifications and retention¶
Membership changes notify affected held results. With notify_in=None, these
notifications run synchronously in the mutation's calling thread. Supplying an
executor requests dispatch through that executor.
| Concern | Contract |
|---|---|
| Executor ownership | The caller owns the executor and its shutdown. |
| Concurrency | Selecting an executor does not establish general lookup thread safety. |
| Dispatch control | There are no completion, cancellation or exception-aggregation guarantees. |
| Delivery | Notification order, exactly-once delivery and reentrant mutation remain unspecified. |
A callback receives the affected Result, whose membership it can read again.
Keep strong references to the result and to the callback or its owner while
observing changes. See Observe results
for subscription and cleanup.
Direct registrations retain their objects strongly. Deferred registrations retain the key and convertor strongly, while the item weakly caches the converted product. A result's instance collection can retain retrieved products strongly, so weak caching does not guarantee prompt collection. Ownership is covered in Lifetime and change notifications.
InstanceContent ¶
Bases: Content
Control a generic lookup's membership through an owner handle.
Attach this content to a GenericLookup, then give consumers the lookup.
Direct registrations retain their objects. With a convertor, a registration
instead holds a key that describes the member before construction.
The inherited constructor accepts notify_in for executor-based dispatch.
Changes made before attachment are buffered until the lookup attaches.
Each content object belongs to one lookup.
Methods:¶
add ¶
add(instance, convertor=None)
Register a member directly or through a conversion key.
An equal direct addition replaces the existing registration without a membership notification. For deferred members, use the same key and convertor when removing the registration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instance
|
T
|
The member, or the key passed to the convertor. |
required |
convertor
|
Convertor[T, Any] | None
|
Description and creation rules, or |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
The member or conversion key is |
remove ¶
remove(instance, convertor=None)
Remove a registration using the arguments supplied to add.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instance
|
T
|
The registered member or conversion key. |
required |
convertor
|
Convertor[T, Any] | None
|
The convertor used for a deferred registration. |
None
|
set ¶
set(instances, convertor=None)
Replace membership with the supplied collection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instances
|
Collection[Any]
|
Direct members, or conversion keys when using a convertor. |
required |
convertor
|
Convertor[Any, Any] | None
|
Shared creation rules for the keys, or |
None
|
Convertor¶
Convertor[K, T] describes a deferred member whose registered key has type K
and whose product has type T. A subclass must implement all four methods. The
abstract interface defines no constructor options.
| Method | Required return and use |
|---|---|
convert(obj: K) -> T |
Creates the object represented by the registered key. The product must support weak references. |
type(obj: K) -> type[T] |
Advertises the product's class or a superclass without creating the object. Used for matching and type metadata before construction. |
id(obj: K) -> str |
Supplies Item.get_id() for the key. There is no universal uniqueness or persistence guarantee for identifiers. |
display_name(obj: K) -> str |
Supplies Item.get_display_name() for presentation. |
Construction and metadata¶
lookup_item(), lookup_result() and the result's all_items() and
all_classes() can describe deferred members without calling convert().
Retrieving an instance through lookup(), lookup_expected(), lookup_all(),
Result.all_instances() or Item.get_instance() can call it. Metadata methods
can still run during queries and membership changes, so they should describe the
product without constructing it themselves.
The convertor advertises the product's class or a superclass through type(key).
Once the product exists, its item can report the concrete class through
get_type().
Lifetime and failures¶
The converted item's weak cache permits another call to convert() after the
previous product is collected. Conversion is not guaranteed to run exactly
once. Retrieved objects and result instance caches can extend the product's
lifetime, so conversion is not guaranteed to run on every access either.
Exceptions from convertor methods propagate. Returning None, an integer or
another product without weak-reference support raises TypeError when the item
tries to cache it. A conversion failure is not translated into an absent member.
Classes using __slots__ need weak-reference support if their instances are used
as converted products.
Convertor ¶
Bases: ABC, Generic[K, T]
Describe and construct deferred members from registered keys.
Implement all four methods. Metadata methods should describe the product without constructing it. Products must support weak references for item-level caching, while result caches can retain retrieved products strongly.
Methods:¶
convert
abstractmethod
¶
convert(obj)
Construct the member represented by obj.
The item weakly caches the product, so this method can run again after collection. Construction and weak-reference errors propagate to callers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
K
|
The registered conversion key. |
required |
Returns:
| Type | Description |
|---|---|
T
|
A weak-referenceable member instance. |
type
abstractmethod
¶
type(obj)
Advertise the product's class or a superclass without constructing it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
K
|
The registered conversion key. |
required |
Returns:
| Type | Description |
|---|---|
type[T]
|
The type exposed by |
id
abstractmethod
¶
id(obj)
Return the identifier exposed by Item.get_id() for this key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
K
|
The registered conversion key. |
required |
display_name
abstractmethod
¶
display_name(obj)
Return the text exposed by Item.get_display_name() for this key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
K
|
The registered conversion key. |
required |
Module-level extension support¶
Pair and Content are importable from lookups.generic_lookup, rather than
from the package root. They support the documented generic lookup extension interfaces and follow the
public API versioning policy. Internal Storage,
Transaction and SetStorage classes are not extension interfaces.
Pair¶
Pair[T] extends Item[T]. An implementation
must supply the four item methods and these two predicates:
| Method | Meaning |
|---|---|
instance_of(cls) -> bool |
Whether the pair can represent an instance matching the searched type. |
creator_of(obj) -> bool |
Whether the pair has already supplied that identical object. |
The interface defines no constructor options. Pairs passed to the mutation
helpers must work with set hashing and equality. Generic matching uses
get_type() and issubclass(), so overriding instance_of() alone does not
change selection. Implement a custom Lookup when selection requires a different
matching rule.
Pair ¶
Bases: Item[T]
Extend Item with matching and instance-origin predicates.
This module-level support interface is used by generic lookup subclass hooks.
Implement the four Item methods plus instance_of and creator_of.
Generic matching uses get_type() and issubclass(), so
arbitrary predicate implementations alone do not provide custom matching.
Content¶
Content(notify_in=None) supplies attachment and pair-level mutation support for
owner-side adapters. Its constructor is also the inherited constructor of
InstanceContent. A custom content subclass can translate its own operations
into _add_pair(), _remove_pair() and _set_pairs(). Passing the content to
GenericLookup attaches it.
These helpers buffer changes until attachment, then forward them to the lookup
with the constructor's notification executor. Unlike the lookup's pair helpers,
they use the executor chosen at construction. pair in content tests pair
membership, while InstanceContent accepts direct objects.
Content ¶
Bases: Container[Any]
Attach an owner-side membership handle to one generic lookup.
Changes before attachment are buffered. Once attached, the lookup owns
storage and subclasses can adapt pair-level changes through the protected
helpers. InstanceContent is the usual handle for application code.
Methods:¶
__init__ ¶
__init__(notify_in=None)
Create an unattached content handle with optional notification dispatch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
notify_in
|
Executor | None
|
Executor for generic result notifications, or |
None
|
Executor ownership and shutdown remain the caller's responsibility. This option does not establish general lookup thread safety.
_add_pair ¶
_add_pair(pair)
Register a pair, buffering it until the lookup attaches.
Returns:
| Type | Description |
|---|---|
bool
|
|
For owner-side changes, see Manage membership. Deferred registration is covered in Defer object creation, and custom implementations in Extend Lookups.