1

I have a function that attempts to read a value and returns False if there is a failure. Similar to this:

import random
def fun():
    vals = [random.randint(0,3)]
    try:
        choice = vals[random.randint(0,1)]
    except Exception as e:
        logger.exception(e)
        return False

    return choice

This function is used by a test which behaves differently depending on the return value. When calling this function is using the 'is' keyword the only way to distinguish 0 from False?

test code...

if fun() is False:
    do something...
if fun() == False:
    what if fun returns 0 value
if not fun():
    what if fun returns 0 value
Evan Brittain
  • 547
  • 5
  • 15
  • 3
    You'd be better off changing your function so that it doesn't return False and 0 to mean different things; but yes, `is False` is a way to distinguish them. You could also check if the value's type is `bool`. – khelwood Feb 21 '20 at 22:38
  • 2
    This might be more of a code review than a problem, I'd recommend simply returning a value from the function, and then catching an exception rather than returning `False` would be cleaner in my personal opinion – jamylak Feb 21 '20 at 22:42
  • 2
    At the very least, return `None` instead of `False`. – chepner Feb 21 '20 at 22:43
  • `== False` is bad for at least two different reasons, and so is using `except Exception` like this (see: https://stackoverflow.com/questions/4990718/about-catching-any-exception, https://stackoverflow.com/questions/54948548/what-is-wrong-with-using-a-bare-except?noredirect=1&lq=1). – AMC Feb 21 '20 at 23:45

0 Answers0