gpt4 book ai didi

python - with 语句的等效 try 语句是什么?

转载 作者:行者123 更新时间:2023-12-01 11:50:37 27 4
gpt4 key购买 nike

看完with statement section Python 的语言文档,我想知道声明这段 Python 代码是否正确:

with EXPRESSION as TARGET:
SUITE

相当于这个:

try:
manager = (EXPRESSION)
value = manager.__enter__()
TARGET = value # only if `as TARGET` is present in the with statement
SUITE
except:
import sys
if not manager.__exit__(*sys.exc_info()):
raise
else:
manager.__exit__(None, None, None)

编辑

Guido van Rossum 本人在 PEP 343 中给出了正确的等效 Python 代码(真正的 CPython 实现是在 C 中) :

mgr = (EXPR)
exit = type(mgr).__exit__ # Not calling it yet
value = type(mgr).__enter__(mgr)
exc = True
try:
try:
VAR = value # Only if "as VAR" is present
BLOCK
except:
# The exceptional case is handled here
exc = False
if not exit(mgr, *sys.exc_info()):
raise
# The exception is swallowed if exit() returns true
finally:
# The normal and non-local-goto cases are handled here
if exc:
exit(mgr, None, None, None)

从 Python 3.6 开始,这发生了一些变化:现在 __enter__ 函数在 __exit__ 函数之前加载(参见 https://bugs.python.org/issue27100 ).

所以我的等效 Python 代码存在三个缺陷:

  1. __enter____exit__ 函数应该在调用__enter__ 函数之前加载。
  2. __enter__ 函数应在try 语句之外调用(参见语言文档中第 4 点的注释)。
  3. else 子句应该改为 finally 子句,以处理非本地 goto 语句(breakcontinue, return) in suite.

但是我不明白为什么 PEP 343 中的等效 Python 代码将 finally 子句放在外部 try 语句中而不是内部 >try 语句?

最佳答案

Nick Coghlan,PEP 343 的另一位作者, 在 Python bug tracker 上回答:

It's a matter of historical timing: PEP 343 was written before try/except/finally was allowed, when try/finally and try/except were still distinct statements.

However, PEP 341 was also accepted and implemented for Python 2.5, allowing for the modern try/except/finally form: https://docs.python.org/dev/whatsnew/2.5.html#pep-341-unified-try-except-finally

所以 with 语句的现代 try 语句等效 Python 代码是这样的:

manager = (EXPRESSION)
enter = type(manager).__enter__
exit = type(manager).__exit__
value = enter(manager)
hit_except = False

try:
TARGET = value # only if `as TARGET` is present in the with statement
SUITE
except:
import sys
hit_except = True
if not exit(manager, *sys.exc_info()):
raise
finally:
if not hit_except:
exit(manager, None, None, None)

关于python - with 语句的等效 try 语句是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59322585/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com