How to proceed with batch execution for python methods

Asked

Viewed 53 times

0

I have the 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 implementation of the run().

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 was not successful.

1 answer

3


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

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

Then just call it that way:

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

DEMONSTRATION

Another way to do more like the question is to use eval, BUT:
ATTENTION:
if it operates on external inputs or data that you have not controlled DO NOT RECOMMEND, is very insecure if you do not know with certainty about what will act:

...
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 the eval above:

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

Note that I recommend the first, with dictionary.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.