0

I want to call a function dynamically, but I didn't success.

available.append({
     'analysis_name': 'Category X Total Payment',
     'col_name': 'VALUE',
     'required_cols': ['Category','VALUE'],
     'agg':'SUM',
     'analysis_type': 'pareto-bar',
     'func': 'draw_pareto'})
available.append({
    'analysis_name': 'Category X Count',
    'col_name': 'Count',
    'required_cols': ['Category','VALUE'],
    'agg':'Count',
    'analysis_type': 'pareto-bar',
    'func': 'draw_pareto'})

I have an array which is mapping function names, and I want to call the function by user option like this:

def runAnalysis(self, analysis):
    required_cols = analysis['required_cols']
    agg = analysis['agg']
    col_name = analysis['col_name']
    analysis['data'] = self.draw_pareto(required_cols[0], required_cols[1], agg, col_name) // this line must be dynamically
    return analysis['data']

3 Answers 3

1

Change your data to contain the function:

available.append({
    'analysis_name': 'Category X Count',
    'col_name': 'Count',
    'required_cols': ['Category','VALUE'],
    'agg':'Count',
    'analysis_type': 'pareto-bar',
    'func': self.draw_pareto})

Then call it:

analysis['data'] = analysis['func'](required_cols[0], required_cols[1], agg, col_name) // this line must be dynamically
Sign up to request clarification or add additional context in comments.

Comments

1

In python everything (classes, functions etc) is an object, if you want a dict to map from keys to functions use function objects.

def test():
    map = { 'a': func1, 'b': func2 }
    map['a']()

def func1(): pass
def func2(): pass

Comments

1

If you can not change the dictionary to contain the function itself, instead of it's name, as suggested in other answers, when you can use getattr to get the function corresponding to the name:

func = getattr(self, analysis['func'])
analysis['data'] = func(required_cols[0], required_cols[1], agg, col_name)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.