by css · 5y ago · 0 comments
https://docs.python.org/3/reference/lexical_analysis.html#wh...
Also Python: Meh, you can leave out the whitespace, I'll figure it out
I've never encountered this issue before.
The reason I've never encountered this issue, or even needed to know it was an issue is because I use good development tools. 1) Pycharm highlighted the or in orange, making it clear that it was being interpreted as a keyword, 2) I use a linter (as we all should) which explicitly highlights the lack of whitespace around the token as an issue (PEP 8: E225), and 3) I use a code formatter (which we all should) which, again, highlights this statement as requests that I fix it.
Python has a lot of flaws. This one is down near the bottom of ones that are even really worth talking about.
Reminds me of Fortran.
When we were in college learning FORTRAN, students would ask for help from the teaching assistants at the computer center. One big problem was FORTRAN allowed horrible spaghetti code because GOTO statements could be used anywhere. It was easy to jump into and out from loops. The TAs had a tough job.
It didn't help when people would deliberately mess with the TAs by asking about code with language features similar to those in the article you linked. Something like IIRC after 47 years:
DO 15 I = (1, 100)
purported loop stuff goes here
15 final statement of loop
That is also not a loop control statement. Instead it is an assignment to a complex number. % cat 0xfor.py
0xfor 1
% python -m tokenize -e '0xfor.py'
0,0-0,0: ENCODING 'utf-8'
1,0-1,3: NUMBER '0xf'
1,3-1,5: NAME 'or'
1,6-1,7: NUMBER '1'
1,7-1,8: NEWLINE '\n'
2,0-2,0: ENDMARKER ''
Also, literals have to be evaluated before names, otherwise you could overwrite them: >>> 0xzzz = 1
File "<stdin>", line 1
0xzzz = 1
^
SyntaxError: invalid hexadecimal literal
>>> 0xf = 1
File "<stdin>", line 1
0xf = 1
^
SyntaxError: cannot assign to literal
[0]: https://docs.python.org/3/library/stdtypes.html#float.fromhe...[1]: https://github.com/python/cpython/blob/5ce227f3a767e6e44e7c4...
[2]: https://github.com/python/cpython/blob/5ce227f3a767e6e44e7c4...
> the first thing it sees looks like the start of a number
Yes, because it checks if the token is a number before checking if it is a name.
This isn't a bug. It's a slightly loose grammar spec that can surprise python users who don't play golf.