28
def lite(a,b,c):
    #...

def big(func): # func = callable()
    #...


#main
big(lite(1,2,3))

how to do this?
in what way to pass function with parameters to another function?

Mike
  • 1,008
  • 3
  • 12
  • 15

4 Answers4

44

Why not do:

big(lite, (1, 2, 3))

?

Then you can do:

def big(func, args):
    func(*args)
Skilldrick
  • 69,215
  • 34
  • 177
  • 229
  • 5
    you can even do `big(lite, 1, 2, 3)` and `def big(func, *args): func(*args)` – Anurag Uniyal Feb 27 '10 at 14:35
  • 1
    That's nice if you can (and want to) change `big`, and `lite` has a fixed signature. But oftentimes one or both are external. In that case Teddy's method (`partial`) is much more general. – Mark Feb 06 '16 at 17:58
13
import functools

#main
big(functools.partial(lite, 1,2,3))
Teddy
  • 6,013
  • 3
  • 26
  • 38
5

Similar problem is usually solved in two ways:

  1. With lambda… but then the passed function will expect one argument, so big() needs to be changed
  2. With named functions calling the original functions with arguments. Please note, that such function can be declared inside other function and the arguments can be variables.

See the example:

#!/usr/bin/python

def lite(a,b,c):
    return "%r,%r,%r" % (a,b,c)

def big(func): # func = callable()
    print func()

def big2(func): # func = callable with one argument
    print func("anything")


def main():
    param1 = 1
    param2 = 2
    param3 = 3

    big2(lambda x: lite(param1, param2, param3))

    def lite_with_params():
        return lite(param1,param2,param3)

    big(lite_with_params)

main()
Jacek Konieczny
  • 8,283
  • 2
  • 23
  • 35
0

Not this way, you're passing to big the return value of lite() function.

You should do something like:

def lite(a, b, c):
    return a + b + c

def big(func, arg):
    print func(arg[0], arg[1], arg[2])



big(lite, (1, 2, 3))
Enrico Carlesso
  • 6,818
  • 4
  • 34
  • 42