Assertions

Steve D'Aprano steve+python at pearwood.info
Fri Sep 22 08:43:36 EDT 2017


On Fri, 22 Sep 2017 10:03 pm, alister wrote:

> On Fri, 22 Sep 2017 21:15:54 +1000, Steve D'Aprano wrote:
> 
>> On Fri, 22 Sep 2017 08:50 pm, alister wrote:
>> 
>>>> The bottom line is, if I saw
>>>> 
>>>> if not (thing > 0): raise AssertionError(...)
>>>> 
>>>> in a code review, I'd probably insist that either it be changed to use
>>>> `assert`,
>>>> or the exception be changed to ValueError, whichever better expresses
>>>> the intention of the code.
>>> 
>>> In a code review I would want the condition changed to be less noisy/
>>> confusing to the reader.
>>> 
>>> if thing <=0: whatever
>> 
>> Fair point, assuming they are the same.
>> 
>> Actually, even for floats they're not the same.
>> 
>> py> not (NAN > 0)
>> True py> NAN <= 0 False
> 
> I bet those are conditions the original author did not expect

Yes, everyone forgets about NAN ("Not A Number").
 
> actually I am not sure how you got them on my system

Oops, sorry, NAN is defined in my startup.py file, together with INF.

NAN = float('nan')
INF = float('inf')

Apologies.


> I would also say that if your examples did indeed return different
> results then pythons logic model has a bug.

No, Python does the right thing here.

Not all classes of values have a total ordering. With numbers, we can safely say
that if x > y, and y > z, then x > z too. But that doesn't necessarily hold for
everything.

E.g. if x, y and z are sports teams, and we identify ">" with "beats", then x
can beat y, and y beat z, but x lose to z. This isn't *numeric* order, but it
is a valid form of order.

In the case of floating point NANs, they are unordered with respect to all
numbers. So for any number x, we always have:

NAN == x
NAN < x
NAN > x
NAN <= x
NAN >= x

all return False, and 

NAN != x

return True.




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list