Assertions

Thomas Jollans tjol at tjol.eu
Fri Sep 22 08:31:30 EDT 2017


On 2017-09-22 14:03, alister via Python-list wrote:
> On Fri, 22 Sep 2017 21:15:54 +1000, Steve D'Aprano wrote:
>> On Fri, 22 Sep 2017 08:50 pm, alister wrote:
>>> [snip]
>>>
>>> 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.
>>
> [snip]
>
> I would also say that if your examples did indeed return different 
> results then pythons logic model has a bug.


No, it doesn't (in Python 3).
NaN is not a number. It is neither larger nor smaller than zero. This
behavior is correct:

Python 3.6.0 |Continuum Analytics, Inc.| (default, Dec 23 2016, 12:22:00)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from math import nan
>>> nan < 0
False
>>> nan > 0
False
>>> nan == 0
False
>>> not (nan > 0)
True


Python 2.7 is a bit more fickle:

Python 2.7.5 (default, Aug  2 2017, 11:05:32)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from numpy import nan
>>> nan < 0
False
>>> nan > 0
False
>>> nan == 0
False
>>> not(nan > 0)
True
>>> cmp(nan, 0)
-1
>>> cmp(0, nan)
1


Of course I see why the behavior of NaN is hard to swallow: in a sense
the logical thing to do would be to raise a ValueError (or TypeError)
when comparing to NaN - seeing as the operation doesn't make much sense
in the first place - but it's better to not have an edge case where
comparing two floats can raise, but only under very unusual circumstances.


Cheers,
Thomas

-- 
Thomas Jollans



More information about the Python-list mailing list