Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't python3 care about non-ascii characters in source file?

Suppose I have a .py file with the following contents

print('(ノಠ益ಠ)ノ彡┻━┻')

When called by python3 it prints the angry guy flipping a table, however on python2 we get SyntaxError and need to add a declaration line like # coding: utf-8 in the file to run it.

My question is why doesn't python 3 care about non-ascii characters? I don't see any description of that in PEP 0263. How does the interpreter guess the encoding of the file correctly when I didn't specify that, where is the behaviour documented?

like image 393
wim Avatar asked Jan 27 '26 23:01

wim


1 Answers

Python 3 uses utf-8 as the default source code encoding.

Python 2 uses ASCII by default, so unless you explicitly tell Python # -*- coding: utf-8 -*- at the top of your file, it doesn't know how to handle character values above 127.

like image 169
Tim Pietzcker Avatar answered Jan 30 '26 12:01

Tim Pietzcker



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!