Python Basic Doubt

Chris Angelico rosuav at gmail.com
Sat Aug 10 21:00:51 EDT 2013


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

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

ChrisA



More information about the Python-list mailing list