Skip to content
Advertisement

changing the name of a function in a loop

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?

Advertisement

Answer

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()
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement