我有以下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'
)
声明它的最佳方法是什么,因此它不会超过 80 个字符的 Python 行限制?
我提出了一个符合 PEP-8 的版本,它将您的属性声明为列表。
name = 'Product'
attrs = [
'product_symbol',
'entity',
'unique_id',
...
]
Product = namedtuple(name, attrs)
在attrs
中添加尾随逗号,这使得在进行差异比较时变得容易。
如果你的 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__
来处理注释,然后无论如何都委托给集合来构建类型(使用与上述相同的代码生成 +exec
(。
我建议使用 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')
如果您只是在谈论分解字符串,使其不超过 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'
)