Skip to content

Commit

Permalink
extend
Browse files Browse the repository at this point in the history
  • Loading branch information
dycw committed Oct 9, 2024
1 parent 1daf979 commit bbcaed3
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/tests/test_iterables.py
Original file line number Diff line number Diff line change
Expand Up @@ -592,6 +592,18 @@ def test_new_many_iterables(self) -> None:
assert isinstance(collection, Collection)
assert len(collection) == 3

def test_new_post_init(self) -> None:
class SubCollection(Collection[_Item]):
@classmethod
@override
def check_items(cls, items: Iterable[_Item]) -> None:
if any(item.n >= 1 for item in items):
msg = "n >= 1 is not permitted"
raise ValueError(msg)

with raises(ValueError, match="n >= 1 is not permitted"):
_ = SubCollection(map(_Item, range(3)))

def test_or_singleton(self) -> None:
collection = Collection(map(_Item, range(3)))
result = collection | _Item(3)
Expand Down
5 changes: 5 additions & 0 deletions src/utilities/iterables.py
Original file line number Diff line number Diff line change
Expand Up @@ -499,6 +499,7 @@ class Collection(frozenset[_TSupportsHashAndSort]):

def __new__(cls, *item_or_items: MaybeIterable[_TSupportsHashAndSort]) -> Self:
items = list(chain(*map(always_iterable, item_or_items)))
cls.check_items(items)
return super().__new__(cls, items)

def __init__(self, *item_or_items: MaybeIterable[_TSupportsHashAndSort]) -> None:
Expand Down Expand Up @@ -574,6 +575,10 @@ def __sub__(
other = cast(Iterable[_TSupportsHashAndSort], other)
return self.__sub__(type(self)(other))

@classmethod
def check_items(cls, items: Iterable[_TSupportsHashAndSort], /) -> None:
_ = items

def filter(self, func: Callable[[_TSupportsHashAndSort], bool], /) -> Self:
return type(self)(filter(func, self))

Expand Down

0 comments on commit bbcaed3

Please sign in to comment.