You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This is convenient from a Python perspective because operations like sum are more familiar than binary operators like add. However this is not lazy and requires all dicts to be read in at once.
Although this doesn't address the laziness issue, one option to deal with any binop (including builtins) is to do a try-except as follows:
try:
# current methodreturndict((k, func(v)) fork, viniteritems(result))
exceptTypeError:
# perform reduction assuming `func` is a binary function
...
This isn't perfect. What if the function returned an actual TypeError? Also, if func is a curried function that needs two more inputs, then it won't be reduced as expected.
Regarding the attempt in #127, I don't like relying on inspect.
Two other options include:
Make a new function
Add a keyword argument to choose automatic (and lazy) binop reduction.
A keyword option may also allow variadic calling of a function, such as func(*vals).
For example, merge_with(func, *dicts, **functype), where keyword functype may be unary (default), binary, or variadic.
One solution is to add init as a keyword parameter. If it is given, then use func as a binary operator, otherwise use func as a unary operator.
This would require changing the API to def merge_with(func, *dicts, **init) or def merge_with(func, dicts, init=no_init). Side note: def merge_with(func, *dicts, init=no_init) is possible in Python 3.
The strategy to choose func as binop or unop based on whether init is provided may also work for reduceby, which is being discussed here: pytoolz/cytoolz#1
Clojure's
core.merge-with
takes a binary operatorToolz
merge_with
takes a reduction operationThis is convenient from a Python perspective because operations like
sum
are more familiar than binary operators likeadd
. However this is not lazy and requires all dicts to be read in at once.I tried a solution in #127 but gave up.
The text was updated successfully, but these errors were encountered: