Skip to content

Commit

Permalink
Accelerate lazy lookup.
Browse files Browse the repository at this point in the history
  • Loading branch information
riga committed Jul 19, 2024
1 parent 0923b1f commit dd5f068
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions order/unique.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,17 +202,14 @@ def _build_lazy_object(self, key, silent=False):
return None

# build the object
obj = self._lazy_factories[key](self)
obj = self._lazy_factories.pop(key)(self)
if not isinstance(obj, self._cls):
raise TypeError(
"lazy factory function '{}' of {} produced object of wrong type: {}".format(
key, self, obj,
),
)

# remove the key from the lazy factories
del self._lazy_factories[key]

return self.add(obj, overwrite=True)

def _build_lazy_objects(self, silent=False):
Expand All @@ -221,6 +218,9 @@ def _build_lazy_objects(self, silent=False):
to the index. When *silent* is *True*, no exception is raised when an object could not be
built.
"""
if not self._lazy_factories:
return

for key in list(self._lazy_factories.keys()):
self._build_lazy_object(key, silent=silent)

Expand Down Expand Up @@ -276,7 +276,7 @@ def add(self, *args, **kwargs):
obj = self._cls(*args, **kwargs)

# check if obj is a duplicate and whether it should overwrite or cause an exception
for _obj in self:
for _obj in self._index:
if obj.name == _obj.name:
if not overwrite:
raise DuplicateNameException(self._cls, obj.name)
Expand All @@ -288,6 +288,12 @@ def add(self, *args, **kwargs):
self.remove(obj.id)
break

# also check for lazy factories
if obj.name in self._lazy_factories:
if not overwrite:
raise DuplicateNameException(self._cls, obj.name)
self._lazy_factories.pop(obj.name)

# add to the index
self._index.append(obj)

Expand Down Expand Up @@ -327,7 +333,7 @@ def get(self, obj, default=_no_default):
if isinstance(obj, self._cls):
obj = obj.name

for _obj in self:
for _obj in self._index:
if obj in (_obj.name, _obj.id):
return _obj

Expand Down

0 comments on commit dd5f068

Please sign in to comment.