Python编码注释格式

Python Encoding Comment Format

原来在Python2.7中我是这样指定源码编码的:

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

现在我才注意到,PEP263 也允许这样做:

# coding=utf-8

它们之间有什么区别吗?编辑器兼容性、跨平台等怎么样?

Python3 呢? python 3 是否仍需要此注释,或者 python 3 中的任何代码是否默认为 utf-8?

自 Python 3 起,默认编码为 utf-8。您仍然可以使用特殊格式的注释 # -*- coding: <encoding name> -*-.

更改编码

docs 建议使用此编码表达式,因为它也可被 GNU Emacs 识别。

由于python检查前两行是否匹配正则表达式coding[=:]\s*([-\w.]+)
# coding=utf-8也可以确保utf-8编码但无法识别由 GNU Emacs 开发。

看看 PEP3120,它将 python 源代码的默认编码更改为 UTF-8

对于 python 3.x 因此在 docs 中找到:

If a comment in the first or second line of the Python script matches the regular expression coding[=:]\s*([-\w.]+), this comment is processed as an encoding declaration [...] The recommended forms of an encoding expression are:

# -*- coding: <encoding-name> -*-

which is recognized also by GNU Emacs, and

# vim:fileencoding=<encoding-name>

which is recognized by Bram Moolenaar’s VIM. If no encoding declaration is found, the default encoding is UTF-8

因此,带回家的信息是:

  1. python 3.x 不一定需要指定 utf-8,因为它是默认值
  2. 编码行的写法在某种程度上是个人选择(只是文档中的推荐),它只需要匹配正则表达式即可。