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?
In Python, None has nothing to do with the boolean value False. None in Python is actually an object implemented by NoneType class. False is a boolean object implemented by the bool class.
Use the isinstance() Function to Check if a Variable Is None in Python. The isinstance() function can check whether an object belongs to a certain type or not. We can check if a variable is None by checking with type(None) . It returns a tuple, whose first element is the variable whose value we want to check.
It's one of Python's Magic Methods. The confusing thing is, that bool(None) returns False , so if x is None, if x works as you expect it to. However, there are other values that are evaluated as False . The most prominent example is an empty list.
Never use is
for (value) equality testing. Only use it to test for object identity. It may work for the example if string is ''
, but this is implementation dependent, and you can't rely on it.
>>> a = "hi"
>>> a is "hi"
True
>>> a = "hi there!"
>>> a is "hi there!"
False
Other than that, use whatever conveys the meaning of your code best.
I prefer the shorter if string:
, but if string != '':
may be more explicit.
Then again if variable:
works on every kind of object, so if variable
isn't confined to one type, this is better than if variable != "" and variable != 0:
etc.
To expand on Tim Pietzcker's answer:
if string:
print string
This tests if string
evaluates to True. I.E.
>>> bool("")
False
>>> bool(None)
False
>>> bool("test")
True
So it's not only testing if it is empty, but if it is None
or empty. This could have an impact depending on how you treat None
/empty.
Firstly, don't use if string is '':
because this is not guaranteed to work. The fact that CPython interns short strings is an implementation detail and should not be relied on.
Using if string:
to check that string
is non-empty is, I think, a Pythonic way to do it.
But there is nothing wrong about using if string == ''
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With