1

I have two functions that return a bool. The first is using bool() and the second is using is not None.

def func_1(x) -> bool:
    return bool(x)

def func_2(x) -> bool:
    return x is not None

foo = "something"
bar = None

print(func_1(foo))
print(func_2(foo))
print("-----")
print(func_1(bar))
print(func_2(bar))

Here is the output

True
True
-----
False
False

Is there a difference between is not None and bool() in this instance? Is there something I may want to consider when using one or the other?

Brett La Pierre
  • 493
  • 6
  • 15

3 Answers3

2

Is there a difference between is not None and bool() in this instance?

Yes! Check the Python documentation here, you will find that some values are falsey even beeing different from None.


Just as an example:

>>> 0 != None
True
>>> bool(0)
False
FLAK-ZOSO
  • 3,873
  • 4
  • 8
  • 28
2

Here's the effect of bool on various types (not comprehensive):

  • numeric types: False if 0, True otherwise
  • sequence type (list, tuple, etc): False if empty, True otherwise
  • object: False if None, true otherwise

(Note that if None is assigned to a variable that previously referred to a sequence type, the semantics will change from 2nd to 3rd bullet above).

Here's the effect of is not None:

  • variable assigned to be None: False
  • other: True
constantstranger
  • 9,176
  • 2
  • 5
  • 19
  • This, added to the other two answers, makes the explaination quite complete, I guess this deserves my +1 – FLAK-ZOSO May 06 '22 at 16:02
1

According to this site, using bool function, all following will return False :

  1. None
  2. False
  3. Zero
  4. Operators...
JoelCrypto
  • 462
  • 2
  • 12