mercredi 22 avril 2015

Set (and remove) keyword arguments from function

I have a function like:
def foo(a, b, c): return a+b+c

Now I like to fix b to 2 and create signature:
def bar(a, c): return foo(a, 2, c)

Another option is to use a lambda function:
bar = lambda a, *args: foo(a,2,*args)

But also this is not very nice, because I have to know how many arguments there are before b.

functools.partial solves this problem partially:
bar = partial(foo, b=2)

However, this has a signature bar(a, b=2, c) instead of bar(a, c)

Is there a better solution?

Background: Currently, I try to fit data using scipy.optimize.minimize. Some parameters I want to fix (not changing during fitting).

Aucun commentaire:

Enregistrer un commentaire