Verifying assertion failures

Andrew Dalke dalke at acm.org
Sat May 19 15:16:42 EDT 2001


Gustavo Niemeyer wrote in message ...
>I was just wondering, is there anyway of knowing what assertion
>has failed?
>
>I mean, it'd be nice to have something like:
>
>>>> try:
>...   assert 0 == 1
>... except AssertionError, e:
>...   print e
>...
>0 == 1

No there isn't, unless you specify it.  Why would it
be nice (give an example from real code)?

Suppose it is implemented.  What is the content of that
exception when done in the context of

  a = 0
  b = 1
  assert a == b == (a == math.sqrt(a))
?

I can think of two possibilities

The first is to use the string
 "a == b == (a == math.sqrt(a))"

that is, to use the exact text representation of the
exception.  Since assertions should not occur in working
code, this would be used for debugging.  Since you have
the source code when debugging, this information comes
up in the stack trace, or you can use the same methods
to write a function to get that code.

The second is to somehow insert actual values for the
different part of the assertion, as in using the text
  0 == 1 == (0 == math.sqrt(0))

But that isn't possible because:
  - math.sqrt could be turned into <built-in function sqrt>
  - perhaps you want to see the results of math.sqrt
     0 == 1 == (0 == 0.0)
  - suppose 'a' was really an instance which overrides __cmp__
    in which case you may want to see the results of the ___cmp__
     0 == 1 == 1
  - to be done correctly, the expression cannot be reevaluated
     to get the text.  For example,
         assert f(1) != 1
     should not require calling f twice.  A good implementation
     only needs to do it once (by saving the intermediate results
     of the expression) so there is no expectation for a double
     call.
The only general solution I know of is to show the whole
expression tree as output and the values for each node.  This
is complicated code to implement and hard to understand.

On the other hand, with the current assert format I can do

  assert a == b == (a == math.sqrt(a)), \
     "%s == %s == (%s == math.sqrt(%s))" % (a, b, a, a)

or
  assert a == b == (a == math.sqrt(a)), \
     "%s == %s == %s" % (a, b, a == math.sqrt(a))


and get exactly the output I want and know exactly how each
term will be used and when.

                    Andrew
                    dalke at acm.org






More information about the Python-list mailing list