:)
I want to build a very tiny functional pipeline in my code to reduce a bunch of functions on a single dictionary. Every function does 1 thing, but on different keys, here's a simplified example:
I have this dictionary
d = {"me": "gab", "you": "cita"}
and suppose a silly function like this:
def make_caps(dic, on=None):
if on is not None:
to_cap = dic.get(on, None)
if to_cap is not None:
dic[on] = to_cap.upper()
return dic
I would like to have this working:
def reduce_fns_on_dict(fns, dic):
from functools import reduce
return reduce(lambda d, f: f(d), fns, dic)
new_dic = reduce_fns_on_dict(fns=[make_caps(on="me"), make_caps(on="you")],
dic=d)
print(new_dic)
on console
{'me': 'GAB', 'you': 'CITA'}
But when I run the above I get:
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: make_caps() missing 1 required positional argument: 'dic'
make_caps(on="me")
calls the make_caps function. What you want is a new function which behaves like make_caps(some_arg, on='me')
. You can make such a function with functools.partial. The line will look something like fns=[partial(make_caps, on="me")...
.
EDIT: Alternatively, you could curry the function.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다