[Python-Dev] == on object tests identity in 3.x
Stephen J. Turnbull
stephen at xemacs.org
Tue Jul 8 09:01:00 CEST 2014
Rob Cliffe writes:
> > Why? What value (pun intended) is there in adding an explicit statement
> > of value to every single class?
> It troubles me a bit that "value" seems to be a fuzzy concept - it has
> an obvious meaning for some types (int, float, list etc.) but for
> callable objects you tell me that their value is the object itself,
Value is *abstract* and implicit, but not fuzzy: it's what you compare
when you test for equality. It's abstract in the sense that "inside
of Python" an object's value has to be an object (everything is an
object). Now, the question is "do we need a canonical representation
of objects' values?" Ie, do we need a mapping from from every object
conceivable within Python to a specific object that is its value?
Since Python generally allows, even prefers, duck-typing, the answer
presumably is "no". (Maybe you can think of Python programs you'd
like to write where the answer is "yes", but I don't have any
examples.) And in fact there is no such mapping in Python.
So the answer I propose is that an object's value needs a
representation in Python, but that representation doesn't need to be
unique. Any object is a representation of its own value, and if you
need two different objects to be equal to each other, you must define
their __eq__ methods to produce that result.
This (the fact that any object represents its value, and so can be
used as "the" standard of comparison for that value) is why it's so
important that equality be reflexive, symmetric, and transitive, and
why we really want to be careful about creating objects like NaN whose
definition is "my value isn't a value", and therefore "a = float('NaN');
a == a" evaluates to False.
I agree with Steven d'A that this rule is not part of the language
definition and shouldn't be, but it's the rule of thumb I find hardest
to imagine *ever* wanting to break in my own code (although I sort of
understand why the IEEE 754 committee found they had to).
> How can we say if an object is mutable if we don't know what its
> value is?
Mutability is a different question. You can define a class whose
instances have mutable attributes but are nonetheless all compare
equal regardless of the contents of those attributes.
OTOH, the test for mutability to try to mutate it. If that doesn't
raise, it's mutable.
More information about the Python-Dev