How to proceed with batch execution for python methods

0

I have following code below:

def exemplo01():
    return 'exemplo01'

def exemplo02():
    return 'exemplo02'

def exemplo03():
    return 'exemplo03'

def run():
    #list of <class 'function'>
    fx = []
    fx.append(exemplo01)
    fx.append(exemplo02)
    fx.append(exemplo03)

    for item in fx:
        print(item())
        print('-'*30)

if __name__ == '__main__':
    run()

This code works perfectly. But I want to change the run () implementation.

def run():
    l = []
    for i in range(1, 4):
        l.append('exemplo{:0>2}'.format(i))

    for i in l:
        print(i())
        print('-'*30)

In the first implementation the array is of class function, in the second str, I tried to perform a Cast but I did not succeed.

    
asked by anonymous 15.05.2018 / 15:28

1 answer

3

This is because exemplo01 is a function, while i is a string, although it has the same function name, my county is to use a dictionary to map to key (key, in this case the same function name) to value (function):

...
l = {}
for func in [exemplo01, exemplo02, outrafunc]:
    l[func.__name__] = func
...

Then just call it this way:

l['exemplo01']() # ou neste caso, l[i]()

DEMONSTRATION

Another way to do more of the question is to use eval , BUT:
ATTENTION: If you operate on external inputs or data that you have not controlled I DO NOT RECOMMEND , it is very insecure if you do not know with certainty what you are going to act on:

...
l = []
    for i in range(1, 4):
    l.append('exemplo{:0>2}'.format(i))

for i in l:
    print(eval(i)())
    print('-'*30)

DEMONSTRATION

In this case, you can also use globals() , instead of eval above :

...
for i in l:
    print(globals()[i]())
    print('-'*30)
...

Note that I recommend the first one with a dictionary.

    
15.05.2018 / 15:57