Passing functions with arguments to another function in Python? Passing functions with arguments to another function in Python? python python

Passing functions with arguments to another function in Python?


Do you mean this?

def perform(fun, *args):    fun(*args)def action1(args):    # somethingdef action2(args):    # somethingperform(action1)perform(action2, p)perform(action3, p, r)


This is what lambda is for:

def perform(f):    f()perform(lambda: action1())perform(lambda: action2(p))perform(lambda: action3(p, r))


You can use the partial function from functools like so.

from functools import partialdef perform(f):    f()perform(Action1)perform(partial(Action2, p))perform(partial(Action3, p, r))

Also works with keywords

perform(partial(Action4, param1=p))