Search code examples
pythonnestedtry-exceptidempotent

Python Nested Try/Except/Else for Control Flow


What I'd like to achieve in the most elegant Python way: Try to find an object in the database on a certain filter. Only if there is no result, then try to find the object using another filter. If that returns no result, then the object does not exist, so insert a new instance.

What I'm thinking:

try:
    obj = session.query(model).filter_by(field_a).one()
except NoObjFound:
    try:
        obj = session.query(model).filter_by(field_b).one()
    except NoObjFound:
        insert_into_db(brand_new_obj)
else:
    update_the_obj(obj)

I'm not sure if this block is correct or the best way to handle what I'm trying to accomplish.


Solution

  • I would suggest something like:

    for filter in (field_a, field_b):
        try:
            obj = session.query(model).filter_by(filter).one()
        except NoObjFound:
            pass # or 'continue'
        else:
            update_the_obj(obj)
            break
    else:
        insert_into_db(brand_new_obj)
    

    This will ensure that the correct things happen in the correct order, is more readable than nested try blocks and can easily be extended to add more filters.