Strange Python behavior from inappropriate usage of 'is not' comparison?

后端 未结 5 874
南方客
南方客 2021-01-22 15:12

I (incorrectly?) used \'is not\' in a comparison and found this curious behavior:

>>> a = 256
>>> b = int(\'256\')
>>> c = 300
>>         


        
5条回答
  •  既然无缘
    2021-01-22 16:03

    Don't use is [not] to compare integers; use == and != instead. Even though is works in current CPython for small numbers due to an optimization, it's unreliable and semantically wrong. The syntax itself is valid, but the benefits of a warning (which would have to be checked on every use of is and could be problematic with subclasses of int) are presumably not worth the trouble.

    This is covered elsewhere on SO, but I didn't find it just now.

提交回复
热议问题