Repository navigation
Improve error reporting for invalid character in source code #84773
Description
Activity
Currently you get SyntaxError with message "invalid character in identifier" in two cases:
- The source code contains some non-ASCII non-identifier character. Usually it happens when you copy code from internet page or PDF file which was "improved" by some enhachaizer which replaces spaces with non-breacking spaces, ASCII minus with a dash or Unicode minus, ASCII quotes with fancy Unicode quotes. They do not look like a part of identifier at all. The error message also does not say what character is invalid, and it is hard to find the culprit because they look too similar to correct characters (especially with some monospace fonts).
See https://mail.python.org/archives/list/python-ideas@python.org/thread/ILMNJ46EAL4ENYK7LLDLGIMYQKZAMMWU/ for discussion.
- Other case is very special -- when the source code contains the declaration for the utf-8 encoding followed by non-UTF-8 bytes sequences. It is rarely happen in real world.
The proposed PR improves errors for these cases.
>>> print(123—45) File "<stdin>", line 1 print(123—45) ^ SyntaxError: invalid character '—' (U+2014)
-
The error message no longer contains misleading "in identifier".
-
The error message contains the invalid character, literal and its hexcode.
-
The caret points on the invalid character. Previously it pointed on the last non-ascii or non-alphabetical character followed the invalid character (5 in the above example).
-
For the special case of non-decodable UTF-8 sequence the syntax error message is more informative: "(unicode error) 'utf-8' codec can't decode byte 0xff ...". Although this case needs further improvements.
- added3.9 (EOL)end of lifeend of lifeinterpreter-core(Objects, Python, Grammar, and Parser dirs)(Objects, Python, Grammar, and Parser dirs)type-featureA feature request or enhancementA feature request or enhancement
on May 11, 2020
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields: