[Tutor] How to break long lines?

Steven D'Aprano steve at pearwood.info
Sat Feb 23 00:46:28 CET 2013


On 23/02/13 08:26, Jim Byrnes wrote:

> I am cleaning up my code and have a number of sqlite3 execute statements
>  that extend far past 80 characters.
>
> From my reading implicit line joining with (), [] or {} seems to be the
>  preferred method, but
>
> cur.execute('SELECT Account FROM pwds WHERE Category=? ORDER BY Account
>      COLLATE NOCASE', cat)
>
> gives this error:
[...]
> SyntaxError: EOL while scanning string literal


Single quote strings are limited to a single line, regardless of any
brackets (round, square or curly) around them. In this case, the round
brackets simply allow the arguments to cur.execute() to extend over
multiple lines, but each argument still has to obey the syntax rules.

You can't expect this to work:

func(12345
      67890)  # ten digit number

just because of the parentheses. Neither do single-quote strings suddenly
gain the power to extend past the end of line.


But what you can do is use a line continuation \ as you have seen. Or you
can use a little-known feature of Python, implicit string concatenation.
The Python compiler will automatically concatenate strings at compile-time:

s = "spam " 'ham ' 'eggs'

is a more-verbose way of writing:

s = "spam ham eggs"

Now obviously this example here is useless, but when combined with
parentheses, you get a powerful way of writing long strings:


cur.execute('SELECT Account FROM pwds'
             ' WHERE Category=?'
             ' ORDER BY Account'
             ' COLLATE NOCASE', cat)


which I think is really nice to read. The best part is, because these
are string literals, the language promises to concatenate them at
compile-time, not runtime.

If implicit concatenation is too magical for you, you can use explicit
concatenation:

cur.execute('SELECT Account FROM pwds' +
             ' WHERE Category=?' +
             ' ORDER BY Account' +
             ' COLLATE NOCASE', cat)

At worst, the string concatenation + operator will apply at runtime,
which for a short string like this is not a big deal. But in practice,
I would expect Python's "keyhole optimizer" to see that it is only
string literals being concatenated, and perform constant-folding at
compile-time.

(Note: constant-folding is not a promise of the language. Not all
Python versions or implementations will do this.)


A fourth option is to use triple-quoted strings:

cur.execute('''SELECT Account FROM pwds
                WHERE Category=?
                ORDER BY Account
                COLLATE NOCASE''', cat)


but this relies on your SQL database being happy to receive commands
with embedded newlines, which it may not be.




-- 
Steven


More information about the Tutor mailing list