Hot to split string literals that will across two or more lines ?

Magnus Lycka lycka at carmen.se
Wed Nov 23 06:03:29 EST 2005


Fredrik Lundh wrote:
>     cursor.execute(
>         'select * from foo'
>         ' where bar=%s'
>         ' limit 100',
>         bar
>     )

The disavantage with this is that it's easy to make
a mistake, like this...

      cursor.execute(
          'select * from foo '
          'where bar=%s'
          'limit 100',
          bar
      )

That might be a reason to prefer triple quoting instead:

      cursor.execute(
          '''select * from foo
          where bar=%s
          limit 100''',
          bar
      )

This last version will obviously contain some extra whitespace
in the SQL text, and that could possibly have performance
implications, but in general, I prefer to reduce the risk of
errors (and I've made mistakes with missing spaces in adjacent
string literals).



More information about the Python-list mailing list