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)
There really isn't any wrongs ways in there. All the ones you listed will work the same.
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:The two relevant passages are this one from the Maximum Line Length section:
... and the entire Should a line break before or after a binary operator? section:
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:
PEP 8 says that breaking before the operator is preferred:
https://www.python.org/dev/peps/pep-0008/#should-a-line-break-before-or-after-a-binary-operator
FWIW, autopep8 (with an
--aggressive
flag) produced this from your original code:But I agree -- Bastien's solution is more elegant.
Do what works.
Also, check out this whitepaper on the myths of indentation in Python. That can be found here.
It starts out with:
I hope that helps.