Comparisons of incompatible types

John Nagle nagle at animats.com
Tue Dec 7 18:08:23 EST 2010


On 12/6/2010 4:17 PM, Steven D'Aprano wrote:
> On Mon, 06 Dec 2010 08:59:12 -0800, TomF wrote:
>
>> I'm aggravated by this behavior in python:
>>
>> x = "4"
>> print x<  7    # prints False
>
>> I can't imagine why this design decision was made.
>
> You've never needed to deal with an heterogeneous list?
>
> data = ["Fred", "Barney", 2, 1, None]
> data.sort()
>
> Nevertheless, I agree that in hindsight, the ability to sort such lists
> is not as important as the consistency of comparisons.

    If you're thinking hard about this, I recommend viewing Alexander
Stepanov's talk at Stanford last month:

    http://www.stanford.edu/class/ee380/Abstracts/101103.html

He makes the point that, for generic programs to work right, the
basic operations must have certain well-defined semantics.  Then
the same algorithms will work right across a wide variety of
objects.

    This is consistent with Python's "duck typing", but inconsistent
with the current semantics of some operators.

    For example, "+" as concatenation makes "+" non-commutative.
In other words,

	a + b

is not always equal to

	b + a

which is not good.

Important properties to have across all types:

	a + b == b + a

Exactly one of

	a > b
	a = b
	a < b

is true, or an type exception must be raised.

The basic Boolean identities

	(a or b) == (b or a)
	not (a or b) == (not a) and (not b)
	not (not a) == a

should all hold, or an type exception should be raised.
With Python accepting both "True" and "1" as sort of
equivalent, there are cases where those don't hold.

			John Nagle
	



More information about the Python-list mailing list