From 48466cbccfb87fda6bb988fe4c8007d10734cdff Mon Sep 17 00:00:00 2001 From: Brian Pugh Date: Tue, 24 Oct 2023 08:55:12 -0700 Subject: [PATCH] optimize rereferencing --- autoregistry/_registry.py | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/autoregistry/_registry.py b/autoregistry/_registry.py index 25d6cf3..22ac744 100644 --- a/autoregistry/_registry.py +++ b/autoregistry/_registry.py @@ -35,19 +35,22 @@ def cls(self): @cls.setter def cls(self, new_cls: type): if self._cls is not None: - self._rereference(self._cls, new_cls) + self._rereference(self._cls, new_cls, root=True) self._cls = new_cls - def _rereference(self, old_cls: type, new_cls: type) -> None: - """Recursively updates all registry references from ``old_cls`` to ``new_cls``.""" - # TODO: this could be optimized by only recursively apply to recursive parents - # And not searching self at first _rereference iteration. - for k, v in self.items(): - if v is old_cls: - self[k] = new_cls + def _rereference(self, old_cls: type, new_cls: type, root=False) -> None: + """Recursively updates all registry references from ``old_cls`` to ``new_cls``. - for parent_registry in self.walk_parent_registries(): - parent_registry._rereference(old_cls, new_cls) + Used when a "clone" class is created, in libraries like ``attrs``. + """ + if not root: + for k, v in self.items(): + if v is old_cls: + self[k] = new_cls + + if root or self.config.recursive: + for parent_registry in self.walk_parent_registries(): + parent_registry._rereference(old_cls, new_cls) def walk_parent_registries(self) -> Generator["_Registry", None, None]: """Iterates over immediate parenting classes and returns their ``_Registry``."""