在python toolz中合并merge_with

时间:2017-12-04 14:33:32

标签: python currying toolz

我希望能够讨好merge_with

merge_with按预期工作

>>> from cytoolz import curry, merge_with
>>> d1 = {"a" : 1, "b" : 2}
>>> d2 = {"a" : 2, "b" : 3}
>>> merge_with(sum, d1, d2)
{'a': 3, 'b': 5}

在一个简单的函数上,curry按预期工作:

>>> def f(a, b):
...     return a * b
... 
>>> curry(f)(2)(3)
6

但是我无法手动"制作merge_with的咖喱版:

>>> curry(merge_with)(sum)(d1, d2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'dict' object is not callable
>>> curry(merge_with)(sum)(d1)(d2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'dict' object is not callable

预先讨论的版本有效:

>>> from cytoolz.curried import merge_with as cmerge
>>> cmerge(sum)(d1, d2)
{'a': 3, 'b': 5}

我的错误在哪里?

1 个答案:

答案 0 :(得分:2)

这是因为merge_withdicts作为位置参数:

merge_with(func, *dicts, **kwargs)

所以f是唯一的强制性参数,而对于空*args,你会得到一个空字典:

>>> curry(merge_with)(sum)  # same as merge_with(sum)
{}

这样:

curry(f)(2)(3)

相当于

>>> {}(2)(3)
Traceback (most recent call last):
...
TypeError: 'dict' object is not callable

您必须明确并定义帮助

def merge_with_(f):
    def _(*dicts, **kwargs):
        return merge_with(f, *dicts, **kwargs)
    return _

可以根据需要使用:

>>> merge_with_(sum)(d1, d2)
{'a': 3, 'b': 5}

或:

def merge_with_(f, d1, d2, *args, **kwargs):
    return merge_with(f, d1, d2, *args, **kwargs)

这两者都可以

>>> curry(merge_with_)(sum)(d1, d2)
{'a': 3, 'b': 5}

>>> curry(merge_with_)(sum)(d1)(d2)
{'a': 3, 'b': 5}