Is there any low-level, implementation-related difference (performance-ish) between these approaches..?
# check if string is empty
# the preferred way it seems [1]
if string:
print string
else:
print "It's empty."
# versus [2]
if string is '':
# or [3]
if string == '':
For example, when testing for None, I still find it more readable and explicit to do:
if some_var is not None:
..instead of..
if not some_var:
if not some_var, at least for me, always reads “if some_var does not exist”.
Which is better to use, what are the proper use cases for ==, is and bool-testing?
Never use
isfor (value) equality testing. Only use it to test for object identity. It may work for the exampleif string is '', but this is implementation dependent, and you can’t rely on it.Other than that, use whatever conveys the meaning of your code best.
I prefer the shorter
if string:, butif string != '':may be more explicit.Then again
if variable:works on every kind of object, so ifvariableisn’t confined to one type, this is better thanif variable != "" and variable != 0:etc.