Diagnose lookup problems¶
Use this guide when a query finds no member, a result appears stale or a callback does not run. Start with the searched type and source, then check observation and construction separately. Run diagnostics with the interpreter that runs the application. If imports fail, follow Install Lookups first.
Check what the query searches¶
Pass the Python type that the member implements or inherits from. A method with the right name does not establish a match, and an entry-point name or item identifier is not a searched type. If a contribution and its consumer import separate definitions of an otherwise identical class, check those imports: they need the same shared role type.
Reduce a failed query to the following shape, substituting the searched type and a member from your source:
from lookups import NoneLookupError, fixed
class Renderer:
pass
class PdfRenderer(Renderer):
pass
member = PdfRenderer()
lookup = fixed(member)
assert lookup.lookup(Renderer) is member
assert lookup.lookup(str) is None
assert lookup.lookup_result(str).all_items() == ()
try:
lookup.lookup_expected(str)
except NoneLookupError:
print("No str member")
This prints No str member. An empty result is a valid result, and
NoneLookupError means the required query returned None. Use is None to check
absence, because a matching object can be false-valued. Source and conversion exceptions are separate failures and are not
translated into NoneLookupError.
For your actual lookup, inspect lookup.lookup_result(object).all_items() and
each item's get_type() and get_id(). This can reveal a different registered
type or a missing registration without retrieving deferred instances. Metadata
methods can still raise, and custom implementations determine their own effects.
If the member is absent, check the owner's registration and any composite source
list using Manage membership or
Combine and switch lookups. See the
query reference for matching and absence
rules.
Check result and callback ownership¶
Keep the result alive for the whole observation, together with the callback or the object owning its bound method. A subscription alone does not retain them. If notifications stop after a setup function returns, inspect where those references are stored. Also confirm that cleanup has not already removed the callback.
Use a retained function and result to isolate subscription from application code:
from lookups import GenericLookup, InstanceContent, Result
content = InstanceContent()
lookup = GenericLookup(content)
content.add("already present")
result = lookup.lookup_result(str)
reads: list[tuple[str, ...]] = []
def changed(updated: Result[str]) -> None:
reads.append(tuple(updated.all_instances()))
result.listeners += changed
try:
assert reads == []
changed(result)
assert reads == [("already present",)]
content.set(["replacement"])
assert reads[-1] == ("replacement",)
assert len(reads) == 2
finally:
result.listeners -= changed
Subscription does not read the initial state, so call your refresh function explicitly as above. On notification, read from the callback's result because an earlier collection is not a live view. This reproduction uses synchronous generic notifications. Fixed lookups do not automatically notify, and an executor changes when generic callbacks run. Follow Observe results for subscription lifetime and executor cleanup.
If this check succeeds but the application remains stale, add logging at entry and exit of its callback. The default Listeners dispatcher logs ordinary callback exceptions and suppresses them, so inspect the logs for a callback that started but failed before updating the application. See listeners and lifetime for subscription details.
Refresh a changed provider explicitly¶
If a provider now supplies another source but queries still return the old
members, check delegated.delegate. Ordinary DelegatedLookup queries do not
consult the provider again. The owner must call lookup_updated() after changing
the source:
from typing_extensions import override
from lookups import DelegatedLookup, Lookup, LookupProvider, singleton
class Selection(LookupProvider):
def __init__(self, current: Lookup) -> None:
super().__init__()
self.current = current
@override
def get_lookup(self) -> Lookup:
return self.current
provider = Selection(singleton("old"))
delegated = DelegatedLookup(provider)
result = delegated.lookup_result(str)
provider.current = singleton("new")
assert delegated.lookup(str) == "old"
delegated.lookup_updated()
assert delegated.delegate is provider.current
assert result.all_instances() == ("new",)
If refresh still keeps the old source, inspect equality on the two lookups: an
equal replacement need not be adopted. The provider must return an initialised
Lookup. Use an empty lookup when there are no members to supply. See
construction and explicit refresh.
Inspect installed entry points before constructing the lookup¶
If an entry-point group appears empty, inspect its metadata with the interpreter that runs the application. Replace the example distribution and group names:
python -m pip show acme-report-contribution
python -c "from importlib.metadata import entry_points; print(entry_points(group='acme_reports.renderers'))"
If the distribution is missing, install it in this environment. If no entries
appear, check the group's spelling and reinstall after changing package metadata.
Source files being importable does not register an entry point. The application
default uses lookup.default, with singular lookup. Follow
Discover package contributions for a complete
registration and installation check.
If EntryPointLookup(group) raises, follow the traceback to the contribution's
import or factory. Construction loads and calls every target immediately, with
no per-contribution error isolation. Check that the target exists, is callable
without arguments and returns a non-None object. A factory returning None
raises ValueError('None cannot be a lookup member'). Other loading and factory
errors propagate rather than producing an empty lookup.
An existing entry-point lookup has fixed membership. After changing installed contributions, restart the application and construct a new lookup. Default resolution is cached and has no public reset API. See construction, queries and lifetime and default lookup resolution.
Separate deferred metadata from product creation¶
If lookup_item() succeeds but instance retrieval fails, inspect the convertor's
convert() method and its returned object. Item and class metadata can exist
before the product has been created. Test the product's weak-reference support
independently with weakref.ref(product): a failure here also prevents the item
from weakly caching it.
For example, an integer product produces this diagnostic:
import weakref
try:
weakref.ref(0)
except TypeError as error:
print(error)
This raises and catches a TypeError because integers do not support weak
references. Return an object that supports weak references. For a slotted class, include "__weakref__" in its slots unless
a base class already supplies that support. The
deferred-creation guide shows a suitable product and all four
required convertor methods.
If creation happens again later, check which references retain the product. Converted items cache it weakly. Keep a strong reference while the application needs the same product, and make the convertor safe to call again after collection. See lifetime and failures.
Check how a member was registered¶
If removing a deferred member fails, use the conversion key and convertor supplied
to add(), rather than the created product. The expression product in content
checks direct-member registration and does not test whether a converted product
is available. Query the lookup by the product's type to check its availability.
Manage membership covers direct registration and removal,
and Defer object creation shows conversion-key registration.
If two deferred registrations appear to collapse into one, compare their keys. Equal, hashable conversion keys identify the same registration even when their convertors differ. Give distinct deferred members distinct keys, and check custom equality and hashing when registrations behave unexpectedly. See InstanceContent for the registration interface.
If a query selects a different member from the one you expected, inspect all matching items before assuming registration failed. Generic lookup membership does not establish a priority order. When combining sources, check their order as described in Combine and switch lookups.