Python中的链式方法调用缩进样式 [英] Chained method calls indentation style in Python

查看:135
本文介绍了Python中的链式方法调用缩进样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过阅读PEP-8,我知道您应该将右括号放在函数调用中最后一个参数的同一行:

From reading PEP-8, I get it that you should put the closing parenthesis on the same line as the last argument in function calls:

ShortName.objects.distinct().filter(
    product__photo__stockitem__isnull=False)

最好完全避免使用长表达式。但是如果不受欢迎,您将如何进行多个链接方法调用?结束符应该换行吗?

Probably, long expressions are best to avoid at all. But if it's undesirable, how would you go about multiple chained method calls? Should the closing paren be on a new line?

ShortName.objects.distinct().filter(
    product__photo__stockitem__isnull=False
).values_list('value', flat=True)

那么无参数方法呢? 如何在不引用中间返回值的情况下在多行上写它们?

What about no-arguments methods? How to write them on multiple lines without referencing the intermediate return values?

ShortName.objects.distinct(
    ).filter().values() # looks ugly






更新:存在一个重复的问题,如何在Python中断开一系列链接方法?可接受的答案表示jQuery风格的一种熟悉之处,即以点开头的每一行。作者没有提供任何原因或权威参考,因此,我想对这种风格或替代方法进行确认。


Update: There's a duplicate question of How to break a line of chained methods in Python?. The accepted answer suggests a familiar from jQuery style of starting each new line with a dot. The author doesn't provide any reasons or authoritative references, so I'd like to get a confirmation on such style or an alternative.

推荐答案

在这种情况下,首选使用行继续符来打开括号。

This is a case where a line continuation character is preferred to open parentheses.

ShortName.objects.distinct() \
         .filter().values()      # looks better

需要这种样式随着方法名称变长以及方法开始采用参数,这种情况变得更加明显:

The need for this style becomes more obvious as method names get longer and as methods start taking arguments:

return some_collection.get_objects(locator=l5) \
                      .get_distinct(case_insensitive=True) \
                      .filter(predicate=query(q5)) \
                      .values()

PEP 8旨在以一种常识的方式进行解释,并兼顾实用性和美观性。欣然违反任何导致丑陋或难以阅读代码的PEP 8准则。

PEP 8 is intend to be interpreted with a measure of common-sense and an eye for both the practical and the beautiful. Happily violate any PEP 8 guideline that results in ugly or hard to read code.

话虽如此,如果您经常发现自己与PEP 8不符,可能是迹象表明存在可读性问题超出了您对空白的选择:-)

That being said, if you frequently find yourself at odds with PEP 8, it may be a sign that there are readability issues that transcend your choice of whitespace :-)

这篇关于Python中的链式方法调用缩进样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆