Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

encoding in py_compile vs import

When a python script with non ASCII character is compiled using py_compile.compile it does not complaint about encoding. But when imported gives in python 2.7

SyntaxError: Non-ASCII character '\xe2' in file

Why is this happening? whats the difference between importing and compiling using py_compile?

like image 641
par Avatar asked Jul 26 '26 13:07

par


1 Answers

It seems that Python provides two variants of its lexer, one used internally when Python itself parses files, and one that is exposed to Python through e.g. __builtins__.compile or tokenizer.generate_tokens. Only the former one checks for non-ASCII characters, it seems. It's controlled by an #ifdef PGEN in Parser/tokenizer.c.

I have a qualified guess on why they did it this way: In Python 3, non-ASCII characters are permitted in .py files, and are interpreted as utf-8 IIRC. By silently permitting UTF-8 in the lexer, 2.7's tokenizer.generate_tokens() function can accept all valid Py3 code.

like image 136
Erik Carstensen Avatar answered Jul 30 '26 09:07

Erik Carstensen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!