Skip to content

Commit 0aeae16

Browse files
committed
optimization, and error test case
1 parent 3f32e99 commit 0aeae16

2 files changed

Lines changed: 36 additions & 2 deletions

File tree

effect/fold.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,5 +49,17 @@ def folder(acc, element):
4949

5050

5151
def sequence(effects):
52-
"""Perform each Effect serially, collecting their results into a list."""
53-
return fold_effect(lambda acc, el: acc + [el], [], effects)
52+
"""
53+
Perform each Effect serially, collecting their results into a list.
54+
55+
:raises: :obj:`FoldError` with the list accumulated so far when an effect
56+
fails.
57+
"""
58+
# Could be: folder = lambda acc, el: acc + [el]
59+
# But, for peformance:
60+
l = []
61+
62+
def folder(acc, el):
63+
l.append(el)
64+
return l
65+
return fold_effect(lambda acc, el: acc + [el], l, effects)

effect/test_fold.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
def _disp(dispatcher):
1414
return ComposedDispatcher([dispatcher, base_dispatcher])
1515

16+
1617
def test_fold_effect():
1718
"""Behaves like foldM."""
1819
effs = [Effect('a'), Effect('b'), Effect('c')]
@@ -78,3 +79,24 @@ def test_sequence():
7879
def test_sequence_empty():
7980
"""Returns an empty list when there are no Effects."""
8081
assert sync_perform(base_dispatcher, sequence([])) == []
82+
83+
84+
def test_sequence_error():
85+
"""
86+
Allows :obj:`FoldError` to be raised when an Effect fails. The list
87+
accumulated so far is the `accumulator` value in the :obj:`FoldError`.
88+
"""
89+
effs = [Effect('a'), Effect(Error(ZeroDivisionError('foo'))), Effect('c')]
90+
91+
dispatcher = SequenceDispatcher([
92+
('a', lambda i: 'Ei'),
93+
])
94+
95+
eff = sequence(effs)
96+
97+
with dispatcher.consume():
98+
with raises(FoldError) as excinfo:
99+
sync_perform(_disp(dispatcher), eff)
100+
assert excinfo.value.accumulator == ['Ei']
101+
assert excinfo.value.wrapped_exception[0] is ZeroDivisionError
102+
assert str(excinfo.value.wrapped_exception[1]) == 'foo'

0 commit comments

Comments
 (0)