Comparison with False - something I don't understand
Alice Bevan–McGregor
alice at gothcandy.com
Thu Dec 2 03:15:42 EST 2010
Howdy!
> 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.
Comparisons against False -are- dangerous, demonstrated below.
> Yet in some situations I need to specifically check whether False was
> returned or None was returned. Why is comparison with False so bad?
(False == 0) is True
(True == 1) is True
The bool type is a subclass of int! (Run those lines in a Python
interpreter to see. ;)
> if var == False:
if var is False: …
> So how do you get around this? My functions return False and None under
> different circumstances. 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.
If you want to check not just for value equivelance (False == 0) but
literal type, use the "is" comparator. "is" checks, and others correct
me if I'm wrong, the literal memory address of an object against
another. E.g. False, being a singleton, will always have the same
memory address. (This is true of CPython, possibly not of Python
implementations like Jython or IronPython.) Using "is" will be
effective for checking for literal None as well.
When ever I need to test for None, I always use the "is" comparator.
It's also more English-like. (None, evaluating to False when using
'==', is useful when all you care about is having a blank default
value, for example.)
— Alice.
More information about the Python-list
mailing list