Search code examples
pythonfunctioncallable-object

Create a callable object with arguments already supplied in Python


Essentially I am trying to pass arguments to a function but defer the execution that function until later. I don't want to delay by some amount of time or I would just sleep. Here's the usage I'm going for

import requests

def test_for_active_server(server_address):
    response = requests.get(server_address)

try_n_times(func, expected_error, n_iterations):
    for i in range(n_iterations):
        try:
            func()
            break
        except expected_error:
            continue
    else:
        return False
    return True

try_n_times(
    create_callable(test_for_active_server("http://localhost/"),  
    requests.ConnectionError, 10)

The problem here of course is that when I call test_for_active_server("http://localhost/") it will just run right away so the argument to create_callable will just be None. I believe I could do this with something like

def create_callable(func, func_args: List[str], func_kwargs: Dict[str, str], *args):
    def func_runner():
        func(*args, *func_args, **func_kwargs)
    return func_runner

and then use it as

create_callable(test_for_active_server, "http://localhost")

But this is rather awkward. Is there a better way to do this?


Solution

  • You're looking for functools.partial.

    You can supply all the arguments, so you can do something like:

    obj = functools.partial(test_for_active_server, server_address="http://localhost/")
    # ...do other things...
    obj()