How to pass an argument to a function pointer parameter?

You can either use a lambda:

repeat(lambda: bar(42))

Or functools.partial:

from functools import partial
repeat(partial(bar, 42))

Or pass the arguments separately:

def repeat(times, f, *args):
    for _ in range(times):
        f(*args)

This final style is quite common in the standard library and major Python tools. *args denotes a variable number of arguments, so you can use this function as

repeat(4, foo, "test")

or

def inquisition(weapon1, weapon2, weapon3):
    print("Our weapons are {}, {} and {}".format(weapon1, weapon2, weapon3))

repeat(10, inquisition, "surprise", "fear", "ruthless efficiency")

Note that I put the number of repetitions up front for convenience. It can’t be the last argument if you want to use the *args construct.

(For completeness, you could add keyword arguments as well with **kwargs.)

Leave a Comment