Dynamic function call callback possibility?

I have a use case where the list of functions that could be used by is dynamic (I get the list programmatically from an external API).
I can populate the list of functions list easily with the API response JSON, no problem.
The problem is with the actual “callback” functions: I cannot provide them “dynamically”. In my use case, if a function is identified and should be called, then I would need to call a generic API that I created that implements the function logic.

I can call this API with the name of the function and the parameters. So it’s not a local Python function but something on an external server. But the list of these functions should be always dynamic, and be provided by an external API.

I could use something like the following:

def func_call_proxy(**data):
    # function name
    func_name = inspect.currentframe().f_code.co_name
    # params and values
    for key, value in data.items():
        print("{} is {}".format(key,value))

But the actual function name here is of course always the same. Maybe I am not that adept with Python, I thought about using lambda functions, but there does not seem to be a way to realize my use case of dynamic functions. If this is the case, then it would be nice to be able to support it via e.g. providing a proxy function that receivers the name of the function first and arguments.

Thanks!

Ok, lambda functions were working after all. :slight_smile: Here is a little snippet in case someone tries to do something like this:

function_map={
        "get_books_of_series": lambda **data : func_call_proxy('get_books_of_series', **data),
        "get_book_first_published": lambda **data : func_call_proxy('get_book_first_published', **data),
    }

and

def func_call_proxy(function_name, **data):
    if function_name == 'get_books_of_series':
        return get_books_of_series(**data)
    if function_name == 'get_book_first_published':
        return get_book_first_published(**data)
    
def get_books_of_series(book_series_name):
    return ['Book1', 'Book2']

def get_book_first_published(book_title):
    return "2023"

1 Like