When running this example 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>)
the last line (return ret, exc) raises UnboundLocalError: local variable 'exc' referenced before assignment even tho exc is definitively bound in the first line of the function (exc = None). This can be fixed by changing the except-clause like so:
except Exception as exc1:
exc = exc1
exc.__traceback__ = None
# Error logging here
pass
Questions:
- Is it possible to avoid using another variable (in my example
exc1) while still avoiding theUnboundLocalError? - Why does the
except <Exception> as <var>statement "swallow" already defined local variables?