assert statement gives the possibility to display the text which goes along with the AssertionError exception. Most of the times though, what would be more appropriate is to raise a different exception (e.g. ValueError). My proposal is to be able to specify an exception as a replacement for AssertionError as in:
>>> assert callable(fun), ValueError("object is not a callable")
ValueError: object is not a callable
Specifically, this would be useful at the top of a function or method, where argument types or values are usually checked:
def retry(times=3, timeout=0.1, callback=None):
assert times >= 1, ValueError("times must be >= 1")
assert isinstance(timeout, (int, float)), ValueError("invalid timeout")
assert callable(callback), ValueError("callback is not a callable")
...as opposed to:
def retry(times=3, timeout=0.1, callback=None):
if not times >= 1:
raise ValueError("times must be >= 1")
if not isinstance(timeout, (int, float)):
raise ValueError("invalid timeout")
if not callable(callback):
raise ValueError("callback is not a callable")
Other than saving 1 line for each type/value check, this has the advantage that the assertion logic (e.g. "times >= 1") is shown in the traceback message itself, because it's on the same line, enriching the context and giving more information in case of error.
Thoughts?
--