Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically call all functions matching a certain pattern in python

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_*()
like image 848
D R Avatar asked Jul 19 '10 13:07

D R


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

yields

# 1
# 3
# 2
like image 72
unutbu Avatar answered Sep 28 '22 09:09

unutbu


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()
like image 22
Philipp Avatar answered Sep 28 '22 07:09

Philipp