I may be being a little pedantic here, but I would say the best answer is
if my_var is not None and 'something' in my_var:
#do something
The difference being the explicit check for None
, rather than the implicit conversion of my_var
to True
or False
.
While I'm sure in your case the distinction isn't important, in the more general case it would be quite possible for the variable to not be None
but still evaluate to False
, for example an integer value of 0
or an empty list.
So contrary to most of the other posters' assertions that it's safe, I'd say that it's safe as long as you're explicit. If you're not convinced then consider this very contrived class:
class Contrived(object):
def __contains__(self, s):
return True
def __nonzero__(self):
return False
my_var = Contrived()
if 'something' in my_var:
print "Yes the condition is true"
if my_var and 'something' in my_var:
print "But this statement won't get reached."
if my_var is not None and 'something' in my_var:
print "Whereas this one will."
Yes I know that's not a realistic example, but variations do happen in real code, especially when None
is used to indicate a default function argument.