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?

2

4 Answers 4

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.

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.

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
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

7
  • Actually it does handle 0, as it is treated as being falsey
    – yatu
    Commented May 22, 2019 at 13:12
  • 2
    False does not equal None
    – Alec
    Commented May 22, 2019 at 13:14
  • @yatu False and 0 are even more closely related than other falsey values, since bool is a subclass of int.
    – chepner
    Commented May 22, 2019 at 13:15
  • None is NoneType whether False is Boolean type. Commented May 22, 2019 at 13:15
  • I see your point, of course these values are not equal or same, but regarding to question in case of using if not ... condition doesn't matter that 0 or False or None. Commented May 22, 2019 at 13:22

Not the answer you're looking for? Browse other questions tagged or ask your own question.