Planning a Python Course for Beginners

Steve D'Aprano steve+python at pearwood.info
Wed Aug 9 11:32:31 EDT 2017


On Wed, 9 Aug 2017 11:46 pm, Marko Rauhamaa wrote:

> Typically, an object's equality is simply the "is" relation.

"Typically"? I don't think so. Are you sure you've programmed in Python before?
*wink*

py> [1, 2] is [1, 2]
False

The most commonly used objects don't define equality as identity, e.g. strings,
lists, tuples, ints, bytes, dicts etc don't. It would mean that two objects
with the same value would nevertheless compare as unequal.

In general, caring about `is` (identity) is a failure of abstraction. Why should
we care about object identity? Take the value 42 -- why should anyone care
whether that is represented in computer memory by a single object or by a
billion separate objects?

You might care about memory constraints, but that's a leaky abstraction.
Ideally, where memory is not a constraint, if you care about identity, you are
probably doing it wrong.

I'll allow, in principle, that caring about the identity of stateless, valueless
objects that are defined only by their identity such as None and NotImplemented
may be acceptable. But the Singleton design pattern, as beloved by Java
programmers, puts the emphasis on the wrong place: identity, instead of state.
Why not have one or a million objects, so long as they have the same state?
Hence the Borg design pattern.

There are, in my opinion, very few legitimate uses for `is` and identity
checking, and nearly all of them are either:

- testing for None; or
- debugging implementation details.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list