How to pass an argument to a function pointer parameter? How to pass an argument to a function pointer parameter? python python

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 partialrepeat(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.)


You will need to pass the parameters for foo, to the repeat function:

#! /usr/bin/python3.2def repeat (function, params, times):    for calls in range (times):        function (*params)def foo (a, b):    print ('{} are {}'.format (a, b) )repeat (foo, ['roses', 'red'], 4)repeat (foo, ['violets', 'blue'], 4)


While many of the answers here are good, this one might be helpful because it doesn't introduce any unnecessary repetition and the reason for callbacks in the first place is often to synchronize with other work outside of the main UI thread.

Enjoy!

import time, threadingdef callMethodWithParamsAfterDelay(method=None, params=[], seconds=0.0):    return threading.Timer(seconds, method, params).start()def cancelDelayedCall(timer):    timer.cancel()# Exampledef foo (a, b):    print ('{} are {}'.format (a, b) )callMethodWithParametersAfterDelay(foo, ['roses', 'red'], 0)