Question about 'None'

Steven Bethard steven.bethard at gmail.com
Thu Jan 27 15:29:35 EST 2005


Francis Girard wrote:
> Le jeudi 27 Janvier 2005 20:16, Steven Bethard a écrit :
> 
>>flamesrock wrote:
>>
>>>The statement (1 > None) is false (or any other value above 0). Why is
>>>this?
>>
>>What code are you executing?  I don't get this behavior at all:
>>
>>py> 100 > None
>>True
>>py> 1 > None
>>True
>>py> 0 > None
>>True
>>py> -1 > None
>>True
>>py> -100 > None
>>True
>>
> 
> 
> Wow ! What is it that are compared ? I think it's the references (i.e. the 
> adresses) that are compared. The "None" reference may map to the physical 0x0 
> adress whereas 100 is internally interpreted as an object for which the 
> reference (i.e. address) exists and therefore greater than 0x0.
> 
> Am I interpreting correctly ?

Actually, I believe None is special-cased to work like this.  From object.c:

static int
default_3way_compare(PyObject *v, PyObject *w)
{
	...
	if (v->ob_type == w->ob_type) {
		...
		Py_uintptr_t vv = (Py_uintptr_t)v;
		Py_uintptr_t ww = (Py_uintptr_t)w;
		return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
	}
	...
	/* None is smaller than anything */
	if (v == Py_None)
		return -1;
	if (w == Py_None)
		return 1;
	...
}

So None being smaller than anything (except itself) is hard-coded into 
Python's compare routine.  My suspicion is that even if/when objects of 
different types are no longer comparable by default (as has been 
suggested for Python 3.0), None will still compare as smaller than 
anything...

Steve



More information about the Python-list mailing list