2

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.

Romulus Urakagi Ts'ai
  • 3,699
  • 10
  • 42
  • 68
  • Does this answer your question? [How to prevent try catching every possible line in python?](https://stackoverflow.com/questions/10898873/how-to-prevent-try-catching-every-possible-line-in-python) – Mayank Porwal Nov 26 '20 at 06:09

1 Answers1

6

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)
DYZ
  • 55,249
  • 10
  • 64
  • 93