1

What is the best practice to run functions in sequence?

I have 4 functions, if the previous one failed, do not run the following ones. In each function, I set global error and error = 1 when exception occurs. Then in main, I just use if statement to check the value of error. I think there should be a better way to do it.

def main():
    engine = conn_engine()
    if error == 0:
        process_sql()
    if error == 0:
        append_new_rows_to_prod()
    if error == 0:
        send_email_log()
3
  • 5
    The canonical way is to raise an exception within the function. Refrain yourself from using globals as they are difficult to debug when there is an issue. Commented Sep 25, 2020 at 3:23
  • The "other" canonical way is to return a completion status code. This is common on UNIX systems, but named exceptions are my preference from long experience with both methods. Commented Sep 25, 2020 at 3:27
  • 1
    @Prune True. Exit codes lead to defensive programming which makes it harder to read. It has still its uses though, especially in cases when the success or failure of the function can be ignored. Commented Sep 25, 2020 at 3:29

1 Answer 1

2

The canonical way is to raise an exception within the function. For example:

def process_sql():
  # Do stuff
  if stuff_failed:
    raise ProcessSQLException("Error while processing SQL")

def append_new_rows_to_prod():
  # Do other stuff
  if other_stuff_failed:
    raise AppendRowsException("Error while appending rows")

def main():
    engine = conn_engine()
    try:
      process_sql()
      append_new_rows_to_prod()
      send_email_log()
    except ProcessSQLException, AppendRowsException as e:
      # Handle exception, or gracefully exit
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.