Automatically call all functions matching a certain pattern in python

大兔子大兔子 提交于 2019-12-30 03:28:27

问题


In python I have many functions likes the ones below. I would like to run all the functions whose name matches setup_* without having to explicitly call them from main. The order in which the functions are run is not important. How can I do this in python?

def setup_1():
    ....

def setup_2():
    ....

def setup_3():
    ...

...

if __name__ == '__main__':
    setup_*()

回答1:


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()

yields

# 1
# 3
# 2



回答2:


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()



回答3:


You can use locals()

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

Of course you'll want to make sure that your function names don't appear elsewhere in locals.

In addition, you could also do something like this because functions are first class objects (note the function names are not strings):

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



回答4:


This does not get function objects directly but must use eval, I am checking 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 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_')]


来源:https://stackoverflow.com/questions/3281300/automatically-call-all-functions-matching-a-certain-pattern-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!