PEP8, line continuations and string formatting operations

Chris Rebert clp2 at rebertia.com
Fri Jan 21 15:53:49 EST 2011


On Fri, Jan 21, 2011 at 11:53 AM, Gerald Britton
<gerald.britton at gmail.com> wrote:
> Style question:
>
> PEP 8 suggests that line continuations be done by enclosing
> expressions in parentheses rather than using the line continuation
> character.  In the same paragraph, it states a preference to put
> binary operators at the end of the line to be continued, so:
>
> x = (a +
>       b)
>
> is preferred over:
>
> x = (a
>       + b)
>
> Fair enough.
>
> What about string formatting operations (old style) though?

Fair warning: They're deprecated and liable to possibly be removed:
http://docs.python.org/dev/library/stdtypes.html#old-string-formatting-operations

> The %
> symbols is a binary operator between a string and the substitution
> values.  Strictly reading PEP 8 leads to:
>
> my_string = ("A long string with %s substitutions that %s the line
> should be %s." %
>                   ("many", "suggest", "continued")
>                  )
>
> However, I often see the % on the continued line, immediately
> preceding the substitution variables, like this:
>
> my_string = ("A long string with %s substitutions that %s the line
> should be %s."
>                   % ("many", "suggest", "continued")
>                  )
>
> This goes against the PEP 8 guidelines, but I prefer it since it makes
> the substitution variables "jump out" a bit more -- at least to me.

Remember that PEP 8 itself says:
"A Foolish Consistency is the Hobgoblin of Little Minds
  [...]
  But most importantly: know when to be inconsistent -- sometimes the style
  guide just doesn't apply.  When in doubt, use your best judgment.  Look
  at other examples and decide what looks best."

i.e. Generally, don't read PEP 8 super-strictly.

FWIW, your style seems reasonable and slightly preferable to me.

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list