Semantics of ==

Erik Max Francis max at alcyone.com
Wed Mar 17 18:38:53 EST 2004


Axel Boldt wrote:

> I couldn't find that algorithm in the language reference, only in 5.9:
> "Tuples and lists are compared lexicographically using comparison of
> corresponding elements. This means that to compare equal, each element
> must compare equal and the two sequences must be of the same type and
> have the same length."
> 
> That definition doesn't seem to fully specify equality of list values:
> ...

Sure it does; the rule can be used recursively.  As I indicated,
according to its definition, your s and w are clearly equal despite
being infinite and having different internal representations.  == has to
do with value, not identity.

> I hope that the
> actual result received, i.e. s==w, is not implementation dependent?

They're also equal in Jython.  It wouldn't surprise me if you could find
an implementation where they might not compare equal, because this is
such a pathological case.  As I indicated before, I've never seen anyone
use a self-referencing list in any real-world code, ever.

> It now appears to me that there are four levels of equality in Python:
> 
> a is b => pickle.dumps(a)==pickle.dumps(b) => repr(a)==repr(b) => a==b
> 
> and none of the arrows can be reversed in general. I suppose I had
> naively assumed the last three to be equivalent.

__eq__ and __repr__ can be overridden to do whatever the programmer
wants, so why would you think the last three would be equivalent?

repr(a) == repr(b) is certainly not equivalent to a == b.  Consider the
default repr of an arbitrary class, which will only be equal to another
object if a is b -- that is, if they represent the same object.  Beyond
that, it's up to the programmer to make custom types behave how he or
she would like with respect to equality and repr.

> Is there a string
> function analogous to pickle.dumps or repr which only takes values
> into account, not internal structure?

How can you define the value of an arbitrary object without reference to
its internal structure?

-- 
 __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
/  \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
\__/ Liberty is the right to do whatever the law permits.
    -- Charles Louis Montesquieu



More information about the Python-list mailing list