I love assert
steve+comp.lang.python at pearwood.info
Fri Nov 14 12:33:26 CET 2014
Ethan Furman wrote:
> On 11/12/2014 01:41 PM, Marko Rauhamaa wrote:
>> Or I might indicate the exhaustion of possibilities:
>> if status == OK:
>> elif status == ERROR:
>> assert status == WARNING
> And here's a nice example of what one should NOT do. Imagine that a new
> status, CONFUSED is added, the above code is not modified to handle it,
> and for whatever reason the program is being run optimized -- the assert
> is not there, and CONFUSED is treated the same as WARNING.
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:
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"
We know that even the best programmer writes buggy code, which is why we
invent processes like defensive programming, design by contract, test
driven development, unit testing and so on. Even so, buggy code gets
written and released. When that happens, it is a failure of process. If
your process is so poor that you release code without running it with
asserts enabled, then assert will not save you from bugs. No process is
immune to sufficiently malicious or incompetent use.
Assertions are just a tool, not a panacea.
More information about the Python-list