I have a relatively simple Python code:
import threading
class Foo():
def __init__(self):
self._thread = None
def start(self):
self._thread = threading.Thread(...)
def stop(self):
if self._thread:
...
A colleague suggested that I should compare with None
explicitly in stop
function: if self._thread is not None:
I am not sure which version is more Pythonic: the implicit or explicit check? Also, if I use any other type (apart from collections, which when evaluated in boolean context test for emptiness) should I compare to None
explicitly?
It depends on the values your variable may take and the expectations your code has. If your variable may take on other falsey values, then yes, the difference between None
and, say, []
may be significant and you need to explicitly check for is None
.
But not always. What if your value is a falsey []
, and you're writing an if foo:
to decide whether you have a value that needs processing? Well, an empty list might not need processing either, since it's empty. So both None
and []
can be treated the same. In this case you'd need to explicitly check for is None
and and empty list, in which case if foo:
already encapsulates both very succinctly.
In your case, if the variable can be either None
or a Thread
, there's no difference whether you add is not None
or not, it will behave identically in both cases. So why make it more verbose than it needs to be?
There's no one rule that fits all situations.