'1' + 1 ==> True ???

Erik Max Francis max at alcyone.com
Wed Mar 17 22:22:26 EST 2004


Nicola Mingotti wrote:

> I obtained this result :
> ------
> >>> '1' > 1
> True
> ------
> with python2.2.3 and 2.3.3 .
> (Yes , in python 2.2 i get 1 instead of True)

Yes, with the exception of complex numbers, doing comparisons between
objects of different types is valid.  The ordering is guaranteed to be
consistent on a particular implementation (e.g., here strings are
considered greater than ints). but you're not guaranteed the behavior
will be the same from implementation to implementation (i.e., it's
perfectly valid for another implementation to consider ints less than
strings).

> but
> ------
> >>> '1' + 1
> TypeError
> -------

That's right, adding strings and integers is a type error because it
doesn't make any sense in Python.  Python is strongly typed, so it's
unclear what this operation would mean.  Do you mean int('1') + 1 or '1'
+ str(1)?

> and
> -----------------------------
> >>>'1'.__gt__.__doc__
> 'x.__gt__(y) <==> x>y'
> -----------------------------

I don't understand what bearing this snippet has on the previous two.

> so i'm a little puzzled :)
> 
> Is this a bug or is there a very good reason
> to this strange behaviour ?

In a strongly, dynamically typed language like Python, it's helpful to
have relational operators usually work even between objects of different
types, even if the result is not immediately useful, because you often
don't know the type of an object you have and so can't guarantee that
you'll always be comparing apples with apples.

There are other approaches, such as restricting the standard relational
operators to only work with objects of the same type and raise
TypeErrors otherwise, and introduce a new set of relational operators
which are forgiving with respect to incompatible objects of different
types (this is something I did with a project of mine, where `eq'
requires type compatibility (and raises if it is not satisfied) but
`seq' ("safe equality") simply returns false instead of raising an error
with incompatible types.  However, this is not the approach that Python
has historically used.

Additionally, since types determine the behavior of operations in a
strongly-typed language like Python, not operations, it's useful for
operations that have multiple meanings (+ can mean arithmetic addition
but also string concatenation) -- possible in a strongly-typed language
-- to reject ambiguous arguments rather than trying to guess what it is
you mean.

-- 
 __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
/  \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
\__/ Does the true light / Of love come in flashes
    -- Sandra St. Victor



More information about the Python-list mailing list