2

I'm newbie in Python, but the second time I encouter this problem. Problem: In some libraries there are functions with arguments. Sometimes there is argument as function, like this:

def somefun(fun):
    x = [1,2,3]
    z = fun(x)
    return z

And I want to pass there some other function like this:

def func(x,y):
    return x*y

which have more than one argument. I want to make one argument static, so somefun except func as argument.

Finally I want to make some kind of cycle where I can change static arg. Something like this:

for i in xrange(1,9):
    somefun(func(i,*))

Please do not offer me to change any functions. They are from library and it's not very comfortable to change them. Thanks a lot!

3 Answers3

1

You can use lambda statement:

somefun(lambda x: func(i, x))
Daria Pydorenko
  • 1,754
  • 2
  • 18
  • 45
1

It sure sounds like you are looking for functools.partial. From the docs:

functools.partial(func, *args, **keywords)

Return a new partial object which when called will behave like func called with the positional arguments args and keyword arguments keywords.

In your example, you could pass partial(func, 10) as the argument to somefun. Or you could create the partial objects and use them in a loop:

for i in xrange(1,9):
    somefun(partial(func, i))
Community
  • 1
  • 1
Blckknght
  • 100,903
  • 11
  • 120
  • 169
0

My solution with decorator

from functools import wraps
import numpy as np

def p_decorate(f):
    @wraps(f)
    def wrapped(*args):
        z = f(*args)
        return z
    return wrapped

@p_decorate
def myfunc(a,b):
    """My new function"""
    z = np.dot(a,b)
    return z    

x = [1,2,3]
y = [4,2,0]
r = myfunc(x,y)
print (r)   

print (myfunc.__name__)
print (myfunc.__doc__)

You can change myfunc as you wish.You can also insert more function layers.Without the use of this decorator factory,you would lose the name of myfunc and the docstring.

MishaVacic
  • 1,812
  • 8
  • 25
  • 29