Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return a function object with parameter binded?

All,

def a(p):
    return p+1

def b(func, p):
    return func(p)

b(a,10)   # 11

here I do not want the result "11" actually, what I want is a function object with the parameter has been binded, let's name it c.

when I use c() or something alike, it will give me the result 11, possible?

Thanks!

like image 727
user478514 Avatar asked Oct 28 '10 10:10

user478514


3 Answers

The functools module provides the partial function which can give you curried functions:

import functools

def a(p):
    return p+1

def b(func, p):
    return functools.partial(func, p)

c = b(a,10)
print c() # >>  11

It can be used to apply some parameters to functions, and leave the rest to be supplied:

def add(a,b):
    return a+b

add2 = functools.partial(add, 2)
print add2(10)  # >> 12
like image 106
Ned Batchelder Avatar answered Oct 28 '22 02:10

Ned Batchelder


you can also use the functools module


import functools

def add(a,b):
    return a+b

>> add(4,6)

10
>> plus7=functools.partial(add,7)
>>plus7(9)
16

 
like image 31
mossplix Avatar answered Oct 28 '22 04:10

mossplix


The only way to do that, is to wrap it in a lambda:

c = lambda : b(a,10)
c() # 11

Though if you're going to name it anyway, that doesn't really buy you anything compared to

def c():
  b(a,10)
like image 39
sepp2k Avatar answered Oct 28 '22 02:10

sepp2k