
On 09/08/12 18:09, Rob Cliffe wrote:
On 09/08/2012 06:48, Georg Brandl wrote:
On 08.08.2012 23:56, Ned Batchelder wrote:
On 8/8/2012 4:29 PM, Georg Brandl wrote:
For None, "==" and "is" are equivalent, because no other object is equal to None. For True and False, this is different, and using "is" here is a very stealthy bug.
It's easy to make other objects == None, by writing buggy __eq__ methods. That doesn't happen much, but it's easier with __ne__, where the negated logic is easy to screw up. I've seen it happen. Use "is None", not "== None".
[...]
Surely that's a reason to fix the buggy __eq__ and __ne__ methods, not to avoid using them. (Sorry Georg I accidentally replied to you not to the list.)
It may not be in your power to fix the buggy method, because it may be in the caller's code, not yours.
Or it may not even be a bug -- maybe the caller has some good reason for wanting his object to compare equal to None.
If I write a function like this:
def spam(n=None): """Print spam n times. If n is not given or is None, print a nasty message.""" if n == None: print("Nobody expects the SPANISH INQUISITION!!! ***ominous chords***") else: for i in range(n-1): print("Spam! ", end='') print("Glorious SPAM!!!")
my intention, and the documented behaviour, is that n=None, and nothing but n=None, should trigger the nasty message. So my function has a bug, not the caller, because my code fails to live up to my promise.
Blaming the caller for passing a "buggy" object is just a cop-out. I made a promise that None and only None is special, and my code breaks that promise. My bug, not the caller's.
The fix is, of course, to use "is None" unless I genuinely want to match None by equality for some strange reason.