Comparisons of incompatible types

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Dec 8 05:29:35 EST 2010


On Tue, 07 Dec 2010 15:08:23 -0800, John Nagle wrote:

>     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.

But they already work right across a wide variety of objects, so long as 
you limit yourself to the subset of objects where the basic operations 
have the same semantics.

I think that insisting that all operators must always have the same 
semantics is as impractical and unnecessary as insisting that all 
functions and methods with the same name must always have the same 
semantics. We wouldn't expect 

pencil.draw
six_shooter.draw
game.draw

to all have the same semantics, or

math.sin
priest.sin

despite the inconvenience it makes to duck-typing. Why should we expect 
more from operators than we expect from named functions, when there are 
so many more named functions and so few useful symbols for operators?

To my mind, it is foolish for us to expect x*y to always have the same 
semantics when even mathematicians don't expect that. In pure 
mathematics, x*y != y*x for any of the following:

matrices
quaternions
octonions

and probably many others I don't know about.


>     This is consistent with Python's "duck typing", but inconsistent
> with the current semantics of some operators.
> 
>     For example, "+" as concatenation makes "+" non-commutative.

No, it only makes + non-commutative for those types where + is non-
commutative.


> In other words,
> 
> 	a + b
> 
> is not always equal to
> 
> 	b + a
> 
> which is not good.

I don't see why. It seems to me that it's only a bad thing if you hope to 
reason about the meaning of a+b without knowing what a and b actually are.

Personally, I don't consider that a particularly useful trait.


> 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.

As Mark Wooding has already pointed out, that would make numeric 
programmers mad, as it eliminates NANs, which are far more important to 
them. And me.

It also would make it impossible to use > and < to talk about rankings in 
natural hierarchies, such as (say) pecking orders. Using > to mean "out-
ranks", you might have a pecking order among five hens like this:

A > B > C > D > E

but

D > B

Not all comparisons are equivalence relations, and it would be a crying 
shame to lose the ability to use > and < to discuss (e.g.) non-transitive 
comparisons.



-- 
Steven



More information about the Python-list mailing list