Python Assert Fails Silently?

Problem: Python assert statements are prone to silently fail in obvious misuse.

Solution: Modify Python assert statement to “assert condition as message”

Python usually does the right thing ™. That is, usually a programmer’s code does what is expected without odd language gotcha’s. Here is one of the gotcha’s:

  1. def do_with_file(filename):
  2.     assert(len(filename)>0 and filename[0] <> ‘ ‘, ‘filename (%s) not valid’ % filename)
  3.     …

Seems reasonable? Sorry, that assert is equivalent to:

  1. assert True

because your parenthesis made a tuple. You meant to type this:

  1. assert len(filename)>0 and filename[0] <> ‘ ‘, ‘filename (%s) not valid’ % filename

Python 3.0 should be modified to require this:

  1. assert len(filename)>0 and filename[0] <> ‘ ‘ as ‘filename (%s) not valid’ % filename

or just make assert a built_in function and, therefore, require the parenthesis.

del.icio.us Reddit Slashdot Digg Facebook Technorati Google StumbleUpon Tailrank Yahoo Bloglines Newsvine Spurl Fark

6 comments ↓

#1 dude on 04.24.08 at 1:52 pm

How about:

from testing import assert # or similar
assert(…)

Why would it not be a function!? More python inconsistency, it’s frustrating to no end.

#2 charles on 04.24.08 at 2:02 pm

The plus for being a function:
+ more consistency
+ over-ride assertion failure to log it correctly.
+ easier to decide not to throw exception during debugging.
- might have security concerns.

So, I agree with you.

#3 charles on 04.24.08 at 2:05 pm

Oh, FYI, Guido opines that making it a function prevents it from being disabled in -O mode.

#4 Andy on 05.26.08 at 5:14 pm

Considering the change to ‘print’, it definitely seems like ‘assert’ should also be a function.

To handle the problem where they wouldn’t be disabled with -O, maybe they could hack the parser so that ‘assert’ functions are treated specially from normal functions. There are a few constructs in Python that seem normal, but are totally special-cased under the hood (such as ‘from __future__’ imports)

#5 Jay Lee on 06.20.08 at 5:02 pm

In regards to my image being used for this article, please read and consider the Creative Commons License that outlines acceptible use. You can view it here:

http://creativecommons.org/licenses/by-nd/2.0/deed.en

Thanks for your consideration

#6 charles on 06.20.08 at 10:02 pm

Hello Jay,

The image is indeed a hyperlink to your original on the flicker account. This was, last I saw, the attribution required by Flickr and also satisfies the terms of a non-derivative CC license. My guess from the language is that this post was from a slightly off spider.

Have fun,

Charles

Leave a Comment