Tuesday, January 13, 2009

A counterintuitive Python specification

I found this story on python-ml-jp mailing list.


>>> None is None is None
True
>>> (None is None) is None
False
>>> None is (None is None)
False
This is not a bug. Python behaves like this since is is not a binary operator.
It's well known that you can write a code like

if a < b < c:
do something
to do something if a is smaller than b and b is smaller than c.
This is because < is a comparison, which is not a binary operator.
It is taken as

if a < b and b < c:
do something
This behavior is documented here.
If it was a binary operator, it would be taken as

if (a < b) < c:
do something
is and in are categorized in tests. Though it doesn't seem to be clearly documented, a test behaves the same way as a comparison.