How to Break a Line of Chained Methods in Python

How to break a line of chained methods in Python?

You could use additional parentheses:

subkeyword = (
Session.query(Subkeyword.subkeyword_id, Subkeyword.subkeyword_word)
.filter_by(subkeyword_company_id=self.e_company_id)
.filter_by(subkeyword_word=subkeyword_word)
.filter_by(subkeyword_active=True)
.one()
)

Correct style for line breaks when chaining methods in Python

PEP 8 recommends using parenthesis so that you don't need \, and gently suggests breaking before binary operators instead of after them. Thus, the preferred way of formatting you code is like this:

my_var = (somethinglikethis
.where(we=do_things)
.where(we=domore)
.where(we=everdomore))

The two relevant passages are this one from the Maximum Line Length section:

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.

... and the entire Should a line break before or after a binary operator? section:

Should a line break before or after a binary operator?

For decades the recommended style was to break after binary operators.
But this can hurt readability in two ways: the operators tend to get
scattered across different columns on the screen, and each operator is
moved away from its operand and onto the previous line. Here, the eye
has to do extra work to tell which items are added and which are
subtracted:

# No: operators sit far away from their operands
income = (gross_wages +
taxable_interest +
(dividends - qualified_dividends) -
ira_deduction -
student_loan_interest)

To solve this readability problem, mathematicians and their publishers
follow the opposite convention. Donald Knuth explains the traditional
rule in his Computers and Typesetting series: "Although formulas
within a paragraph always break after binary operations and relations,
displayed formulas always break before binary operations"

Following the tradition from mathematics usually results in more
readable code:

# Yes: easy to match operators with operands
income = (gross_wages
+ taxable_interest
+ (dividends - qualified_dividends)
- ira_deduction
- student_loan_interest)

In Python code, it is permissible to break before or after a binary
operator, as long as the convention is consistent locally. For new
code Knuth's style is suggested.

Note that, as indicated in the quote above, PEP 8 used to give the opposite advice about where to break around an operator, quoted below for posterity:

The preferred way of wrapping long lines is by using Python's implied line
continuation inside parentheses, brackets and braces. Long lines can be
broken over multiple lines by wrapping expressions in parentheses. These
should be used in preference to using a backslash for line continuation.
Make sure to indent the continued line appropriately. The preferred place
to break around a binary operator is after the operator, not before it.
Some examples:

class Rectangle(Blob):

def __init__(self, width, height,
color='black', emphasis=None, highlight=0):
if (width == 0 and height == 0 and
color == 'red' and emphasis == 'strong' or
highlight > 100):
raise ValueError("sorry, you lose")
if width == 0 and height == 0 and (color == 'red' or
emphasis is None):
raise ValueError("I don't think so -- values are %s, %s" %
(width, height))
Blob.__init__(self, width, height,
color, emphasis, highlight)

Breaking long method chains into multiple lines in Python

Best approach I've came up with so far is this:

t_values = (df_grouped_by_day
.sort_values('day_of_week')
.groupby(['day_of_week', 'day_of_week_name'])['Show_up']
.apply(lambda sample: ttest_ind(population, sample))
.reset_index())

Chained method calls indentation style in Python

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

Method chaining - how many chained methods are enough?

This is largely a matter of personal preference, but if the text in f isn't going to be used elsewhere then that's fine. The point at which it becomes unclear to a casual reader what the chain actually returns is the point at which it's too long. The only benefits to splitting it up are that you can use intermediate results and you may gain clarity.

Is it possible to split a sequence of pandas commands across multiple lines?

In python you can continue to the next line by ending your line with a reverse slash or by enclosing the expression in parenthesis.

df.groupby[['x','y']] \
.apply(lambda x: (np.max(x['z'])-np.min(x['z']))) \
.sort_values(ascending=False)

or

(df.groupby[['x','y']]
.apply(lambda x: (np.max(x['z'])-np.min(x['z'])))
.sort_values(ascending=False))

Python: split method call into multiple lines

Other answers would get you how to split a statement into multiple lines, But an easier way to achieve what you are doing would be to use str.format() -

>>> template = "{a}{b}-{c}{d}"
>>> a = 1
>>> b = 2
>>> c = 3
>>> d = 4
>>> template.format(**{'a':a,'b':b,'c':c,'d':d})
'12-34'
>>> template.format(a=a,b=b,c=c,d=d)
'12-34'

The first str.format() unpacks a dictionary into keyword arguments for the function format() (similar to what the second one does directly) .


Also, you can split the arguments to a function call in multiple lines without having to use \ , Example -

>>> template.format(a=a,
... b=b,
... c=c,
... d=d)
'12-34'

How can I do a line break (line continuation) in Python?

What is the line? You can just have arguments on the next line without any problems:

a = dostuff(blahblah1, blahblah2, blahblah3, blahblah4, blahblah5, 
blahblah6, blahblah7)

Otherwise you can do something like this:

if (a == True and
b == False):

or with explicit line break:

if a == True and \
b == False:

Check the style guide for more information.

Using parentheses, your example can be written over multiple lines:

a = ('1' + '2' + '3' +
'4' + '5')

The same effect can be obtained using explicit line break:

a = '1' + '2' + '3' + \
'4' + '5'

Note that the style guide says that using the implicit continuation with parentheses is preferred, but in this particular case just adding parentheses around your expression is probably the wrong way to go.



Related Topics



Leave a reply



Submit