True == 1 weirdness
Jussi Piitulainen
harvesting at makes.email.invalid
Wed Sep 16 08:53:44 EDT 2015
Blake T. Garretson writes:
> I am maintaining some old code where the programmer used 1 for True
> because booleans hadn't been added to Python yet. I'm getting some
> weird behaviour, so I created some simple tests to illustrate my
> issue.
>
> >>> 1 in {1:1} #test1
> True
> >>> 1 in {1:1} == 1 #test2
> False
> >>> (1 in {1:1}) == 1 #test3
> True
> >>> 1 in ({1:1} == 1) #test4
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: argument of type 'bool' is not iterable
> >>>
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.
More information about the Python-list
mailing list