Comparison with False - something I don't understand

Ben Finney ben+python at benfinney.id.au
Thu Dec 2 06:19:25 EST 2010


Harishankar <v.harishankar at gmail.com> writes:

> When I run pychecker through my modules I get the message that
> comparisons with "False" is not necessary and that it might yield
> unexpected results.

Good advice.

> Yet in some situations I need to specifically check whether False was
> returned or None was returned. Why is comparison with False so bad?

Because it's almost always unnecessary and can yield unexpected results
:-)

In other words, the only purpose of the ‘bool’ type is to have values
explicitly designed for testing in Boolean conditions. Comparing them to
the literals is a code smell — indicating a poor design.

> # example code which matches both False and None
> if not var:
>     # do something

Can you give a specific real-world example of why this is not good
enough? It's likely we can suggest better ways of achieving the broader
purpose.

> So how do you get around this? My functions return False and None
> under different circumstances.

Usually it is None that will be the special case, so it's usually better
to write something like::

    result = foo()

    if result is None:
        # do special things

But that's just one possibility, and might not apply in your use case.

> Should I raise exceptions instead? I feel it's unnecessary clutter to
> use exceptions unless absolutely no other solution is available and
> yet I have doubts about the "False" value.

More details of the problem you're trying to solve would help with
giving specific advice.

-- 
 \     “I was sad because I had no shoes, until I met a man who had no |
  `\       feet. So I said, ‘Got any shoes you're not using?’” —Steven |
_o__)                                                           Wright |
Ben Finney



More information about the Python-list mailing list