代码之家  ›  专栏  ›  技术社区  ›  gogasca

名称双重声明缩进

  •  3
  • gogasca  · 技术社区  · 7 年前

    我有以下内容 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行限制?

    4 回复  |  直到 7 年前
        1
  •  5
  •   cs95 abhishek58g    7 年前

    我建议使用符合PEP-8的版本,将属性声明为一个列表。

    name = 'Product'
    attrs = [
       'product_symbol',
       'entity',
       'unique_id',
       ... 
    ]
    
    Product = namedtuple(name, attrs)
    

    将尾随逗号添加到 attrs , this makes it easy when doing diff comparisons .

        2
  •  4
  •   wim    7 年前

    如果您的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 是一个类,它使用 metaclasses 还有一个习俗 __new__ 处理注释,然后 delegates to collections anyway 构建类型(使用相同的代码生成+ 执行程序 如上所述)。
        3
  •  -1
  •   martineau    7 年前

    我建议使用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')
    
        4
  •  -2
  •   Ólafur Aron    7 年前

    如果您只想拆分字符串,使其不超过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'
        )