Python Basic Doubt

Gary Herron gary.herron at islandtraining.com
Sat Aug 10 23:21:46 EDT 2013


On 08/10/2013 06:00 PM, Chris Angelico wrote:
> On Sun, Aug 11, 2013 at 1:42 AM, Gary Herron
> <gary.herron at islandtraining.com> wrote:
>> On 08/10/2013 03:09 PM, Chris Angelico wrote:
>>> _notpassed = object()
>>> def frob(appendage, device=_notpassed):
>>>       """Use some appendage to frob some device, or None to frob nothing.
>>>       Omit device to frob whatever is currently held in that appendage"""
>>>       if device is _notpassed:
>>>           device = ...  # whatever you need
>>>       if device is not None:
>>>           # frob the device
>>>
>>> But granted, equality comparisons are a LOT more common than identity
>>> comparisons.
>>>
>>> ChrisA
>>
>> Everything you say is true, and even reasonable for those who know what's
>> up.
>>
>> But for each of your examples, using "==" is equivalent to using "is".  Each
>> of
>>      if something == None
>>      if device == _not passed
>>      if device != None
>> would all work as expected.  In none of those cases is "is" actually needed.
> 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.

>
>> Given that, and the implementation dependent oddities, I still believe that
>> it is *highly* misleading to teach a beginner about "is".
>>
>> Here's a challenge:  What is the simplest non-contrived example where an
>> "is" comparison is *required*.  Where substitution of an "==" comparison
>> would cause the program to fail or be significantly less efficient?   (I'm
>> not including the nearly immeasurably small timing difference between
>> v==None and v is None.)
> 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.


>
> ChrisA




More information about the Python-list mailing list