Question about 'None'

Francis Girard francis.girard at free.fr
Thu Jan 27 15:47:13 EST 2005


Le jeudi 27 Janvier 2005 21:29, Steven Bethard a écrit :
> 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...
>

Well, here's python doesn't seem to confirm what you're saying :

>>> a = "10"
>>> b = 10
>>> a > b
True
>>> b > a
False
>>> id(a)
1077467584
>>> id(b)
134536516

It really looks like the addresses are compared when objects are of different 
types if there is no __cmp__ or __lt__ user made specification to compare 
objects of different types.

If this is case then it is dreadfully dangerous. You end up never really 
knowing for sure if you're comparing the references or the values.

What would be the use to compare references anyway in language like Python. I 
think the code should raise a big bad exception for such cases.

Francis Girard



> Steve




More information about the Python-list mailing list