So while it looks weird there is a rational backwards-compatibility reason for it.
So while it looks weird there is a rational backwards-compatibility reason for it.
I think the more important reason is that Python doesn't really have an emphasis on the boolean type in general. The `if` statement works for every type, in contrast to other languages allowing only the boolean type in `if`. It is very common to use `if string_or_number_or_anything: blah blah` in Python. While I won't make a stance whether this is a good thing or not, it is still awkward that Python allows implicit conversion between `bool` and `int`.
That was a while ago, however. This behavior ought to be phased out in favor of treating it as entirely its own type.
http://stackoverflow.com/a/6865824/1763356
Alex Martelli's answer on the same page goes into more depth.
I get the worries, but this is Python - you should know what domain you're working on anyway, because you have to. It's a different philosophy to statically typed languages, and since having True and False as aliases is convenient I'm personally glad for it:
# Truth as samples
sum(x > 10 for x in xs)
(numpy.random.randint(0, 10, 1000) == 7).mean()
# Several properties are made obvious
assert True > False
my_flag ^= TrueThe only real benefit to this appears to be some shortcuts that shave a few characters off and do so, IMO, at the expense of readability.
E.g. this reads easier for me:
len([x for x in xs if x > 10])
Than this does: sum(x > 10 for x in xs)
Martelli may call this stuff contortions but to me it feels more natural.At the expense of allocating a new list, maybe. But the `sum` convention is faster, space-efficient and cleaner. It's also pretty obvious once you've seen it.
I'm sure some people will look at this and think that it's summing all of the numbers over 10 in xs:
sum(x > 10 for x in xs)
Whereas with this, which is explicit, it's substantially less likely they'll think that: sum(1 for x in xs if x > 10)
Again, I don't see the point of maintaining the weakened type system for a few minor 'clever' barely-short cuts like this. Look at what that kind of thinking did to perl.If python started throwing exceptions on all the code that treated True and False as integers, I'm pretty sure all the fixes done to accommodate that would probably make the code cleaner and easier to understand.
Perhaps it's just a bias of familiarity, but that argument seems contrived to me.
I'm worried the rest of my arguments will amount to "I like what I know", so perhaps we should lay this to rest as a difference in tastes. It does remind me a little of concatenation with `+`, which is oft-hated... and yet I've not seen a single error caused by it.
sum(int(x > 10) for x in xs)
Just require the conversion to be explicit.