Python Basic Doubt

Gary Herron gary.herron at islandtraining.com
Sat Aug 10 20:42:21 EDT 2013


On 08/10/2013 03:09 PM, Chris Angelico wrote:
> On Sat, Aug 10, 2013 at 10:48 PM, Gary Herron
> <gary.herron at islandtraining.com> wrote:
>> This is an oversimplification, but generally useful for all beginner (and
>> most advanced) programmers:
>>      Don't use "is" for comparisons.  Use "==".
>> It 20 years of programming Python, I've *needed* to use "is" ... only once
>> or twice.
> Hrm, I wouldn't make it that hard a rule. Both comparisons have their
> place. As has been mentioned earlier in this thread, checking if
> something is None is spelled "if something is None". Checking if it
> equals zero is spelled "if it == 0", which is a quite different check.
> The other common check that uses 'is' is with an argument default
> where absolutely anything could be passed:
>
> _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.

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.)

Gary Herron



More information about the Python-list mailing list