Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove builders #68

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 1 addition & 68 deletions immutablecollections/_immutabledict.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,9 @@
from typing import (
Callable,
Dict,
Generic,
Iterable,
Iterator,
Mapping,
MutableMapping,
Optional,
Set,
Tuple,
Expand Down Expand Up @@ -134,7 +132,7 @@ def of(dict_: AllowableSourceType) -> "ImmutableDict[KT, VT]":
if isinstance(dict_, ImmutableDict):
return dict_
else:
return ImmutableDict.builder().put_all(dict_).build() # type:ignore
return immutabledict(dict_)

@staticmethod
def empty() -> "ImmutableDict[KT, VT]":
Expand All @@ -143,14 +141,6 @@ def empty() -> "ImmutableDict[KT, VT]":
"""
return _EMPTY

@staticmethod
def builder() -> "ImmutableDict.Builder[KT, VT]":
"""
Deprecated - prefer to build a list of tuples and pass them to the ``immutabledict``
module-level factory
"""
return ImmutableDict.Builder()

@staticmethod
def index(
items: Iterable[VT], key_function: Callable[[VT], KT]
Expand All @@ -163,9 +153,6 @@ def index(
"""
return immutabledict((key_function(item), item) for item in items)

def modified_copy_builder(self) -> "ImmutableDict.Builder[KT, VT]":
return ImmutableDict.Builder(source=self)

def filter_keys(self, predicate: Callable[[KT], bool]) -> "ImmutableDict[KT, VT]":
"""
Filters an ImmutableDict by a predicate on its keys.
Expand Down Expand Up @@ -197,60 +184,6 @@ def __reduce__(self):
_repr = tuple(self.items())
return (immutabledict, (_repr,))

class Builder(Generic[KT2, VT2]):
def __init__(self, source: "ImmutableDict[KT2,VT2]" = None) -> None:
self._dict: MutableMapping[KT2, VT2] = {}
self.source = source

def put(self: SelfType, key: KT2, val: VT2) -> SelfType:
if self.source:
# we only lazily copy the contents of source because if no changes are ever made
# we can just reuse it
# we need the temporary variable because the call to put_all below will
# call this put method again and we need self.source to be None to avoid an
# infinite loop
tmp_source = self.source
# Defend against multithreading scenario where another thread has cleared
# self.source already. Not that this code is meant to be thread-safe anyway,
# but at least you won't get non-deterministic crashes
if tmp_source is not None:
self.source = None
self.put_all(tmp_source)

self._dict[key] = val
return self

def put_all(
self: SelfType, data: Union[Mapping[KT2, VT2], Iterable[IT2]]
) -> SelfType:
if isinstance(data, Mapping):
for (k, v) in data.items():
self.put(k, v)
elif isinstance(data, Iterable):
# mypy is confused
for (k, v) in data: # type: ignore
self.put(k, v)
else:
raise TypeError(
"Can only initialize ImmutableDict from another dictionary or "
"a sequence of key-value pairs"
)
return self

def __setitem__(self, key: KT2, value: VT2) -> None:
self.put(key, value)

def build(self) -> "ImmutableDict[KT2, VT2]":
if self.source:
# if any puts were done this will be None. If no puts were done we can return
# the ImmutableDict we were based on because we will be identical and immutable
# objects can be safely shared
return self.source
if self._dict:
return _RegularDictBackedImmutableDict(self._dict)
else:
return _EMPTY


class _RegularDictBackedImmutableDict(ImmutableDict[KT, VT]):
__slots__ = ("_dict", "_hash")
Expand Down
12 changes: 7 additions & 5 deletions immutablecollections/_immutablemultidict.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,10 +321,9 @@ def __init__(
source: Optional["ImmutableMultiDict[KT2,VT2]"] = None,
order_key: Callable[[VT2], Any] = None,
) -> None:
self._dict: MutableMapping[KT2, ImmutableSet.Builder[VT2]] = defaultdict(
lambda: ImmutableSet.builder(order_key=order_key)
)
self._dict: MutableMapping[KT2, List[VT2]] = defaultdict(list)
self._source = source
self._order_key = order_key
self._dirty = False

def put(self: SelfType, key: KT2, value: VT2) -> SelfType:
Expand All @@ -344,7 +343,7 @@ def put(self: SelfType, key: KT2, value: VT2) -> SelfType:
for v in tmp_source[k]:
self.put(k, v)

self._dict[key].add(value)
self._dict[key].append(value)
self._dirty = True
return self

Expand All @@ -367,7 +366,10 @@ def build(self) -> "ImmutableSetMultiDict[KT2, VT2]":
result: ImmutableSetMultiDict[
KT2, VT2
] = _ImmutableDictBackedImmutableSetMultiDict(
{k: v.build() for (k, v) in self._dict.items()} # type: ignore
{
k: immutableset(v, order_key=self._order_key)
for (k, v) in self._dict.items()
} # type: ignore
)
# item type doesn't matter on empty collections
return (
Expand Down
Loading