Experimental API¶
lookups.experimental exports GlobalLookup, Runnable, ActionableMetaClass
and ActionableMixins. Use the first pair for a temporary execution scope and
the second to maintain the availability of objects offering an action.
Outside the SemVer compatibility policy
lookups.experimental is excluded from the project's
Semantic Versioning guarantees. Its interfaces may
change or be removed in any release, including minor and patch releases.
from lookups.experimental import (
ActionableMetaClass,
ActionableMixins,
GlobalLookup,
Runnable,
)
Execution-scoped lookup¶
GlobalLookup¶
GlobalLookup stores a current lookup separately for each thread. Its methods
are class methods and require no instance. It does not participate in
Lookup.get_default(), whose
application-wide discovery rules appear in
Entry points and the default lookup.
| Call | Behaviour |
|---|---|
GlobalLookup.current() -> Lookup \| None |
Returns this thread's current lookup, initially None. Outside an execution scope it does not consult the system fallback. |
GlobalLookup.set_system_lookup(lookup: Lookup) -> None |
Sets the shared fallback used by subsequent execute(None, runnable) calls. The fallback starts as None and is used by execute(None, runnable). Setting it leaves the current lookup unchanged. There is no public reset method. |
GlobalLookup.execute(default_lookup: Lookup \| None, runnable: Runnable) -> bool |
Selects the supplied lookup, or the system fallback if the argument is None. Applies the skip/run rules below and restores the previous current lookup afterwards. |
execute compares the selected lookup with the current lookup by identity.
If they are the same object, it returns False without calling runnable.run().
This includes an initial call with None when neither a current lookup nor a
system fallback has been set: both values are None, so the work is skipped.
When the lookups differ, execute makes the selected lookup current and calls
runnable.run() synchronously. On normal completion it restores the previous
value and returns True. If run() raises, it restores the previous value in
finally and propagates the exception. Nested execution therefore restores the
outer scope even after an inner exception. When a nested call selects the same
lookup, it skips the inner work.
from lookups import singleton
from lookups.experimental import GlobalLookup
selected = singleton("selected")
class Work:
def run(self) -> None:
assert GlobalLookup.current() is selected
assert GlobalLookup.execute(selected, self) is False
previous = GlobalLookup.current()
assert previous is not selected
assert GlobalLookup.execute(selected, Work()) is True
assert GlobalLookup.current() is previous
The selected lookup is thread-local, while the system fallback is shared across
threads. Selecting a lookup in one thread therefore does not propagate it to
another, and asynchronous tasks sharing a thread share its selected state.
There is no general concurrency or isolation guarantee. Ordinary default lookup
resolution remains independent: GlobalLookup does not inject its selected
lookup into calls to Lookup.get_default().
GlobalLookup ¶
Keep an experimental lookup scope in thread-local state.
This facility is separate from Lookup.get_default(). Scope restoration
happens even when work raises. Because the scope is thread-local, it does
not propagate to other threads, and asynchronous tasks sharing a thread
share its current scope.
Methods:¶
current
classmethod
¶
current()
Return this thread's current lookup, or None outside an active scope.
set_system_lookup
classmethod
¶
set_system_lookup(lookup)
Set the fallback used by execute(None, runnable).
execute
classmethod
¶
execute(default_lookup, runnable)
Run work with a temporary current lookup and restore the previous scope.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
default_lookup
|
Lookup | None
|
Temporary lookup, or |
required |
runnable
|
Runnable
|
Object whose |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
Exceptions from run() propagate after the previous scope is restored.
Runnable¶
Runnable is a protocol requiring run(self) -> None. An object with a
compatible run method can be passed to execute without inheriting from the
protocol. A bare function is not sufficient: execution calls .run() on the
supplied object. Any return value from that method is ignored.
Runnable ¶
Actionable families¶
ActionableMetaClass¶
Combine ActionableMetaClass with ActionableMixins to make instances available
through a family lookup. The class-level, read-only lookup: Lookup property
returns that lookup, creating it on first access.
A base actionable class shares its lookup with its subclasses, which do not receive independent registries. Separate base families have separate lookups. The current implementation chooses the oldest actionable base by scanning the class's method resolution order in reverse. Multiple inheritance does not merge family lookups.
The family lookup supports the ordinary query and result interfaces. Search for the family base type to find all its available actions, or for a subclass to select matching members. Membership changes follow the underlying dynamic lookup behaviour, including its ordering and notification limits.
ActionableMetaClass ¶
Bases: ABCMeta, type
Group experimental actionable instances behind a shared lookup.
Combine this metaclass with ActionableMixins. Initialisation registers an
instance automatically, while the owner must unregister it when its action
is no longer relevant. A hierarchy shares the lookup associated with its
oldest actionable base, allowing subclass instances to be discovered through
their common family.
Observe availability through result = ActionType.lookup.lookup_result(ActionType)
and result.listeners += callback, retaining both result and callback. Remove
the subscription with -= when observation ends.
ActionableMixins¶
ActionableMixins provides cooperative initialisation and explicit registration
operations for classes using ActionableMetaClass.
| Member | Behaviour |
|---|---|
ActionableMixins(*args, **kwargs) |
Calls the next constructor with the supplied arguments, then calls self.register(). A subclass defining its own constructor must call super().__init__() to obtain automatic registration. |
register() -> None |
Adds the instance to its family content if it is absent. Calling it again on an already registered ordinary member has no effect. It can make an unregistered action available again. |
unregister() -> None |
Removes the instance if present. Calling it again on an absent ordinary member has no effect. |
Presence checks use the underlying content's equality and hashing behaviour. Observers of the family lookup can react when an action registers or unregisters.
Registration retains the instance
The family content holds registered objects strongly. Dropping an
application's reference does not remove the action or allow its collection.
The owner must call unregister() when the action is no longer relevant.
Other application references and result caches can still retain the object
after removal.
The following specimen registers a save action during construction and removes
it after a successful save. If handle_save() raises, save() does not reach
unregister(), so the action remains available.
from abc import abstractmethod
from lookups import Result
from lookups.experimental import ActionableMetaClass, ActionableMixins
class Savable(ActionableMixins, metaclass=ActionableMetaClass):
def save(self) -> None:
self.handle_save()
self.unregister()
@abstractmethod
def handle_save(self) -> None: ...
class Document(Savable):
def __init__(self) -> None:
self.saved = False
super().__init__()
def handle_save(self) -> None:
self.saved = True
result = Savable.lookup.lookup_result(Savable)
changes: list[Result[Savable]] = []
def changed(updated: Result[Savable]) -> None:
changes.append(updated)
result.listeners += changed
document = Document()
try:
assert Document.lookup is Savable.lookup
assert document in result.all_instances()
document.save()
assert document.saved
assert document not in result.all_instances()
assert changes and all(updated is result for updated in changes)
finally:
result.listeners -= changed
document.unregister()
Keep both the result and callback alive while observing a family, and remove the callback when observation ends. Notifications receive the result, rather than a list of added or removed actions. See Lifetime and change notifications for ownership and retention details.
ActionableMixins ¶
Register actionable instances during cooperative initialisation.
Use with ActionableMetaClass, call super().__init__() in subclasses, and
explicitly unregister when the action is finished. Registration retains the
object strongly, so explicit unregistration is needed even when the
application releases its own reference.