Idioms and Anti-Idioms Question

Peter Billam peter at www.pjb.com.au
Mon Jun 22 18:52:29 EDT 2009


On 2009-06-22, Lie Ryan <lie.1296 at gmail.com> wrote:
> Ben Charrow wrote:
>> value = foo.bar()['first'][0]*baz.quux(1, 2)[5:9] \
>>         + calculate_number(10, 20)*forbulate(500, 360)
>> What is subtly wrong about this piece of code?  I can't see any bugs and
>> can't think of subtle gotchas (e.g. the '\' is removed or the lines
>> become separated, because in both cases an IndentationError would be
>> raised).
>
> The preferred style is to put the binary operators before the line-break
> (i.e. the line break is after the operators):
> value = foo.bar()['first'][0]*baz.quux(1, 2)[5:9] + \
>         calculate_number(10, 20)*forbulate(500, 360)
> ...
> The following is an extract from PEP 8:
> The preferred way of wrapping long lines is by using Python's
> implied line continuation inside parentheses, brackets and braces.
> If necessary, you can add an extra pair of parentheses around an
> expression, but sometimes using a backslash looks better.  Make sure to
> indent the continued line appropriately.  The preferred place to break
> around a binary operator is *after* the operator, not before it.

Damian Conway, in Perl Best Practices, puts forward a clear argument
for breaking *before* the operator:
  Using an expression at the end of a statement gets too long,
  it's common practice to break that expression after an operator
  and then continue the expression on the following line ...
  The rationale is that the operator that remains at the end
  of the line acts like a continutation marker, indicating that
  the expression continues on the following line.
  Using the operator as a continutation marker seems like
  an excellent idea, but there's a serious problem with it:
  people rarely look at the right edge of code.
  Most of the semantic hints in a program - such as keywords -
  appear on the left side of that code.  More importantly, the
  structural cues for understanding code - for example, indenting, - 
  are predominantly on the left as well ... This means that indenting
  the continued lines of the expression actually gives a false
  impression of the underlying structure, a misperception that
  the eye must travel all the way to the right margin to correct.

which seems to me well-argued.  I wonder on what grounds PEP8
says "The preferred place to break around a binary operator is
*after* the operator" ?
Perhaps it's just the "continutation marker" rationale?

Regards,  Peter

-- 
Peter Billam       www.pjb.com.au    www.pjb.com.au/comp/contact.html



More information about the Python-list mailing list