【发布时间】:2021-03-02 21:49:29
【问题描述】:
运行此示例函数时:
from typing import Tuple, Any, Optional
def func() -> Tuple[Any, Optional[Exception]]:
exc = None
ret = None
try:
# code here, if successful assign result to `ret`
ret = "Result"
# comment this line out and the code works
raise Exception
except Exception as exc:
exc.__traceback__ = None
# Error logging here
pass
finally:
return ret, exc
print(func()) # expected: ("Result", <Exception instance>)
最后一行 (return ret, exc) 引发 UnboundLocalError: local variable 'exc' referenced before assignment 即使 exc 明确绑定在函数的第一行 (exc = None)。这可以通过更改except-clause 来解决,如下所示:
except Exception as exc1:
exc = exc1
exc.__traceback__ = None
# Error logging here
pass
问题:
- 是否可以避免使用另一个变量(在我的示例中为
exc1)同时仍然避免使用UnboundLocalError? - 为什么
except <Exception> as <var>语句会“吞下”已定义的局部变量?
【问题讨论】:
标签: python python-3.x exception scope try-catch