PEP8, line continuations and string formatting operations
Tim Chase
python.list at tim.thechases.com
Fri Jan 21 15:40:15 EST 2011
On 01/21/2011 01:53 PM, Gerald Britton wrote:
> What about string formatting operations (old style) though? 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")
> )
Depending on whether I have one item to map or multiple, I either
bite the bullet and leave them all on one line:
my_string = "A long string with only one %s substitution in
it" % adjective
if it's one substitution and the string is particularly long,
I'll occasionally break the string itself:
my_string = ("A long string with only one %s "
"substitution in it that suggests "
"being broken with a newline") % adjective
For multiple parameters (a tuple), I'll usually cram both the "%"
and the "(" on the same line:
my_string = "A long %s with %s substitution%s in it" % (
"sentence",
"several",
"s", # plural
)
which makes it a little easier to see all my parameters.
Finally, a combination of the *really* long string and multiple
parameters, I usually use a secondary variable for readability,
something like
fmt_string = (
"this is a %s %s with %s substitution%s in it "
"and it extends over several %s"
)
my_string = fmt_string % (
"long",
"string",
"multiple",
"s", # plural
"lines",
)
I like to have the parameters on their own line (and a trailing
comma) because it makes my diffs uncluttered when things are
added/removed.
That's just my own personal taste -- I too am interested in the
perspectives of others on the list.
-tkc
More information about the Python-list
mailing list