Lin Ma
Lin Ma

Reputation: 10139

Check string "None" or "not" in Python 2.7

Wondering if if not foo is None is the same as if foo? Using Python 2.7 and foo is a string.

Upvotes: 7

Views: 30097

Answers (4)

Salva
Salva

Reputation: 6847

Operator is compares ids (you can check the id of something with id(something)). As there is only one instance of None, any expression in the form something is None will be False except for None is None or if something == None. Operator not has less precedence than comparisons (and is is a comparison operator) so the result for not string is None which is the same as not (string is None) is always True.

Nevertheless a string object is considered True if it is not the empty string and False if it is the empty string.

So, one of the expressions is always True and the other can vary so no, they are not equivalent.

Upvotes: 3

MSeifert
MSeifert

Reputation: 152647

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:

  1. 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 to False because their __bool__ method returns False.
  2. If a.__bool__ is not implemented then it checks what a.__len__.__bool__ returns.

    • '', [], set(), dict(), etc. will evaluate to False because their __len__ method returns 0. Which is False because bool(0) is False.
  3. If even a.__len__ is not implemented then if just returns True.

    • so every other objects/function/whatever is just True.

See also: truth-value-testing in thy python documentation.

Upvotes: 11

Sci Prog
Sci Prog

Reputation: 2691

No. Try this code

foo=''
if foo:
  print (1)
else:
  print (2)
if not foo is None:
  print (3)
else:
  print (4)

it will print

2
3

Upvotes: 2

tianwei
tianwei

Reputation: 1879

No, not the same when foo is an empty string.

In [1]: foo = ''

In [2]: if foo:
   ...:     print 1
   ...:

In [3]: if foo is None:
   ...:     print 2
   ...:

In [4]: if not foo is None:
   ...:     print 3
   ...:
3

Upvotes: 5

Related Questions