2

I have a probably quite simple question but was wondering between the difference of these two statements:

if not os.path.isfile(file):
  #Do some stuff
if os.path.isfile(file) is False:
  #Do some stuff

What are the differences (if any) between the two? To my understanding they both return a True or False value, so is it just a matter of preference or are there any significant differences?

Alec
  • 8,529
  • 8
  • 37
  • 63
Nick
  • 667
  • 7
  • 19
  • 1
    Possible duplicate of [Understanding Python's "is" operator](https://stackoverflow.com/questions/13650293/understanding-pythons-is-operator) – Rach Sharp May 22 '19 at 13:14
  • 2
    *wow*, did this really require 6 answers (plus some deleted) when there is a wealth of better information on SO e.g. https://stackoverflow.com/a/100762/4711754 – Andrew Allen May 22 '19 at 13:23

4 Answers4

4

In python (and other dynamic languages) there is the concept of truthy/falsy value. True/False are not the only things that evaluate as true/false

if not []: 
   print("this will be printed")

if [] is False:
   print("this won't")

Another problem is that you should compare with x == False, and not x is False. The False is a singleton object in the current implementation of CPython, but this is not guaranteed by the specification.

Community
  • 1
  • 1
blue_note
  • 27,712
  • 9
  • 72
  • 90
1

In your case, since we know os.path.isfile returns True or False, there is no difference.

In general, there are a lot of objects in python which, when interpreted as boolean, will evaluate to False.

Think of this:

empty_list = []
if not empty_list:
    print('List is not empty')
if empty_list is False:
    print('List is False')

Among the others, None, "" and [] will evaluate to False.

So testing with not variable is usually the preferred way.

bracco23
  • 2,181
  • 10
  • 28
1

It's usually better to use the first, since it works even if you're not checking an actual boolean value in a Python implementation where False is a singleton object.
Uniformity is good, and so is portability.

>>> if 0 is False: print "false"
>>> if not 0: print "false"
false
>>> if [] is False: print "false"
>>> if not []: print "false"
false
>>> if "" is False: print "false"
>>> if not "": print "false"
false

It also protects against mishaps like this:

>>> False = 1
>>> True == False
True
molbdnilo
  • 64,751
  • 3
  • 43
  • 82
0

You should know: False == 0 == None in case of if condition. If you use if not, you can cover all version of False (zero value). If you use == False you cannot handle the 0 or None. if not is recommended. The is operator is a different story (is not same as ==) but you can read more details on this link: Understanding Python's "is" operator

milanbalazs
  • 4,811
  • 4
  • 23
  • 45