Home > Software design >  bool() vs is not None
bool() vs is not None

Time:05-07

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?

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

  1. None
  2. False
  3. Zero
  4. Operators...
  • Related