unittest: assertRaises() with an instance instead of a type
Peter Otten
__peter__ at web.de
Thu Mar 29 03:48:37 EDT 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:
#untested
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