Automatically call all functions matching a certain pattern in python

前端 未结 4 1670
忘掉有多难
忘掉有多难 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 04:02

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

提交回复
热议问题