fixup! Add MapFields transformation

This commit is contained in:
Kryštof Pilnáček
2018-10-29 13:52:20 +01:00
parent 721bdb4318
commit f93f6bb62e
2 changed files with 13 additions and 5 deletions

View File

@ -334,13 +334,19 @@ def MapFields(function, key=True):
def _MapFields(bag):
try:
factory = type(bag)._make
except AttributeError as e:
raise UnrecoverableAttributeError('This transformation works only on objects with named'
' fields (namedtuple, BagType, ...).') from e
except AttributeError:
factory = type(bag)
if callable(key):
try:
fields = bag._fields
except AttributeError as e:
raise UnrecoverableAttributeError(
'This transformation works only on objects with named'
' fields (namedtuple, BagType, ...).') from e
return factory(
function(value) if key(key_) else value for key_, value in zip(bag._fields, bag)
function(value) if key(key_) else value for key_, value in zip(fields, bag)
)
elif key:
return factory(function(value) for value in bag)

View File

@ -123,6 +123,8 @@ MyBag = BagType("MyBag", ["a", "b", "c"])
(MyBag(1, 2, 3), True, MyBag(1, 4, 9)),
(MyBag(1, 2, 3), False, MyBag(1, 2, 3)),
(MyBag(1, 2, 3), lambda x: x == 'c', MyBag(1, 2, 9)),
((1, 2, 3), True, (1, 4, 9)),
((1, 2, 3), False, (1, 2, 3)),
])
def test_map_fields(input_, key, expected):
with BufferingNodeExecutionContext(bonobo.MapFields(lambda x: x**2, key)) as context:
@ -133,7 +135,7 @@ def test_map_fields(input_, key, expected):
def test_map_fields_error():
with BufferingNodeExecutionContext(bonobo.MapFields(lambda x: x**2)) as context:
with BufferingNodeExecutionContext(bonobo.MapFields(lambda x: x**2, lambda x: x == 'c')) as context:
context.write_sync(tuple())
assert context.status == '!'
assert context.defunct