Repository navigation
Cache adapters in adapt call - #122
Conversation
There was a problem hiding this comment.
Pull request overview
Adds an adapter lookup cache to InterfaceType.adapt() to avoid repeatedly recomputing _get_adapter(cls, type(obj)), with cache invalidation hooks on adapter/type registration to keep results correct.
Changes:
- Introduces
_pi._adapter_cacheand uses it inInterfaceType.adapt()to memoize_get_adapter()results per(interface, obj_type). - Adds
clear_adapter_caches()and wires it intoInterfaceType.register()andregister_adapter()for cache invalidation. - Adds a new test suite covering caching behavior and several invalidation scenarios.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
| pure_interface/interface.py | Adds cache storage, cache-clearing helper, and uses cached adapter resolution inside InterfaceType.adapt() |
| pure_interface/adaption.py | Clears adapter caches on register_adapter() to avoid stale cached adapter lookups |
| tests/test_adapter_cache.py | Adds regression tests for caching and cache invalidation behavior |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 3 out of 3 changed files in this pull request and generated no new comments.
Suppressed comments (1)
pure_interface/interface.py:106
_adapter_cacheis a plaindictkeyed bytype, so it will keep strong references to every adapted runtime type and can grow without bound in long-running processes (especially when many dynamic/generated classes are seen). Consider usingweakref.WeakKeyDictionary(similar toself.adapters) so cached entries don’t prevent type objects from being garbage-collected; update tests that compare the cache to{}accordingly (e.g.,len(cache) == 0).
self.adapters = weakref.WeakKeyDictionary() # type: ignore
self.registered_types = weakref.WeakSet() # type: ignore
self.structural_subclasses: Set[type] = set()
self.impl_wrapper_type: Optional[type] = None
self._adapter_cache: Dict[type, Optional[Callable]] = {}
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
russell-stewart-seequent
left a comment
There was a problem hiding this comment.
You walk back up the MRO for cache clearing when new adapters are added. I think the equivalent is missing for registered types. The suggested changes here might fix this.
Closes #121
This adds a cache to return an adapter from a class to an interface. In my testing of a project this reduced the time substantially.
This also attempts to purge adapters from the cache when a new classes or adapters are registered.