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