Chained method calls indentation style in Python [duplicate] Chained method calls indentation style in Python [duplicate] python python

Chained method calls indentation style in Python [duplicate]


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 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.

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


I think the best is to use () to force line joining, and to do this:

(ShortName.objects.distinct() # Look ma! .filter(product__photo__stickitem__isnull=False) # Comments are allowed .values_list('value', flat=True))

It's not ideal, but I like that it stands out visually and makes it somewhat obvious what the chain of calls is. It allows end-of-line comments, which \ newline does not.