Python 命名约定 - 命名元组

Python naming convention - namedtuples

我是 Python 的新手,我一直在阅读在线文档并(尝试)遵循 PEP 0008 以获得良好的 Python 代码风格。 很好奇在研究re库的时候在官方Pythondocs找到的代码段:

import collections

Token = collections.namedtuple('Token', ['typ', 'value', 'line', 'column'])

我无法理解为什么 Token 变量的首字母大写;我已经通读了 PEP 0008,但我所看到的内容没有参考资料。如果它是一个常数(据我所知它不是)?

这里的关键是collections.namedtuple。正如文档所说,

collections.namedtuple(typename, field_names, verbose=False, rename=False)

Returns a new tuple subclass named typename. The new subclass is used to create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable. Instances of the subclass also have a helpful docstring (with typename and field_names) and a helpful __repr__() method which lists the tuple contents in a name=value format.

没有违反PEP 8; Token 是用户定义的 class 并且它的名字应该大写。

在您提供的代码段中,Token 是一个 named tuple,绝对不是常量。它没有遵循其他变量名的命名风格,只是强调它是一个class工厂函数。 如果您将其写为 token,PEP 0008 样式检查器将不会发出警告(例如 PyCharm)但我认为这不是好的做法,因为这样它就不会将其区分为 class 工厂名称。

因此,namedtuples 属于 PEP 0008 中的 Class names。可惜没有更明确地说明。 除了您为 writing a tokenizer, this can also be seen in the collections.namedtuple docs 示例提到的示例:

Point = namedtuple('Point', ['x', 'y'])
Point3D = namedtuple('Point3D', Point._fields + ('z',))
Book = namedtuple('Book', ['id', 'title', 'authors'])