[Tutor] Beginner's question
Dave Angel
d at davea.name
Thu Nov 22 22:43:12 CET 2012
On 11/22/2012 02:50 PM, eryksun wrote:
> On Thu, Nov 22, 2012 at 10:49 AM, Dave Angel <d at davea.name> wrote:
>>
>>> <snip>
>>>
>>
>> This one first gets into trouble if x is even and y is odd, because if
>> tries to compare y with None, which is basically an undefined ordered
>> comparison (and illegal in Python3, I believe). The flag value needs to
>> be an int, or at least numeric.
>
> Yes, comparing an int to None raises a TypeError in Python 3, but it
> is 'defined' in 2.x, for what it's worth. Since
>
> NoneType lacks tp_richcompare (__lt__, __gt__, etc)
> NoneType lacks tp_compare (__cmp__)
> int/long lack tp_richcompare for a swapped operation
> int/long tp_compare isn't _PyObject_SlotCompare
> None can't be coerced (__coerce__) to an int/long
>
> the comparison falls through to default_3way_compare, where it's hard coded:
>
> /* None is smaller than anything */
> if (v == Py_None)
> return -1;
> if (w == Py_None)
> return 1;
>
> http://hg.python.org/cpython/file/70274d53c1dd/Objects/object.c#l750
>
You're looking at a particular implementation of CPython code, while I'm
looking at Python's docs. In tha language version 2.x, the result is
repeatable, but undefined, deliberately.
++ http://docs.python.org/2/reference/expressions.html
++ Otherwise, objects of different types always compare unequal, and
++ are ordered consistently but arbitrarily.
In other words
2 > None
will give the same answer each time, for a single run of a script in
CPython, but it is unspecified what that answer will be, and may vary by
version as well as implementation.
--
DaveA
More information about the Tutor
mailing list