简体   繁体   中英

How does python function return statement work?

I am new to python but I have experience with other languages like nodejs, java etc. I have a function in python defined like:

from flask import abort
def delete_contact(contact_id, api_key=None):  # noqa: E501

    print('delete contact ', contact_id)
    session = Session()
    try:
        query = session.query(DBContact).filter(DBContact.id == contact_id)
        print('delete count:', query.count())
        if query.count() == 0:
            print('return 404')
            return abort(404, 'Not find record')
        contact = query.one()
        session.delete(contact)
        session.commit()
        return 'success'
    except Exception as error:
        print(error)
    finally:
        session.close()
    print('xxxxx')
    return abort(400, 'failed to delete contact ' + contact_id)

When execution this code I can see the output includes both return 404 and xxxxx . I don't understand why xxxxx get printed if the function returns in return abort(404, 'Not find record') already. In other language like java, javascript , if a function returns a value, the rest code should not execute except finally block. But the print('xxxxx') is outside finally block. Why is it executed?

abort(404, 'Not find record') raises a HTTPException , which is caught by your except block.

Therefore the return part of the return abort(404, 'Not find record') statement is never reached and instead of returning python will execute the except block followed by the finally block and then the statements after the try-except-finally statement.

The function then doesn't return either, because the line

return abort(400, 'failed to delete contact ' + contact_id)

raises another HTTPException , which will be propagated through the call stack.

The return s don't do anything.

If you want to propagate the HTTPException , but not other exceptions, you could do something like:

try:
    ...
except HTTPException:
    raise
except Exception as error:
    print(error)
finally:
    ...
...

This will raise the HTTPException s thrown by abort , but handle all other exceptions in the second except block, continuing the function afterwards.

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