I love assert

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Nov 15 03:58:04 CET 2014


Ethan Furman wrote:

> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
> 
> On 11/14/2014 03:33 AM, Steven D'Aprano wrote:
>> 
>> I agree with Marko in this case. Marko's example of defensive programming
>> is very similar to the one I gave in my essay here:
>> 
>> http://import-that.dreamwidth.org/676.html
>> 
>> You're correct of course that under the circumstances you describe the
>> code will fail. But that is no different from the scenario:
>> 
>> "a new status is added, the code is not modified to handle it, no tests
>> are written to check the code is correct (or if the tests are written,
>> the test suite is not run), and then the code is released at which point
>> it fails"
> 
> I am reminded of a Star Treck episode (Deep Space 9?) in which a Klingon
> is mocking the Federation tech for having three backups, instead of only
> two, to which the Federation tech replies, "When the second one fails, I
> wouldn't want to be without my tertiary backup!"
> 
> My point being:  a safety net that is so easily disabled does not count
> (IMHO) as a backup.

Assertions are not a backup or a safety net. They are development tools,
like functional requirements, unit tests, code review and the use of
version control. Like any tool, you need to use it correctly. Writing
assertions but never actually running them is not correct use of
assertions, just like writing tests but never actually running them is not
correct use of tests.

One wouldn't say that code review by a senior developer before code is
checked into the main branch is pointless because "if the developer doesn't
perform the review, buggy code might be checked in". Well duh.

>> If your process is so poor that you release code without running it with
>> asserts enabled, then assert will not save you from bugs.
> 
> This is one my very few complaints about Python:  running it normally is
> the same as running with DEBUG turned on, so the unusual case is
> remembering to run with asserts turned /off/.

That's curious. Your complaint is that asserts are too easy to disable,
nevertheless it takes a deliberate and conscious act to disable them. By
default, Python runs assertions. And yet that is your complaint, so I
suppose that you would rather asserts *didn't* run by default and you
needed a deliberate act to run in debug mode. That doesn't seem consistent
to me.


>> Assertions are just a tool, not a panacea.
> 
> Right -- and using it is like using a rock when what you need is a
> ball-peen hammer.  ;)

Compared to Eiffel, Python doesn't have a lot of flexibility to assertions.
You either run them all, or you run none of them. But the assertions
themselves can be as narrow or as broad as you like. It's just code, you
can do anything you like in it.


-- 
Steven




More information about the Python-list mailing list