Automatically call all functions matching a certain pattern in python

前端 未结 4 1672
忘掉有多难
忘掉有多难 2021-01-01 03:25

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 fr

4条回答
  •  甜味超标
    2021-01-01 03:55

    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_')]
    

提交回复
热议问题