Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python alternative assignment when exceptions occur using context manager

In Python, I can assign alternative values to a variable if the first assignment to this variable raise exceptions, something like:

try:
    a = 1/0
except Exception:
    a = 0

I wonder can we replace the try/except with context manager?

Here what I tried:

from contextlib import contextmanager

@contextmanager
def tryo(*exception_list):
    t = tuple(i for i in exception_list[0]
              if isinstance(i,Exception) or (Exception,))
    try:
        yield
    except t as e:
        print e

with tryo([(Exception, 0)]):
    a = 1/0

I guess I must do something instead of yield but don't know what must I do. Any suggestion?

like image 797
cuonglm Avatar asked Dec 03 '25 14:12

cuonglm


1 Answers

The exception (ZeroDivisionError in this case) is not caused by assignment failure, but becasue of dividing by 0.

The first code can be converted as follow:

a = 0
try:
    a = 1 / 0
except Exception:  # ZeroDivisionError:
    pass

How about the following approach (yielding default value, change the value in with statement body)?

>>> from contextlib import contextmanager
>>>
>>> @contextmanager
... def tryo(exceptions, default):
...     try:
...         yield default
...     except exceptions:
...         pass
...
>>> with tryo((Exception), 0) as a:  # ZeroDivisionError:
...     a = 1 / 0
...
>>> with tryo((Exception), 0) as b:  # ZeroDivisionError:
...     b = 4 / 2
...
>>> a
0
>>> b
2.0
like image 56
falsetru Avatar answered Dec 05 '25 04:12

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!