I have some code like this. Should the break occur before the periods or after?
# before
my_var = somethinglikethis.where(we=do_things).where(we=domore).where(we=everdomore)
# this way
my_var = somethinglikethis.where(we=do_things) \
.where(we=domore) \
.where(we=everdomore)
# or this way
my_var = somethinglikethis.where(we=do_things). \
where(we=domore). \
where(we=everdomore)
解决方案
Personally, I prefer using parenthesis so that you don't need \:
my_var = (somethinglikethis
.where(we=do_things)
.where(we=domore)
.where(we=everdomore))
(I changed the indentation because that's how my editor indents it automatically.)
I just looked through PEP 8, and it looks like there's no mention of line breaks.
But parenthesis (or other characters such as [] or {}) should help your editor indent the code automatically, and they only require you to modify the beginning and the end of the expression.
[Edit]
Here is what the style guide says about it, thanks to delnan:
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)
[Edit]
The style guide now recommends breaking before a binary operator (thanks @Neapolitan):