[Python-Dev] ',' precedence in documentation

Michele Simionato michele.simionato at gmail.com
Mon Sep 29 16:12:13 CEST 2008


I like Martin's proposals (use a function, remove -O) very much.
Actually I wanted
to propose the same months ago. Here is my take at the assert function, which
I would like to be able to raise even exceptions different from AssertionError:

def assert_(cond, exc, *args):
    """Raise an exception if cond is not satisfied. exc can be a template
    string (then args are the interpolation arguments) or an exception
    class (then args are passed to the constructor). Here are a few
    examples:

    >>> assert_(False, 'ahia!')
    Traceback (most recent call last):
       ...
    AssertionError: ahia!

    >>> assert_(False, ValueError)
    Traceback (most recent call last):
      ...
    ValueError

    >>> a = 1
    >>> assert_(isinstance(a, str), TypeError, '%r is not a string' % a)
    Traceback (most recent call last):
    TypeError: 1 is not a string

    """
    if isinstance(exc, basestring):
        raise AssertionError(exc % args)
    elif inspect.isclass(exc) and issubclass(exc, Exception):
        raise exc(*args)
    else:
        raise TypeError('The second argument of assert_ must be a string '
        'or an exception class, not %r' % exc)

 M. Simionato


More information about the Python-Dev mailing list