简体   繁体   中英

Python naming convention - namedtuples

I am new to Python and I have been reading both the online documentation and (trying) to follow PEP 0008 to have a good Python code style. I am curious about the code segment I found in the official Python docs while studying about the re library:

import collections

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

I cannot understand why the Token variable is named with a first letter capitalised; I have read through the PEP 0008 and there is no reference for it for what I have seen. Should it not be token instead or TOKEN if it was a constant (which for all I know it is not)?

In the code-segment you provided, Token is a named tuple , definitely not a constant. It does not follow other variable names naming style only to put emphasis on the fact that it is a class factory function . No warning will occur from an PEP 0008 style checker (like PyCharm for example) if you write it as token but I think it is not good practice since this way it does not distinguish it as a class factory name.

So, namedtuples fall under the Class names in PEP 0008. Too bad is not stated more explicitly. Besides the example you mentioned for writing a tokenizer , this can also be seen in the collections.namedtuple docs examples:

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

The key here is collections.namedtuple . As the documentation says,

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.

There is no PEP 8 violation; Token is an user-defined class and its name is capitalized as it should.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM