Idioms and Anti-Idioms Question

Lie Ryan lie.1296 at
Mon Jun 22 01:54:47 EDT 2009

Ben Charrow wrote:
> I have a question about the "Using Backslash to Continue Statements" in
> the howto "Idioms and Anti-Idioms in Python"
> (
> It says:
> "...if the code was:
> value =['first'][0]*baz.quux(1, 2)[5:9] \
>         + calculate_number(10, 20)*forbulate(500, 360)
> then it would just be subtly wrong."
> 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 =['first'][0]*baz.quux(1, 2)[5:9] + \
        calculate_number(10, 20)*forbulate(500, 360)

and even more preferrable is NOT to use explicit line break at all;
relying on implicit breaking with parentheses since then you won't need
to worry about empty lines:

value = (['first'][0]*baz.quux(1, 2)[5:9] +
         calculate_number(10, 20)*forbulate(500, 360)

although, in a formula that is so complex, the most preferable way is to
separate them so they won't need to take more than a single line:

a =['first'][0]
b = baz.quux(1, 2)[5:9]
c = calculate_number(10, 20)
d = forbulate(500, 360)
value = a*b + c*d

of course, a, b, c, d should be substituted with a more helpful names.

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.

More information about the Python-list mailing list