简体   繁体   中英

What is the best way to create a function with a single argument from a function with multiple arguments?

In python, I have a function f(x,y) defined as

def f(x,y):
    return x + y

Now I want to define a function g(x) = f(x,y) for a fixed value of y, determined at run-time. In my specific case, I loop over several values of y, and need to generate this function g(x) for each iteration:

for y in range(0,10):
    def g(x):
        return f(x,y)
    #do something with g(x)...

The above code works, but my question is if there exists a more efficient way to do this? It seems to me that creating a function object at each loop iteration could become inefficient in terms of memory/computation time.

Use functools.partial :

>>> def f(x, y):
    return x * y

>>> from functools import partial
>>> g = partial(f, y=2)
>>> g(3)
6

It's not a real function, but depending on what your do something actually is, it may be sufficient to use a lambda expression:

>>> def f(x, y):
...   return x * y
...
>>> g = lambda x: f(x, 2)
>>> g(3)
6

Performance-wise, it seems to be a tiny bit faster than functools.partial even (using Python 2.7.5):

$ python -mtimeit -s 'def f(x, y): return x * y' -s 'g = lambda x: f(x, 2)' 'g(9)'
1000000 loops, best of 3: 0.364 usec per loop
$ python -mtimeit -s 'def f(x, y): return x * y' -s 'from functools import partial' -s 'g = partial(f, y=2)' 'g(9)'
1000000 loops, best of 3: 0.378 usec per loop

The functools module has exactly what you need :

from functools import partial

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

plus5 = partial(add,5)
print plus5(10) # outputs 15

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM