Python Basic Doubt

Chris Angelico rosuav at gmail.com
Sat Aug 10 23:43:04 EDT 2013


On Sun, Aug 11, 2013 at 4:21 AM, Gary Herron
<gary.herron at islandtraining.com> wrote:
> On 08/10/2013 06:00 PM, Chris Angelico wrote:
>> Wrong. If you do equality comparisons, it's entirely possible for
>> something to be passed in that compares equal to the RHS without
>> actually being it, so "is" is precisely what's wanted. (Plus, why go
>> through a potentially expensive comparison check when you can simply
>> check object identity - which could be, for instance, an address
>> check? But performance is a distant second to correctness here.)
>
> You're missing my point.
>
> Our knee-jerk reaction to beginners using "is" should be:
>     Don't do that!  You almost certainly want "==".   Consider "is" an
> advanced topic.
>
> Then you can spend as much time as you want trying to coach them into an
> understanding of the precise details.  But until they have that
> understanding, they are well served by a rule-of-thumb that says:
>     Use "==" not "is" for comparisons.

No, I'm not missing your point; I'm disagreeing with it. I think that
'is' should be taught, that it is every bit as important as '==';
you're walking down the path of "GOTO considered harmful", of decrying
some particular language feature because it can be misused.

>> All it takes is a slightly odd or buggy __eq__ implementation and the
>> == versions will misbehave. To check if an argument is something, you
>> use "is", not ==.
>
> No, sorry, but any use of the word "is" in an English sentence is way too
> ambiguous to specify a correct translation into code.   To check "if a
> calculation of some value is a million", you'd write
>         value == 1000000
> not
>         value is 1000000
> even though there are plenty of other examples where "is" would be correct.

Granted, English is a poor litmus test for code. But in this
particular example, we're talking about immutable types (simple
integers), where value and identity are practically the same. A Python
implementation would be perfectly justified in interning *every*
integer, in which case the 'is' would work perfectly here. The
distinction between the two is important when the objects are mutable
(so they have an identity that's distinct from their current values).

ChrisA



More information about the Python-list mailing list