For empty strings both are different:
foo = '' if foo: print 'if foo is True'
will not print anything because it is empty and therefore considered False
but:
if foo is not None: print 'if not foo is None is True'
will print because foo
is not None!
I Changed it according to PEP8. if foo is not None
is equivalent to your if not foo is None
but more readable and therefore recommended by PEP8.
A bit more about the general principles in Python:
if a is None: pass
The if
will only be True
if a = None
was explicitly set.
On the other hand:
if a: pass
has several ways of evaluating when it is True
:
- Python tries to call
a.__bool__
and if this is implemented then the returned value is used.- So
None
,False
,0.0
,0
will evaluate toFalse
because their__bool__
method returnsFalse
.
- So
- If
a.__bool__
is not implemented then it checks whata.__len__.__bool__
returns.''
,[]
,set()
,dict()
, etc. will evaluate toFalse
because their__len__
method returns0
. Which isFalse
becausebool(0)
isFalse
.
- If even
a.__len__
is not implemented then if just returnsTrue
.- so every other objects/function/whatever is just
True
.
- so every other objects/function/whatever is just
See also: truth-value-testing in thy python documentation.