Python: How to simplify multiple statements with the same try/except block

Viewed 101

I have a code block like this:

try:
    gitlab.gl_delete_project(gitlab_project_id)
except DevOpsError as e:
    if e.status_code != 404:
            raise e
try:
    redmine.rm_delete_project(redmine_project_id)
except DevOpsError as e:
    if e.status_code != 404:
        raise e
try:
    if harbor_project_id is not None:
        harbor.hb_delete_project(harbor_project_id)
except DevOpsError as e:
    if e.status_code != 404:
        raise e

Each method may raise a DevOpsError, and in some conditions, I just want to ignore the Exception, or re-raise it in other times.

Since the try/except block are all identical, is there a way to simplify the code?

Edit: I'm suggested a similar question, but it does not tell me how to pass arguments to the methods.

1 Answers

Define function and call it as many time as needed:

def try_to_delete(delete_method, object):
    try:
        delete_method(object)
    except DevOpsError as e:
        if e.status_code != 404:
            raise e

try_to_delete(gitlab.gl_delete_project, gitlab_project_id)
try_to_delete(redmine.rm_delete_project, redmine_project_id)
if harbor_project_id is not None:  
    try_to_delete(harbor.hb_delete_project, harbor_project_id)
Related