I know how to pass a function as argument, and then use the function later. However I could not figure out how to do this with a method. I'd like to provide users with an "API" that allows them to configure custom functions.
As a (not) working example, let's say I want the user to be able to supply some general pandas function:
import pandas as pd
# user-supplied data
right = pd.DataFrame({'right_a':[1,2],
'right_b':[3,4]})
# user-supplied function & arguments
myfun = pd.DataFrame.merge
args = {'right':right,
'right_on':'right_a',
'how':'inner'
}
user_configs = {'func': myfun,
'args':args}
def exec_func(exec_dict):
# some data that only the function knows:
left = pd.DataFrame({'left_a':[1,2],'left_b':['foo','bar']})
# some args that only the function knows
exec_dict['args']['left_on'] = 'left_a'
# apply the function
#result = left.merge(**exec_dict['args']) # desired result
result = left.exec_dict['func'](**exec_dict['args']) # generalized but not working code
return result
exec_func(user_configs)
the above code result in a
AttributeError: 'DataFrame' object has no attribute 'exec_dict'
for obvious reasons. How could i achieve the desired behavior, that allows the user to supply different functions?
myfun = 'merge'and thenresult = getattr(left, exec_dict['func'])(**exec_dict['args']).exec_dict['func']directly and provideleftas the first argument, i.e.exec_dict['func'](left, **exec_dict['args']).pandasand several dictionaries is making things needlessly complicated both for us and you.