简体   繁体   中英

python - flow control when executing multiple functions inside a function

I've been writing some python app and unfortunately I stumbled upon (I believe...) a Design Pattern/Flow Control problem.

Let's say that I have some big function that includes multiple other function and outcome of the big function is strictly determined by small function success.

So the big function simply contains a series of operations.

If just one small function fails then we should abort the big function, unfortunately the deeper we go... then the small functions make more modifications to some objects, so I think that I just cannot abort the big function, because I have to revert/repair some of those unfinished changes made by small functions - "perform cleanup".

Is there a pythonic way to check/control execution of small functions inside a big function? Because the solution that I have now seems extremely ugly and not very ZENish...

Here is some pseudo code that represents the solution that I have now:

def small_func():
    try:
        # doing something here
        return True # if operation successful
    except Error:
        return False



def big_func():
    # state var helping determine if we need to cleanup if some of the 
    # funtions were unsuccessful
    state = True

    if not  small_func1():
        state = False
    if not  small_func2():
        state = False   
    if not  small_func3():
        state = False   
    if not  small_func4():
        state = False
    if not  small_func4():
        state = False
    etc...


    if not state:
        #perform some cleanup after failed function since we can't
        #finish the big function  - we need to abort and clean unfinished stuff

You could save all states first, use a single try-block in the big function and reset in the except block if something goes wrong. Like this:

def small_func():

    # no try-block

def big_func():

    # Save all states here

    try:

        small_func1()
        small_func2()
        small_func3()
        small_func4()

    except Error:

        # Reset all states here

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