Skip to content

Commit

Permalink
Optimize init
Browse files Browse the repository at this point in the history
  • Loading branch information
kiendang committed Oct 22, 2023
1 parent e4e0068 commit 06c2a0a
Showing 1 changed file with 16 additions and 25 deletions.
41 changes: 16 additions & 25 deletions packages/syft/src/syft/types/dicttuple.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# stdlib
from collections import OrderedDict
from collections import deque
from collections.abc import Collection
from collections.abc import Iterable
from collections.abc import KeysView
Expand Down Expand Up @@ -54,21 +55,14 @@ def __call__(
return obj

elif isinstance(__value, Mapping) and __key is None:
keys = OrderedDict()
values = []

for i, k in enumerate(__value.keys()):
keys[k] = i
values.append(__value[k])

obj = cls.__new__(cls, values)
obj.__init__(keys)
obj = cls.__new__(cls, __value.values())
obj.__init__(__value.keys())

return obj

elif isinstance(__value, Iterable) and __key is None:
keys = OrderedDict()
values = []
values = deque()

for i, (k, v) in enumerate(__value):
keys[k] = i
Expand All @@ -79,27 +73,17 @@ def __call__(

return obj

elif isinstance(__value, Iterable) and isinstance(__key, Callable):
keys = OrderedDict()
values = []

for i, v in enumerate(__value):
keys[i] = __key(v)
values.append(v)
elif isinstance(__value, Iterable) and isinstance(__key, Iterable):
keys = OrderedDict((k, i) for i, k in enumerate(__key))

obj = cls.__new__(cls, values)
obj = cls.__new__(cls, __value)
obj.__init__(keys)

return obj

elif isinstance(__value, Iterable) and __key is not None:
if len(__key) != len(__value):
raise ValueError("`__key` has to be of the same length as `__value`")

keys = OrderedDict((k, i) for i, k in enumerate(__key))

elif isinstance(__value, Iterable) and isinstance(__key, Callable):
obj = cls.__new__(cls, __value)
obj.__init__(keys)
obj.__init__(__key)

return obj

Expand Down Expand Up @@ -177,9 +161,16 @@ def __init__(
self.__mapping = MappingProxyType(
OrderedDict((k, i) for i, k in enumerate(__value))
)
elif isinstance(__value, Callable):
self.__mapping = MappingProxyType(
OrderedDict((__value(v), i) for i, v in enumerate(self))
)

super().__init__()

if len(self.__mapping) != len(self):
raise ValueError("__keys and __values do not have the same length")

@overload
def __getitem__(self, __key: _KT) -> _VT:
...
Expand Down

0 comments on commit 06c2a0a

Please sign in to comment.