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)
            .
            .
            .
6
  • 1
    Why do you need to create the functions inside the loop? Just pass whatever you need as arguments to the functions Commented Jul 4, 2018 at 13:20
  • 1
    No, this is not what you want to do. This sounds like a classic XY problem. 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. Commented Jul 4, 2018 at 13:21
  • you can define function with name in string stackoverflow.com/questions/14078357/… Commented Jul 4, 2018 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: sites.google.com/site/pythonactr/subsymbolic/simple-activation Commented Jul 4, 2018 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. Commented Jul 4, 2018 at 13:37

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It's not an option in my case, unfortunately. I could write a code generator. Then that would be the case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.