akai akai - 7 months ago 25
Python Question

How to define multiple functions changing internal values?

I think my question should be more clearly understood by this short code:

fs = []
for k in range(0, 10):
def f(x):
return x + 2*k
# expecting 1 but 19(=1+2*9)

How do I instead make
return what I want? Please note that
cannot receive
as an argument.

(What I'm actually trying to do is prepare multiple constraint functions that are fed to scipy.optimize.minimize)


The typical way to fix this is to do something like:

def f(x, k=k):
    return x + 2*k

For the most part, this shouldn't affect your "f cannot receive k as an argument" condition because it isn't a required argument.

A related, but different approach would be to define f out of the loop.

def f(k, x):
    return x + 2*k

Then in the loop use functools.partial.

import functools
fs = []
for k in range(10):
    fs.append(functools.partial(f, k))

In this approach, your function won't accept a value for k even if you try to pass one.