命名元组声明的缩进

3
我有以下的 namedtuple

from collections import namedtuple

Product = namedtuple(
        'Product',
        'product_symbol entity unique_id as_of_date company_name followers linkedin_employees linkedin industry date_added date_updated description website sector product_industry'
    )

如何声明它,以便不超过 Python 的 80 个字符行限制?


圆括号内有隐含的行连接。另外,请注意Python进行隐式字符串连接,所以'Hello ' 'world'将隐式变为'Hello world' - juanpa.arrivillaga
在字符串 'product_symbol entity unique_id as_of_date ...' 中,所有这些以空格分隔的项都应该成为 namedtuple 的单独元素/成员吗? - martineau
@martineau:namedtuple 的文档中说明可以接受一个由属性名用空格和/或逗号分隔的字符串,或者一个包含每个属性名的字符串序列。两种方式都可以;当属性名不超过半打短名称时,我倾向于使用单个字符串以保持简洁,但对于更长的属性集,使用 list/tuplestr 可能会提高可读性。 - ShadowRanger
@ShadowRanger:我知道,我只是想了解OP想要完成什么。 - martineau
4个回答

5
我提议使用符合PEP-8的版本,将你的属性声明为一个列表。
name = 'Product'
attrs = [
   'product_symbol',
   'entity',
   'unique_id',
   ... 
]

Product = namedtuple(name, attrs)

attrs中添加一个尾随逗号,这样做可以在进行差异比较时更加方便

3
无需加入,第二个参数可以是一个序列。字符串版本适用于我们这些懒人 :) - juanpa.arrivillaga

4
如果您的Python版本足够现代(Python 3.6+),您可以考虑采用声明性版本:
from datetime import datetime
from typing import NamedTuple

class Product(NamedTuple):
    product_symbol: str
    entity: str
    unique_id: int
    as_of_date: datetime
    company_name: str
    followers: list
    linkedin_employees: list
    linkedin: str
    industry: str
    date_added: datetime
    date_updated: datetime
    description: str
    website: str
    sector: str
    product_industry: str

生成的类型与 collections.namedtuple 相同,但添加了 __annotations___field_types 属性。实现细节不同:
  • namedtuple 是一个工厂函数,它构建一个字符串来定义类型,然后使用 exec 返回生成的类型。
  • NamedTuple 是一个类,它使用 元类 和自定义的 __new__ 来处理注释,然后 委托给 collections 来构建类型(使用与上述相同的代码生成+exec)。

-1
我建议使用Python的隐式连接相邻字符串字面量,使其更易读并符合PEP 8标准。请注意,我还在字符串项之间添加了(可选)逗号,这样可以使其更易读。
Product = namedtuple('Product',
                     'product_symbol, entity, unique_id, as_of_date,'
                     'company_name, followers, linkedin_employees,'
                     'linkedin, industry, date_added, date_updated,'
                     'description, website, sector, product_industry')

-2

如果你只是想把字符串分割成不超过80个字符的长度,你可以在字符串中使用\字符,这样它就会被解释为单个字符串而没有换行符(\n)。

from collections import namedtuple

Product = namedtuple(
        'Product',
        'product_symbol entity unique_id as_of_date company_name followers\
         linkedin_employees linkedin industry date_added date_updated\ 
         description website sector product_industry'
    )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接