运行此示例func时:
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
-子句来解决:
except Exception as exc1:
exc = exc1
exc.__traceback__ = None
# Error logging here
pass
问题:
exc1
),同时仍然避免使用UnboundLocalError
李>except <Exception> as <var>
语句“吞咽”已定义的局部变量李>
这种情况在8.4. The try statement中描述:
相关问题 更多 >
编程相关推荐