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:
-
def do_with_file(filename):
-
assert(len(filename)>0 and filename[0] <> ‘ ‘, ‘filename (%s) not valid’ % filename)
-
…
Seems reasonable? Sorry, that assert is equivalent to:
-
assert True
because your parenthesis made a tuple. You meant to type this:
-
assert len(filename)>0 and filename[0] <> ‘ ‘, ‘filename (%s) not valid’ % filename
Python 3.0 should be modified to require this:
-
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.

dude | 24-Apr-08 at 1:52 pm | Permalink
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.
charles | 24-Apr-08 at 2:02 pm | Permalink
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.
charles | 24-Apr-08 at 2:05 pm | Permalink
Oh, FYI, Guido opines that making it a function prevents it from being disabled in -O mode.
Andy | 26-May-08 at 5:14 pm | Permalink
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)
Jay Lee | 20-Jun-08 at 5:02 pm | Permalink
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
charles | 20-Jun-08 at 10:02 pm | Permalink
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