When running the following line:
>>> [0xfor x in (1, 2, 3)]
I expected Python to return an error.
Instead, the REPL returns:
[15]
What can possibly be the reason?
As others have explained, it’s just the hexadecimal number 0xf
followed by the operator or
. Operators generally don’t need surrounding spaces, unless necessary to avoid ambiguity. In this case, the letter o
cannot be part of a hexadecimal number, so there is no ambiguity. See the section on whitespace in the Python language reference.
The rest of the line is not evaluated because of short-circuit evaluation, although it is parsed and compiled, of course.
Using that same “trick” you can write similarly obfuscated Python code that doesn’t throw exceptions, for example:
>>> 0xbin b'in'
False
>>> 0xbis 1000
False
>>> 0b1and 0b1is 0b00
False
>>> 0o1if 0b1else Oy1then
1
Other answers already tell what exactly happens. But for me, the interesting part was that the operator is recognized even without whitespace between the number and it. Actually, my first thought was "Wow, Python has a weird parser".
But before judging too harshly, maybe I should ask my other friends what they think:
Perl:
$ perl -le 'print(0xfor 3)'
15
Lua:
$ lua5.3 -e 'print(0xfor 4)'
15
Awk doesn't have or
, but it has in
:
$ awk 'BEGIN { a[15]=1; print(0x0fin a); }'
1
Ruby? (I don't really know it, but let's guess):
$ ruby -e 'puts 0x0for 5'
15
Yep, FWIW, Python is not alone, all of those other script-type languages also recognize the alphabetic operators even if stuck immediately to the back of a numeric constant.