Skip to content
Tutorial

Observe a changing selection

Build a small selection that reports its current members whenever you change it. You will keep one live result, start with no selected objects, then add, replace and remove members without creating another result. The program prints the selection after each change and finishes by unsubscribing its callback.

Prepare your environment

Complete Find your first objects first, using the same environment with Lookups installed.

The finished program will print:

Expected output
Initial selection: []
Selection changed: ['report.txt']
Selection changed: ['chart.svg', 'report.txt']
Selection changed: ['chart.svg']
Selection changed: []
After unsubscribe: ['report.txt']

Keep a result for an empty selection

Create changing_selection.py with this code:

changing_selection.py
from lookups import GenericLookup, InstanceContent, Result


class Document:
    def __init__(self, name: str) -> None:
        self.name = name


content = InstanceContent()
selection = GenericLookup(content)
selected = selection.lookup_result(Document)


def selection_changed(result: Result[Document]) -> None:
    print("Selection changed:", sorted(member.name for member in result.all_instances()))


selected.listeners += selection_changed
print("Initial selection:", sorted(member.name for member in selected.all_instances()))

Run the program:

Run the example
python changing_selection.py
Expected output
Initial selection: []

The owner changes membership through InstanceContent, while consumers use GenericLookup to query the available objects. The selected result is a live view of members matching Document, even though none are available yet.

Registering selection_changed subscribes it to possible changes. Subscription does not call it with an initial selection, so the final line reads that state explicitly. When a notification arrives, the callback receives the result and reads its current members with all_instances(). The argument does not describe which objects were added or removed.

Keep the observation alive

Keep strong references to the result and to the callback or its owner for as long as you want notifications. Here, the module variables selected and selection_changed retain both. Read all_instances() again to retrieve the current selection, because a collection returned by an earlier read does not update itself.

Add two selected documents

Append this code to changing_selection.py:

changing_selection.py
report = Document("report.txt")
chart = Document("chart.svg")

content.add(report)
content.add(chart)

Run python changing_selection.py again. After the initial empty selection, the callback prints:

Expected output
Selection changed: ['report.txt']
Selection changed: ['chart.svg', 'report.txt']

Both documents match the result's searched type. Each addition changes what the retained result sees, so the callback can read the new selection through the same result. With the default InstanceContent() used here, generic notifications run synchronously in the calling thread, before the mutation call returns.

The callback sorts names solely to make its output predictable. GenericLookup does not promise registration order or a priority between members.

Replace the selection, then clear its last member

Append these operations:

changing_selection.py
content.set([chart])
content.remove(chart)

Run python changing_selection.py again. The new lines are:

Expected output
Selection changed: ['chart.svg']
Selection changed: []

set([chart]) replaces the lookup's entire membership with the supplied collection, leaving only the chart selected. remove(chart) removes that remaining registration. The result stays usable when the selection becomes empty, just as it was at the start.

Stop observing

Append this final block:

changing_selection.py
selected.listeners -= selection_changed
content.add(report)
print("After unsubscribe:", sorted(member.name for member in selected.all_instances()))

Run python changing_selection.py again. The final line is:

Expected output
After unsubscribe: ['report.txt']

There is no Selection changed: message for this addition because you removed the callback. Unsubscribing ends the observation while leaving the lookup and retained result available for further changes and queries.

For application use, continue with Manage membership and Observe results. Combine and switch lookups covers selections drawn from several sources. Lifetime and change notifications explains result and callback ownership, and Dynamic membership and conversion describes the interfaces used here.

Complete example

Show the complete changing_selection.py
changing_selection.py
from lookups import GenericLookup, InstanceContent, Result


class Document:
    def __init__(self, name: str) -> None:
        self.name = name


content = InstanceContent()
selection = GenericLookup(content)
selected = selection.lookup_result(Document)


def selection_changed(result: Result[Document]) -> None:
    print("Selection changed:", sorted(member.name for member in result.all_instances()))


selected.listeners += selection_changed
print("Initial selection:", sorted(member.name for member in selected.all_instances()))

report = Document("report.txt")
chart = Document("chart.svg")

content.add(report)
content.add(chart)

content.set([chart])
content.remove(chart)

selected.listeners -= selection_changed
content.add(report)
print("After unsubscribe:", sorted(member.name for member in selected.all_instances()))