How to call a function stored as variable with arguments - Python 3

1.3k Views Asked by At
def some_function():
    print("This will always be the same")


def some_other_function(text):
    print(text)


some_variable = "hello"

list_of_elements = [

    "element_one": {
        "name": "static_print",
        "function": some_function
            },

    "element_two": {
        "name": "flexible_print",
        "function": some_other_function
            }
        ]

In the above minimal code example I have several elements in a list, each representing in reality an element (of a game menu I am making with pygame). Each of these elements is a dictionary, with several key:value pairs, one of which is "function". The function then gets selectively called for a chosen element. Sometimes, however, a function stored in this key:value pair needs to be called with arguments, at which point I cannot figure out what to do.

I managed to do this with conditional statements, but this requires checking for each function separately, which circumvents the entire purpose of using this list of dicts as a flexible and generalised way of having multiple (menu) elements, each with its attributes and associated function neatly organised.

Is there an elegant way to do this, and if not what would be your personal approach?

1

There are 1 best solutions below

0
On

After reading many constructive comments, and some tinkering, I found exactly what I needed.

This solution is largely based on Matteo Zanoni's comment, with some modifications to account for the possibility of missing 'args' and 'kwargs', depending on the particular function being called. This is handled by providing appropriate default values to the 'get' method - an empty list for 'args', and an empty dictionary for 'kwargs'.

For a dictionary structured like so:

dictionary = {
    {
        "function": some_function,
        "args": [1, 4],
    },

    {
        "function": some_other_function,
    },
}

We can do this, which should be flexible to whether or not each 'function' has any associated 'args' or 'kwargs' it needs to be called with:

dictionary[element]["function"](
    *dictionary[element].get("args", []), 
    **dictionary[element].get("kwargs", {}),
)