Skip to content Skip to sidebar Skip to footer

What Should Replace Comparisons With False In Python?

I have a function that returns False if something isn't found, and returns a data structure with what I'm looking for otherwise. When I assign the value returned from this functio

Solution 1:

As a return value indicating absence of a result, None is almost always better.

  • If you must use False, use not my_var. This assumes non - False return values are never "falsy" (bool() converts it into False - this is the case for empty strings, empty collections, and a few other things).

  • If objects may be falsy but must be distinguished from False, then the comparison is necessary and you'll have to ignore the error (a minor variation, my_var is False would be slightly more idiomatic, but it's virtually the same). But that's not a nice situation to be in and you should avoid it for the fake of clarity.

To repeat myself: If at all possible, use None and test for my_var is None.

Solution 2:

Normally you would return None instead of False i.e. if an object doesn't match. And then check if my_var == None: as all not 0, not False and not None return True.

Solution 3:

If you just want to check for a falsy value:

myval = findit('something')
if not myval:
   "not found"

You don't want to do this if you could actually return a value for the "is-found" case which has a falsy value. E.g., if [] (empty list) is found, this will still report "not found".

If you care that it is actually False, use is. True, False, and None are singletons, so the identity comparison operator is used.

if myval isFalse:
   "not found"

In this case you are using False as a sentinel value to indicate that there is no result.

Usually None is used as a sentinel "no-value", however, so I suggest you change the signature of your function to return None if no value is found. This conforms better with Python idiom and the behavior of methods such as {}.get('missing-key').

myval = findit('something')
if myval isNone:
    "not found"

In cases where no sentinel value is possible because any value could be returned (even None or False), Python uses an exception to signal that no value was found. E.g. {}['missing-key'] will raise KeyError.

Solution 4:

Usually you'd just use not:

if not my_var: continue

Solution 5:

Python is actually more strongly typed than C++ in this regard. Only genuine booleans can be True or False.

So my_var must be a boolean. Therefore you just check it as one.

if not my_var:
     continue

Post a Comment for "What Should Replace Comparisons With False In Python?"