Search code examples
pythonbooleanpychecker

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 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?


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.