question of style

Tim Harig usernet at ilthio.net
Fri Jul 3 05:07:30 EDT 2009


On 2009-07-03, Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> wrote:
> On Thu, 02 Jul 2009 22:14:18 +0000, Tim Harig wrote:
>> On 2009-07-02, Paul Rubin <http> wrote:
>>> Tim Harig <usernet at ilthio.net> writes:
>>>> If lower is 5 and higher is 3, then it returns 3 because 3 != None in
>>>> the first if.
>>> Sorry, the presumption was that lower <= higher, i.e. the comparison
>>> had already been made and the invariant was enforced by the class
>>> constructor.  The comment should have been more explicit, I guess.
>> That being the case, it might be a good idea either to handle the
>> situation and raise an exception or add:
>> assert self.lower <= self.higher
> Only if you want strange and mysterious bugs whenever somebody runs your 
> code with the -O flag.

The point here is that Rubin presumed that the condition where lower >
higher should never exist.  Therefore, because the program given segment of
program doesn't test it elswhere, it is possible that a bug in the code
that sets lower > higher could go unoticed while silently passing the wrong
data.

Therefore, It is better to test that assumption in a way that *will* crash
if something is wrong, for instance, if another method accidently changes
one of the values.  That would tend to make errors in another method of the
class (or even higher up in this method), more likely to be found.

> asserts are disabled when the -O flag is given.

Right, like defining NDEBUG in C.  In _Writing Solid Code_ by Steve
Maguire, he likens it to having two pieces of code: one for testing where
any errors should cause crashes as early as possible and one for shipping
where it may be better to handle errors if possible from within the code.

> You should never use asserts for testing data. That's not what they're 
> for. They're for testing program logic (and unit-testing).

What I am suggesting here is exactly that.  If lower is always defined such
that it should always be equal to or lower then higher, then there is an
error in the code somewhere if lower is higher by the time this code is
called.  Either the constructor didn't didn't reject input properly or
another method within the class has inadvertantly changed higher or lower
in an uncorrect way.

In any event, whether I am using it 100% correctly, I want to find any
errors in my code.  If there is an error, I want the program to crash
during testing rather then silently passing bad data.  assert will help
here.

Unfortunatly, Rubin is right.  I did make the mistake that the assert will
fail with higher or lower values of None, which is allowed here.  The same
basic premise is correct but will require more complex assertions to allow
that through.



More information about the Python-list mailing list