When to use utf8 as a header in py files

后端 未结 5 1570
误落风尘
误落风尘 2021-02-05 05:32

Some source files, from downloaded code, have the following header

# -*- coding: utf-8 -*-

I have an idea what utf-8 encoding is but why would

5条回答
  •  遇见更好的自我
    2021-02-05 05:55

    Whenever text is read or written, encodings come in play. Always. A python interpreter has to read your file as text, to understand it. The only situation where you could get away without having to deal with encodings is when you only use characters in the ASCII range. The interpreter can in this case use virtually any encoding in the world, and get it right because almost all encodings encode these characters to same bytes.

    You should not use coding: utf-8 just because you have characters beyond ascii in your file, it can even be harmful. It is a hint for the python interpreter, to tell it what encoding your file is in. Unless you have configured your text editor, the text editor will most likely not save your files in utf-8. So now the hint you gave to the python interpreter, is wrong.

    So you should use it when your file is encoded in utf-8. If it's encoded in windows-1252, you should use coding: windows-1252 and so on.

提交回复
热议问题