1

I have several test functions named test0 through test{n} which provide outputs for the script I am testing.

Instead of going through the cumbersome process of adding them all to a list and iterating through the list, I was wondering if there is a way to iterate through them in a similar way to an f'string.

E.g:

def t0()
def t9()
numTest = 10
def trueFunc(tn())

for i in range(numTest):
    trueFunc(t{i}())
dolphson
  • 11
  • 3
  • 1
    Try `eval`. I would use a list, anyway. – azelcer Jan 08 '22 at 18:52
  • If you're using `pytest` it'll just automatically run all the functions whose names start with `test`. https://docs.pytest.org/en/6.2.x/goodpractices.html#test-discovery – Samwise Jan 08 '22 at 18:55
  • 2
    It may seem cumbersome to add them to a list, but if you are naming anything `t1`...`t2`...`tn`, *especially* if later want to iterate over them, these things should have been in a list in the first place. – Mark Jan 08 '22 at 19:09
  • Closely related, maybe a duplicate: [How do I create variable variables?](/q/1373164/4518341) – wjandrea Jan 08 '22 at 21:27

1 Answers1

2

While you could use eval to get the function from a string representing its name, a much better approach is to put the functions into a list, and iterate over the list:

def f0(): return 0
def f1(): return 1

list_of_functions = [f0, f1]

for func in list_of_functions:
    print(func())

This will work with functions without numbers in their names, and even for anonymous lambda functions that don't ever get a name.

Blckknght
  • 100,903
  • 11
  • 120
  • 169