The contract¶
Each snippet below is part of a file under examples/linq/ that runs in CI. Two small helpers keep them
short. Tracked counts how many elements a source has handed out:
class Tracked:
"""A one-shot source that counts how many elements it has handed out."""
def __init__(self, items: Iterable[int]) -> None:
self._items = iter(items)
self.pulled = 0
def __iter__(self) -> Iterator[int]:
for item in self._items:
self.pulled += 1
yield item
and raises(SomeError) is a with block that asserts the error is raised.
Building a query reads nothing¶
source = Tracked(range(100))
query = flp.it(source).where(lambda x: x % 2 == 1).select(lambda x: x * 10)
assert source.pulled == 0 # building a query reads nothing
assert query.first() == 10 # enumeration does the work ...
assert source.pulled == 2 # ... and reads only 0 and 1
Callbacks run during enumeration¶
calls: list[int] = []
def double(x: int) -> int:
calls.append(x)
return x * 2
query = flp.it([1, 2, 3]).select(double)
assert calls == [] # nothing has run yet
assert query.take(2).to_list() == [2, 4]
assert calls == [1, 2] # the callback ran for the elements taken, no more
Short-circuiting¶
any stops at the first match, single as soon as it sees a second one:
source = Tracked(range(100))
assert flp.it(source).any(lambda x: x >= 3)
assert source.pulled == 4 # stopped at the first match: 0, 1, 2, 3
source = Tracked(range(100))
with raises(MultipleMatchesError):
flp.it(source).single(lambda x: x >= 3)
assert source.pulled == 5 # stopped at the second match: 3 and 4
Exceptions¶
with raises(EmptySequenceError):
flp.it([]).first()
with raises(NoMatchError):
flp.it([1]).first(lambda x: x > 5)
# They all derive from InvalidOperationError, like InvalidOperationException in .NET.
assert issubclass(EmptySequenceError, InvalidOperationError)
assert issubclass(NoMatchError, InvalidOperationError)
# The *_or_default variants return a default instead of raising.
assert flp.it([]).first_or_default(-1) == -1
Sources keep their enumeration characteristics¶
As in .NET, a re-enumerable source can be enumerated again, and a one-shot source stays one-shot. The .NET
LINQ tests exercise this with RunOnce(); the migrated tests do the same with one-shot generators.
repeatable = flp.it([1, 2, 3])
assert repeatable.to_list() == [1, 2, 3]
assert repeatable.to_list() == [1, 2, 3] # a list can be enumerated again
one_shot = flp.it(x for x in range(3))
assert one_shot.to_list() == [0, 1, 2]
assert one_shot.to_list() == [] # a generator stays one-shot
Results and their order¶
assert flp.it([3, 1, 3, 2, 1]).distinct().to_list() == [3, 1, 2] # first occurrence wins
assert flp.it([1, 2, 3]).zip(["a", "b"]).to_list() == [(1, "a"), (2, "b")] # stops at the shorter
See also ordering and grouping.