integer >= 1 == True and integer.0 == False is bad, bad, bad!!!

Ian Kelly ian.g.kelly at gmail.com
Sun Jul 11 02:57:55 EDT 2010


On Sun, Jul 11, 2010 at 12:03 AM, rantingrick <rantingrick at gmail.com> wrote:
> This is another example of the damage integer booling does to your
> code and your mind. What happened to explicit is better than implicit?

Explicit is better than implicit.  Hence, if you're specifically
testing for the property of not being None rather than for the more
general truth value, it's better to write "if choiceIdx1 is not None"
rather than just "if choiceIdx".  This holds true for empty
collections as well.

On Sun, Jul 11, 2010 at 12:22 AM, Stephen Hansen
<me+list/python at ixokai.io> wrote:
> There's numerous cases where "if x" where x is an integer is useful. A
> counter is the simplest example. Say you're counting how many
> watermelons are in your inventory there is, and you want to test if
> there's any or not. "if watermelons" is the concise, readable,
> understandable way to express this. Readability counts.

I would also point out that the current semantics mean that
"bool(container)", "bool(len(container))", and "len(container) > 0"
are all equivalent.  I view this as a positive thing.

It also means that "if integer" in Python and "if (the_same_integer)"
in a C module have the same semantics.  It would be a nasty surprise
for writers of C modules if they didn't.

And I think that partly this is simply historical.  Before a proper
boolean type was added to Python, 1 and 0 were the norm for storing
truth values.  Changing the truth value of 0 when bools were
introduced would have broken tons of existing code.  This is also the
reason why bool is a subclass of int.



More information about the Python-list mailing list