Question

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 function to a variable my_var in a for loop, I do a if my_var == False: continue to carry on.

pychecker doesn't like this and reports Comparisons with False are not necessary and may not work as expected.

What's the python way for doing this?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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 is False:
   "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 is None:
    "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.

Usually you'd just use not:

if not my_var: continue

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top