Python: defining functions on the fly

I have the following code:

funcs = [] for i in range(10): def func(): print i funcs.append(func) for f in funcs: f() 

The problem is that func overrated. Those. code output:

 9 9 9 ... 

How would you solve this without defining new features?

The best solution would be to change the name of the function. I.e:

 for i in range(10): def func+i(): ... 

(or some other weird syntax)

+4
source share
3 answers

The problem is not that func is overwritten, but that the value of i is evaluated when the function is called, and not when it is defined. If you want to evaluate i during the definition, put it in the function declaration, as the default argument to func .

 funcs = [] for i in range(10): def func(value=i): print value funcs.append(func) for f in funcs: f() 

The default arguments are evaluated once when the function is defined, so the incremental loop does not affect them. This will work just as well if you used

 def func(i=i): print i 

but I used the name value to indicate which name is used in this function.

+13
source

Returning func from another function is the safest .

0
source

You may try

 for i in range(10): def func(j=i): print j funcs.append(func) for f in funcs: f() 
0
source

Source: https://habr.com/ru/post/1300642/


All Articles