True == 1 weirdness

Chris Angelico rosuav at gmail.com
Wed Sep 16 09:05:03 EDT 2015


On Wed, Sep 16, 2015 at 10:53 PM, Jussi Piitulainen
<harvesting at makes.email.invalid> wrote:
> Ouch. I love chained comparisons more than most people, but this took a
> while to decipher. I blame you! Your parentheses mis-primed me for the
> wrong reading :) But now I expect to see a long thread about whether
> chained comparisons are a natural thing to have in the language.
>
> The second test, test2, is interpreted (almost) as
>
>   >>>> (1 in {1:1}) and ({1:1} == 1)
>
> which is obviously False.

My view is that they should remain in the language, but that
dissimilar comparisons should raise linter warnings. I can't imagine a
sane reason for chaining 'in' and equality like that (since the RHS of
'in' will be a container, and if you're testing the whole container
for equality, you probably don't care about one member in it), but for
language consistency, it's good to support it.

Chained comparisons of the same type are a great feature:

if 1 < x < 4:

And "same type" doesn't just mean the exact same operator:

if 1 < x <= 4:

It's only when you mix them up in bizarre ways that it's getting a bit weird.

ChrisA



More information about the Python-list mailing list