[Python-ideas] Inline 'raises' expression
Mathias Panzenböck
grosser.meister.morti at gmx.net
Mon Aug 25 14:43:41 CEST 2008
Fredrik Johansson schrieb:
> Hi,
>
> It happens that I'm just interested in whether an expression raises an
> exception, not the return value. This might look something like
>
> try:
> check_status()
> except IOError:
> cleanup()
>
> which could be written more simply as
>
> if check_status() raises IOError:
> cleanup()
>
> Also, instead of the inconvenient
>
> self.assertRaises(ZeroDivisionError, lambda: 1/0)
>
> one could just write
>
> assert 1/0 raises ZeroDivisionError
>
> Something like this would especially be useful for those of us who
> aren't fans of the unittest framework. Alternatively, just the
> assert--raises form could be permitted.
>
> Thoughts?
>
> Fredrik
I think an extra syntax for such an easy task is unnecessary.
The following function emulates this functionality sufficiently:
def raises(f,e):
try:
f()
except e:
return True
except:
return False
else:
return False
def f(x):
if x != 2:
raise ValueError()
>>> raises(lambda:f(1),ValueError)
True
>>> raises(lambda:f(2),ValueError)
False
>>> raises(lambda:f(1),Exception)
True
>>> raises(lambda:f(2),Exception)
False
>>> raises(lambda:f(1),TypeError)
False
>>> raises(lambda:f(2),TypeError)
False
More information about the Python-ideas
mailing list