我应该在Python 3中使用编码声明吗?

问题:我应该在Python 3中使用编码声明吗?

默认情况下,Python 3对源代码文件使用UTF-8编码。我还应该在每个源文件的开头使用编码声明吗?喜欢# -*- coding: utf-8 -*-

Python 3 uses UTF-8 encoding for source-code files by default. Should I still use the encoding declaration at the beginning of every source file? Like # -*- coding: utf-8 -*-


回答 0

因为默认值为 UTF-8,所以仅在偏离默认值时或者在依赖其他工具(例如IDE或文本编辑器)来使用该信息时,才需要使用该声明。

换句话说,就Python而言,仅当您要使用不同的编码时,才需要使用该声明。

其他工具(例如您的编辑器)也可以支持类似的语法,这就是PEP 263规范在语法上具有相当大的灵活性的原因(它必须是注释,文本coding必须在其中,后跟a :=字符以及可选的空白,然后是公认的编解码器)。

请注意,它仅适用于Python如何读取源代码。它不适用于执行该代码,因此不适用于打印,打开文件或字节与Unicode之间的任何其他I / O操作转换。有关Python,Unicode和编码的更多详细信息,强烈建议您阅读Python Unicode HOWTO或Ned Batchelder撰写的非常详尽的Pragmatic Unicode演讲

Because the default is UTF-8, you only need to use that declaration when you deviate from the default, or if you rely on other tools (like your IDE or text editor) to make use of that information.

In other words, as far as Python is concerned, only when you want to use an encoding that differs do you have to use that declaration.

Other tools, such as your editor, can support similar syntax, which is why the PEP 263 specification allows for considerable flexibility in the syntax (it must be a comment, the text coding must be there, followed by either a : or = character and optional whitespace, followed by a recognised codec).

Note that it only applies to how Python reads the source code. It doesn’t apply to executing that code, so not to how printing, opening files, or any other I/O operations translate between bytes and Unicode. For more details on Python, Unicode, and encodings, I strongly urge you to read the Python Unicode HOWTO, or the very thorough Pragmatic Unicode talk by Ned Batchelder.


回答 1

不,如果:

  • 整个项目仅使用UTF-8,这是默认设置。
  • 并且您确定您的IDE工具不需要每个文件中的编码声明。

是的,如果

  • 您的项目依赖于不同的编码
  • 或依赖于许多编码。

对于多编码项目:

如果某些文件在中进行了编码non-utf-8,那么即使对于这些文件,UTF-8您也应该添加编码声明,因为黄金法则是Explicit is better than implicit.

参考:

  • PyCharm不需要该声明:

在pycharm中为特定文件配置编码

  • vim不需要该声明,但是:
# vim: set fileencoding=<encoding name> :

No, if:

  • entire project use only the UTF-8, which is a default.
  • and you’re sure your IDE tool doesn’t need that encoding declaration in each file.

Yes, if

  • your project relies on different encoding
  • or relies on many encodings.

For multi-encodings projects:

If some files are encoded in the non-utf-8, then even for these encoded in UTF-8 you should add encoding declaration too, because the golden rule is Explicit is better than implicit.

Reference:

  • PyCharm doesn’t need that declaration:

configuring encoding for specific file in pycharm

  • vim doesn’t need that declaration, but:
# vim: set fileencoding=<encoding name> :