unittest: assertRaises() with an instance instead of a type

Peter Otten __peter__ at web.de
Thu Mar 29 09:48:37 CEST 2012

Ulrich Eckhardt wrote:

> True. Normally. I'd adapting to a legacy system though, similar to
> OSError, and that system simply emits error codes which the easiest way
> to handle is by wrapping them.

If you have

err = some_func()
if err: 
   raise MyException(err) 

the effort to convert it to

exc = lookup_exception(some_func())
if exc:
    raise exc

is small. A fancy way is to use a decorator:

def code_to_exception(table):
    def deco(f):
        def g(*args, **kw):
            err = f(*args, **kw)
            exc = table[err]
            if exc is not None: 
                raise exc
        return g
    return f

class MyError(Exception): pass
class HyperspaceBypassError(MyError): pass

@code_to_exception({42: HyperspaceBypassError, 0: None})
def some_func(...):
    # ...

More information about the Python-list mailing list