Skip to content

Commit

Permalink
flow.MapGroup accepts the initialization sequence as positional argum…
Browse files Browse the repository at this point in the history
…ents (not as the first argument).
  • Loading branch information
ynikitenko committed Apr 22, 2022
1 parent a0129d2 commit 09edb69
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 28 deletions.
36 changes: 17 additions & 19 deletions lena/flow/group_plots.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,28 +71,26 @@
class MapGroup(object):
"""Apply a sequence to groups."""

def __init__(self, seq, map_scalars=True):
"""*seq* must be a *Sequence*, a *Run* element
or a tuple (which will be converted to a *Sequence*).
def __init__(self, *seq, **map_scalars):
"""Arguments *seq* must form a *Sequence*.
Set *map_scalars* to ``False`` to ignore scalar
values (not groups).
Set a keyword argument *map_scalars* to ``False``
to ignore scalar values (those that are not groups).
"""
# todo: could be made a FillCompute element, depending on *seq*
if lena.core.is_run_el(seq):
self._seq = seq
elif isinstance(seq, tuple):
self._seq = lena.core.Sequence(*seq)
else:
# cast to a Run element
try:
self._seq = lena.core.Run(seq)
except lena.core.LenaTypeError:
raise lena.core.LenaTypeError(
"seq must be a Run element, a tuple or should be "
"able to be converted to a Run element"
)
self._map_scalars = map_scalars
try:
seq = lena.core.Sequence(*seq)
except lena.core.LenaTypeError as err:
raise err

self._seq = seq
# in Python 2 we can't put a kwarg after args
ms = map_scalars.pop("map_scalars", True)
if map_scalars:
raise lena.core.LenaTypeError(
"unknown keyword arguments {}".format(map_scalars)
)
self._map_scalars = bool(ms)

def run(self, flow):
"""Map *seq* to every group from *flow*.
Expand Down
22 changes: 13 additions & 9 deletions tests/flow/test_group_plots.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,17 +51,21 @@ def test_map_group():
list(mg2.run([([1], {"group": []})]))

## test initialization
# Run element works
mgr = MapGroup(lena.core.Run(el), map_scalars=True)
assert list(mgr.run([1])) == [2]
# Several elements work
mg4 = MapGroup(el, el, map_scalars=True)
assert list(mg4.run([1])) == [3]

# Sequence works
mgs = MapGroup(lena.core.Sequence(el), map_scalars=True)
assert list(mgs.run([1])) == [2]
# same without explicit map_scalars
mg4 = MapGroup(el, el)
assert list(mg4.run([1])) == [3]

# tuple works
mgtup = MapGroup((el,), map_scalars=True)
assert list(mgtup.run([1])) == [2]
# map_scalars must be explicit
with pytest.raises(lena.core.LenaTypeError):
MapGroup(el, True)

# wrong keyword arguments raise
with pytest.raises(lena.core.LenaTypeError):
MapGroup(el, wrong_kwarg=True)

# unconvertible element raises
with pytest.raises(lena.core.LenaTypeError):
Expand Down

0 comments on commit 09edb69

Please sign in to comment.