fixup! Add MapFields transformation
This commit is contained in:
@ -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)
|
||||
|
||||
@ -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
|
||||
|
||||
Reference in New Issue
Block a user