Home > Back-end >  changing the name of a function in a loop
changing the name of a function in a loop

Time:04-20

I didn't find the answer my problem

I have function with names stage_1(), stage_2() e.t.c (to 8).

Can I run it using loop?

stage = 1 
for i in range(8):
      print((f'stage_{stage}'))
      stage  =1

I know this is wrong. what is the right way?

CodePudding user response:

I have function with names stage_1(), stage_2() e.t.c (to 8).

Actually this is a very bad idea.


Can I run it using loop?

For sure! You can do it using globals:

for i in range(1, 8):
    current_function = globals()[f"stage_{i}"]
    result_of_current_function = current_function()

Or even using eval or exec:

for i in range(1, 8): # Range should start from 1
    eval(f"stage_{i}()") # or exec

Do you remember when I told you "This is a very bad idea"?

A better idea would be to store the functions into a list:

functions_list = [
    stage_1, stage_2, stage_3,
    stage_4, stage_5, stage_6,
    stage_7
]

In the end you could call them in a for loop this way:

for function in functions_list:
    function()

CodePudding user response:

if you want to run function in loop like this, you should use eval()

stage = 1 
for i in range(8):
      print(eval((f'stage_{stage}')))
      stage  =1

but using eval() is wrong habbit, that is very unsecure, explanation

  • Related