You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何规范声明namedtuple以符合80字符行限制?

符合80字符行限制的NamedTuple声明方式

这里有几种简洁且符合PEP 8行宽规范的写法,你可以根据自己的偏好选择:

方法1:多行字符串拼接(简洁型)

利用Python隐式的字符串拼接特性,把长字段串拆分成多行,每行控制在80字符以内:

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'
)

这种写法保持了字段串的连贯性,同时拆分后每行长度都不会超标,适合字段数量不算特别多的场景。

方法2:列表+join(高可读性型)

把每个字段单独放到列表里,再用' '.join()拼接成字符串。这种方式最直观,方便后续添加/删除字段,也更容易排查字段拼写问题:

from collections import namedtuple
Product = namedtuple(
    'Product',
    ' '.join([
        'product_symbol',
        'entity',
        'unique_id',
        'as_of_date',
        'company_name',
        'followers',
        'linkedin_employees',
        'linkedin',
        'industry',
        'date_added',
        'date_updated',
        'description',
        'website',
        'sector',
        'product_industry'
    ])
)

每个字段独占一行,可读性拉满,尤其适合字段数量较多的情况。

方法3:括号包裹的多行字符串(兼容型)

如果担心隐式拼接的可读性,可以用括号把多行字符串包起来,效果和方法1一致,但结构更清晰:

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'
    )
)

以上三种写法都能完美符合80字符行限制的要求,同时保持代码的整洁性和可读性。

内容的提问来源于stack exchange,提问作者gogasca

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:55:24