The irony
Tim Chase
python.list at tim.thechases.com
Tue May 10 14:27:41 EDT 2016
(interspersing letters to name your examples)
On 2016-05-10 14:03, DFS wrote:
A (nope)
> -----------------------------------
> sSQL = "line 1\n"
> sSQL += "line 2\n"
> sSQL += "line 3"
B (see below)
> -----------------------------------
> sSQL = ("line 1\n"
> "line 2\n"
> "line 3")
C (see below)
> -----------------------------------
> sSQL = "\n".join([
> "line 1",
> "line 2",
> "line 3",
> ])
D (almost)
> -----------------------------------
> sSQL = """line 1
> line 2
> line 3"""
E (almost)
> -----------------------------------
> sSQL = """\
> line 1
> line 2
> line 3"""
F (not bad)
> -----------------------------------
> sSQL = "line 1\n" \
> "line 2\n" \
> "line 3"
> Which is the "one obvious way" to do it?
Readability is one of Python's key strengths. I find my choice(s)
influenced by ease-of-reading and ease-of-editing (along with its
friend, ease-of-reading-diffs).
As leading indentation doesn't usually matter in SQL, I tend to just
use triple-quoted strings for all my SQL, formatting so it looks like
good SQL:
sql = """
SELECT
a.foo,
b.bar
FROM tblA a
INNER JOIN tblB b
ON a.id = b.a_id
WHERE
a.osteopathy > b.saturation
ORDER BY
b.monkey_balloon
"""
This does mean that there's a superfluous newline at the beginning &
end of the string and unneeded indentation for each line. But SQL
doesn't care, and if it had any noticeable performance issue (ooh, a
couple dozen extra bytes getting sent over the wire), it could be
post-processed to a clean one-liner.
That said, there are cases where the leading indentation does matter
to you, then I tend to use your "C" example for code executed once,
or a modification of B for code in loops:
sql = (
"line1\n"
"line2\n"
"line3"
)
(the difference being the newline after the open-paren to align all
the strings' starting offset)
If the redundancy of the "\n" characters became sufficiently
annoying, I'd define a constant (evaluated once, not in a loop) using
the "\n".join(...) method.
Seek the code that reads best for you and meets your needs.
-tkc
More information about the Python-list
mailing list