Skip to content
Advertisement

Python – How to call every function in a list with a single function call

I’m trying to create a dictionary where each value is a list of functions that should get executed when calling the value. Here’s some pseudo-code:

functions = {
    "A": (execute() for execute in [func1(param1), func2(param1)]),
    "B": (execute() for execute in [func1(param2), func2(param2)]),
}

But if I try to call this using functions["A"]() an exception is thrown saying “TypeError: ‘generator’ object is not callable”.

How should I approach this problem?

EDIT: Just to clarify, the functions are not generators nor have any return type. They just execute some actions based on the parameter.

Advertisement

Answer

ACCEPTED ANSWER:

Thanks to all of your suggestions, I came up with a solution. I’m just going to leave the code here:

def move(params):  # params is a list of 5 parameters of different types
    # Execute move

def rotate(params):  # params is a list of 2 parameters of different types
    # Execute rotation


moves: {
    "A": [(move, [param1, param2 etc...]), (rotate, [other_param1, other_param2])
    "B": [(move, [param3, param4 etc...]), (rotate, [other_param3, other_param4])
}


def execute_move(move):
    for func, params in moves[move]:
        func(params)


# Example use
execute_move("A")
execute_move("B")
execute_move("A")

This works really well, so thank you all for your help.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement