Skip to content
How-to guide

Defer object creation

Register a conversion key when consumers need to discover an available member before paying the cost of constructing it. A Convertor describes the member from that key and creates its object when a consumer requests an instance. This guide uses the owner/content arrangement from Manage membership.

Implement the convertor

Subclass Convertor[K, T], where K is the conversion key's type and T is the produced object's type. Implement all four methods. Keep construction in convert() so that type(), id() and display_name() can answer metadata queries without creating the object. The Convertor reference specifies the four methods and their requirements. Advertise the product's class or one of its parents through type(), because this is how a query finds the member before construction.

The following sections build deferred_report.py, registering a report name as a string key and using created to show when conversion happens. Put expensive loading or preparation in Report's constructor or the convertor's convert() method.

deferred_report.py
from __future__ import annotations

from typing_extensions import override

from lookups import Convertor, GenericLookup, InstanceContent


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


class ReportConvertor(Convertor[str, Report]):
    def __init__(self) -> None:
        super().__init__()
        self.created: list[str] = []

    @override
    def convert(self, obj: str) -> Report:
        report = Report(obj)
        self.created.append(obj)
        return report

    @override
    def type(self, obj: str) -> type[Report]:
        return Report

    @override
    def id(self, obj: str) -> str:
        return f"report:{obj}"

    @override
    def display_name(self, obj: str) -> str:
        return f"Report: {obj}"

Use a product that supports weak references: an ordinary class such as Report does. If your class uses __slots__, provide weak-reference support, for example by including "__weakref__" in its slots unless a base class already supplies it. Returning None, an integer or another product without that support raises TypeError when the lookup tries to weakly cache it.

Register the key and inspect its metadata

Attach an InstanceContent to a GenericLookup, then register each key with its convertor. Choose distinct keys with stable equality and hashing so you can locate each registration when removing it. Retain both the key and convertor for that operation.

deferred_report.py
content = InstanceContent()
lookup = GenericLookup(content)
key = "quarterly"
convertor = ReportConvertor()
content.add(key, convertor)

item = lookup.lookup_item(Report)
assert item is not None
assert item.get_type() is Report
assert item.get_id() == "report:quarterly"
assert item.get_display_name() == "Report: quarterly"

result = lookup.lookup_result(Report)
assert result.all_items() == (item,)
assert result.all_classes() == frozenset({Report})
assert convertor.created == []

At this point the member is discoverable, but no Report has been created. Metadata methods can run during queries and membership changes, so they should remain cheap even when convert() is expensive. Choose an identifier that suits your application's use of the item: Lookups does not guarantee that identifiers are unique or persistent across runs.

Retrieve the object, then remove its registration

Request the instance through the item when the consumer is ready to use it. The first call below constructs the report. Keeping report alive lets the following lookup reuse it.

deferred_report.py
report = item.get_instance()
assert report is not None
assert report.name == "quarterly"
assert convertor.created == [key]
assert lookup.lookup(Report) is report
assert convertor.created == [key]

content.remove(key, convertor)
assert lookup.lookup_item(Report) is None
assert result.all_items() == ()
assert report.name == "quarterly"

Remove using the same key and convertor passed to add(), rather than the converted report. Removing the registration withdraws the member from future lookup queries while consumers can continue using any objects they already hold.

lookup(), lookup_expected(), lookup_all() and Result.all_instances() can also trigger conversion. Choose the query that suits the consumer using Queries, results and items.

Account for lifetime and conversion failures

Allow convert() to run more than once for a registration. The item holds its product weakly, so another retrieval can recreate it after collection. Keep a strong reference for as long as your application needs that particular object. A result's instance cache can also hold retrieved products strongly, and any instance collection retained by a caller extends their lifetime. Weak caching therefore does not guarantee prompt collection. See Lifetime and change notifications for the ownership details.

Handle construction errors at the point where you retrieve instances. Exceptions raised by convert() propagate to that caller, so a failed conversion is not reported as an absent member. Exceptions from metadata methods can also propagate from metadata queries or membership changes.

For other extension interfaces, see Extend Lookups.