Automatically call all functions matching a specific pattern in python

In python, I have many functions that I like below. I would like to run all the functions whose name matches setup_*without explicitly calling them from main. The order of the functions is not important. How to do this in python?

def setup_1():
    ....

def setup_2():
    ....

def setup_3():
    ...

...

if __name__ == '__main__':
    setup_*()
+3
source share
4 answers
def setup_1():
    print('1')

def setup_2():
    print('2')

def setup_3():
    print('3')

if __name__ == '__main__':    
    for func in (val for key,val in vars().items()
                 if key.startswith('setup_')):
        func()

gives

# 1
# 3
# 2
+8
source

Here is one possible solution:

import types

def setup_1():
    print "setup_1"

def setup_2():
    print "setup_2"

def setup_3():
    print "setup_3"

if __name__ == '__main__':
    for name, member in globals().items():  # NB: not iteritems()
        if isinstance(member, types.FunctionType) and name.startswith("setup_"):
            member()
+2
source

locals()

L = locals()
for k in L:
    if hasattr(L[k], '__call__') and k.startswith('setup'):
        L[k]()

, , .

, - , ( , ):

setupfunctions = [setup_1, setup_2, setup_3, myotherfunciton]
for f in setupfunctions:
    f()
0
source

This does not give the objects functions directly, but you need to use eval, I check the solution with vars () to get rid of eval:

     def setup_1():
        print('setup_1')

    def setup_2():
        print('setup_2')

    def setup_3():
        print('setup_3')

    if __name__ == '__main__':
        [eval(func+'()') for func in dir() if func.startswith('setup_')]

Ok, here is the version with vars ():

def setup_1():
    print('setup_1')

def setup_2():
    print('setup_2')

def setup_3():
    print('setup_3')    

if __name__ == '__main__':
    [vars()[func]() for func in dir() if func.startswith('setup_')]
0
source

Source: https://habr.com/ru/post/1755311/


All Articles