Counterintuitive Python behavior

Greg Weeks weeks at vitus.scs.agilent.com
Wed Apr 17 12:15:58 EDT 2002


dominikush at yahoo.com wrote:
: >>> dict = {'a':[1],'b':[2]}
: >>> list = dict.values()
: >>> dict['a'].append(3)
: >>> list
: [[1, 3], [2]]

: Who is wrong here: my intuition or Python (2.2)?

As others have said, Python is right on this.  However, Python aids you in
your confusion, as follows:

There should have been an operator in Python that says when objects are
conceptually the same.  For the moment, call it "eq".  The following would
hold:

    3 eq 3
    not (3 eq 4)
    a eq a		# PROVIDED a HAS A VALUE
    "foo" eq "foo"
    not ([] eq [])
    not ({} eq {})
    () eq ()

Furthermore, the behavior of "eq" for class instances should be user
controllable.  Typically, immutable objects would be "eq" when their parts
are "eq", while mutable objects would be "eq" only when one "is" the other.

Furthermore, two "eq" objects should hash to the same value.  So *any*
object could be a hash key.

Python almost has an "eq" operator.  "==" is like "eq" with two exceptions:

    lists
    dictionaries

Since "==" is so close to "eq", it is natural to think of "==" as meaning
conceptual sameness.  And if "==" meant conceptual sameness, then lists
would be immutable, similar to Lisp lists (in the absence of rplaca and
rplacd).  In that case, .append(3) would have been implemented by consing,
and your intuition would have been right.

I'm not saying that your mind did work this way.  But it might have.


Greg


PS: Interestingly enough, all the expressions involving "eq" above are true
on my system with "eq" replaced by "is".  But (I believe) the following are
implementation-dependent:

    3 eq 3
    "foo" eq "foo"
    () eq ()

And "eq" disagrees with "is" for (properly defined) immutable class
instances.  And, although I didn't mention it above, 3 eq 3.0 should
probably hold.  (Which, I should add, means that Guido was *conceptually*
on target with the "/" redefinition.)



More information about the Python-list mailing list