Python `with` 语句的“底层代码”是什么?
假设你有:
with with_target_expression() as with_variable:
with_block_contents(with_variable)
我明白这里的基本意图——也就是说,目标 / with_variable
会在 with_block_contents
完成后被“合理地处理掉”。
但是,这里到底调用或暗示了什么样的“原始”或“基本”的 Python 呢?
1 个回答
3
答案是这样的:
with_target = with_target_expression()
with_variable = with_target.__enter__()
exception_raised = False
try:
with_block_contents(with_variable)
except Exception:
exception_raised = True
exception_details = sys.exc_info()
should_suppress = with_target.__exit__(*exception_details)
if(not should_suppress):
raise
finally:
if(not exception_raised):
with_target.__exit__(None, None, None)
不过,最权威的答案可以在关于with
语句的文档中找到(这个文档会不断更新)
上面的代码和链接中的内容几乎是一样的,只是排版方式不同。