3 ms·
Thing is, it's not actually there for backwards compatibility. Guido says as much: http://stackoverflow.com/a/6865824/1763356 http://stackoverflow.com/a/686582
by Veedrac 11y ago
Thing is, it's not actually there for backwards compatibility. Guido says as much:
http://stackoverflow.com/a/6865824/1763356 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 ^= True
- crdoconnor 11y ago>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 The 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.
- Veedrac 11y ago> E.g. this reads easier for me: len([x for x in xs if x > 10]) 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.
- crdoconnor 11y agoOk with generators then... 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.
- Veedrac 11y ago> I'm sure some people will look at this and think that it's summing all of the numbers over 10 in xs 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.
- cma 11y agoHow about this: sum(int(x > 10) for x in xs) Just require the conversion to be explicit.