0

I am new to python and need to write a loop which declares for every element in a list a function. These functions will then be used after the loop. The last element in the loop needs an extra treatment.

Suppose I have this list

elements = ['element_1' ,'element_2', 'element_3']

I tried:

for i, item in enumerate(elements) : 

    if (i+1) == len(elements):
        def action(focus = 'action_' + str(i)) :
            print ("action_" + str(i) + " : " + item)
            .
            .
            .
    else :
        def action(focus = 'action_' + str(i)) :
            print ("action_" + str(i) + " : " + item)
            .
            .
            .
hhwwww
  • 83
  • 1
  • 2
  • 12
  • 1
    Why do you need to create the functions inside the loop? Just pass whatever you need as arguments to the functions –  Jul 04 '18 at 13:20
  • 1
    No, this is not what you want to do. This sounds like a classic [XY problem](http://xyproblem.info). Can you explain what you are *actually* trying to accomplish? Note that Python supports *closures* that couple data with a function, as well as *lambda* or anonymous functions to solve the kinds of problems you might be having. – Jonathon Reinhart Jul 04 '18 at 13:21
  • you can define function with name in string https://stackoverflow.com/questions/14078357/python-how-can-idynamically-create-a-function-with-a-name-based-on-a-string-re – Ygrick Jul 04 '18 at 13:24
  • I am using python act-r and trying to model a cognitive architecture. I get this array via Rest, which should represent actions by a user. This would be an example: https://sites.google.com/site/pythonactr/subsymbolic/simple-activation – hhwwww Jul 04 '18 at 13:27
  • I know it is a terrible style, but I am bound to python act-r unfortunately and need to dynamically declare the production functions from the list. – hhwwww Jul 04 '18 at 13:37
  • You can also do this with `functools.partial` – c2huc2hu Jul 04 '18 at 14:02

1 Answers1

0

It is considered bad practice to have functions defined as you are suggesting. The best way to do it is to have function defined at the outer level, and call them wherever you need to use them.

John Luscombe
  • 343
  • 2
  • 9
  • It's not an option in my case, unfortunately. I could write a code generator. Then that would be the case. – hhwwww Jul 09 '18 at 11:50