In JavaScript, if I want to know if foo == false
and foo != 0
(or some other "falsy" value), I use foo === false
, and that gives me a nice simple, exact comparison. It's even computationally faster because it doesn't try to test multiple types of equivalence. In Python the only equivalent I found to ===
and !==
was is
and is not
. Now, after getting the SyntaxWarning: "is" with a literal. Did you mean "=="?
error, and reading questions, answers, and articles about why is
shouldn't be used in this, I'm left scratching my head.
For example:
def foo(bar=False):
if bar != False:
print(bar)
else:
print('default!')
Of course I ran into a case where bar
was set to 0
and printed default!
. I had been dealing with it like so:
def foo(bar=False):
if bar is not False:
print(bar)
else:
print('default!')
So if I'm not supposed to do that, what's the correct approach? Do I need to type out bar != False and bar != 0
every time?
CodePudding user response:
One option is :
def foo(bar=None):
if bar is not None:
print(bar)
else:
print('default!')
Only the 'None' object is identical to 'None' so any value of bar
except None
will print 'default'