# questions about functions inside a function

fdu.xiaojf at gmail.com fdu.xiaojf at gmail.com
Mon Jul 16 15:03:21 CEST 2007

```Hi,
Duncan Booth wrote:
> "fdu.xiaojf at gmail.com" <fdu.xiaojf at gmail.com> wrote:
>
>> What I want is, the value of i should be bounded to the anonymous
>> function. And the output should like this:
>>
>> for f in a:
>>      print f()
>> 0
>> 1
>> 4
>> 9
>>
>> How to achieve this?
>
> Use default arguments when defining your function: default arguments are
> evaluated when the function is defined, bound arguments get the current
> value of the variable at the point when it is referenced during the call.
>
> Also, since you give your function a name anyway ('b') you might as well
> use a named function as being clearer than using lambda:
>
>>>> a = []
>>>> for i in range(4):
> 	def b(i=i):
> 		return i**2
> 	a.append(b)
>
>
>>>> for f in a:
> 	f()
>
>
> 0
> 1
> 4
> 9

Thanks for some quick replies.

I'm trying to minimize a function f(X) (X = [x1, x2, ..., xn]) using
scipy.optimize.fmin_cobyla.  The parameter of the function is a list of
N variables. fmin_cobyla also accept a 'cons' parameter as constraint
function, which is a list of functions.

In order to make sure all variables be larger than 0, I tried to created
constraint function like this:

cons = []
for i in range(N):
c = lambda x: x[i] - 1e-10
cons.append(c)

But when functions in cons are evaluated, the value in all functions are
all the same(N-1, which is the last value of i in the loop).

What I want is, when functions in cons be evaluated, every function
refers to a different variable in X.

Regards

Xiao Jianfeng

```