简体   繁体   中英

Python - decorators based execution

I am trying to execute all the functions with common decorator without calling all the functions. For example

@run 
@v1
def test1():
  #do something

@run
@v1
@v2
def test2():
 #do something

@run
@v2
def test3():
 #do something

@run
def test4():
 #do something

I want to executes the test functions based on the decorators like @run executes all 4 tests. @v1 executes only first two. How can I do that? Any guidance will be helpful.

You could probably use the decorator to "register" your functions in a list:

_to_run = [] # list of functions to run
def run(func):
    _to_run.append(func) # add the decorated function to the list
    return func

@run
def test1():
    print('test1')
    return 1

@run
def test2():
    print('test2')

def test3():
    print('test3')

if __name__ == '__main__':
    for test in _to_run: # iterate over registered functions
        x = test()
        print('Returned:', x)

On the other hand, you could as well create this list explicitly, without decorators.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM