[英]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:我是python
新手,但我有使用其他语言的经验,比如nodejs, java
等。我在python
有一个函数定义如下:
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
.执行此代码时,我可以看到输出包括return 404
和xxxxx
。 I don't understand why xxxxx
get printed if the function returns in return abort(404, 'Not find record')
already.我不明白如果函数已经返回return abort(404, 'Not find record')
为什么会打印xxxxx
。 In other language like java, javascript
, if a function returns a value, the rest code should not execute except finally
block.在其他语言,如java, javascript
,如果一个函数返回一个值,除了finally
块之外,其余代码不应执行。 But the print('xxxxx')
is outside finally
block.但是print('xxxxx')
在finally
块之外。 Why is it executed?为什么会被执行?
abort(404, 'Not find record')
raises a HTTPException
, which is caught by your except
block. abort(404, 'Not find record')
引发HTTPException
,它被您的except
块捕获。
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.因此,永远不会到达return abort(404, 'Not find record')
语句的return
部分,而不是返回 python 将执行except
块,然后是finally
块,然后是try-except-finally
语句之后的语句。
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.引发另一个HTTPException
,它将通过调用堆栈传播。
The return
s don't do anything. return
不做任何事情。
If you want to propagate the HTTPException
, but not other exceptions, you could do something like:如果您想传播HTTPException
而不是其他异常,您可以执行以下操作:
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.这将引发abort
抛出的HTTPException
,但处理第二个except
块中的所有其他异常,然后继续该函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.