On 10/17/2013 7:35 PM, Nick Coghlan wrote:
On 18 Oct 2013 06:59, "Xavier Morel" <[email protected]
<mailto:[email protected]>> wrote:
>
> On 2013-10-17, at 22:11 , Ethan Furman wrote:
>
> > On 10/17/2013 01:03 PM, Terry Reedy wrote:
> >>
> >> class suppress:
> >> def __init__(self, *exceptions):
> >> self.exceptions = exceptions
> >> def __exit__(self, etype, eval, etrace):
> >> return etype in self.exceptions
> >
> > This fails when etype is a subclass of the exceptions, as mentioned
in the original issue.
There are two other failures; see below. I know better than to post code
without testing or saying 'untested'; I just wish I would always remember...
> That's fixed by using `issubclass` and does not infirm Terry's point
does it?
Yeah, it looks like it's worth switching to the class based
implementation in this case. I guess I'm too accustomed to that being
the more complex alternative, as I hadn't even tried it :)
With two more changes (add __enter__, account for etype is None), the
suppress tests pass.
import unittest
class suppress:
def __init__(self, *exceptions):
self.exceptions = exceptions
def __enter__(self): pass
def __exit__(self, etype, val, tb):
return etype is None or issubclass(etype, self.exceptions)
class Testsuppress(unittest.TestCase):
def test_no_exception(self):
with suppress(ValueError):
self.assertEqual(pow(2, 5), 32)
def test_exact_exception(self):
with suppress(TypeError):
len(5)
def test_multiple_exception_args(self):
with suppress(ZeroDivisionError, TypeError):
len(5)
def test_exception_hierarchy(self):
with suppress(LookupError):
'Hello'[50]
unittest.main()
>>> Ran 4 tests...OK
--
Terry Jan Reedy
_______________________________________________
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe:
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com