Are line continuations needed?

David Bolen db3l at fitlinxx.com
Wed Apr 7 13:04:25 EDT 2004


Peter Maas <peter.maas at mplusr.de> writes:

> Just had this example:
> 
> d = { 'key1' : 'A very very long string of several hundred '\
>            'characters. I could use a multi-line string but '\
>            'then either left white space would be part of the '\
>            'string or I would have to align it at column 0 '\
>            '(ugly). I could embed it into a pair of brackets '\
>            'but I see no advantage over \\. Finally I could '\
>            'put this string on a single line (also ugly and hard '\
>            'to read).'
>        ...
>      }

Actually that's unnecessary since you are already in a braced
expression from the dictionary constructor.  So the lines are
implicitly continuation lines until you close the dictionary, and the
compilers combination of adjacent string constants still works.  You
can drop the continuation characters and it'll give the same
dictionary.

I tend to construct parenthetical expressions if I can to avoid the
explicit line continuation character - mostly since I think it looks
nicer, but there are some cases where I prefer the contination.
There's normally an alternative to the continuation, but one that I
don't consider as readable.

For example, one place where I've used line continuations was in
explicit from imports, such as:

    from some.package.exceptions import ExceptionName, OtherName, \
                                        AnotherName, AndAnotherName

where I find this more readable than repeating the "from <package>
import" portion of the line multiple times.

I also use it to suppress leading newlines in triple quoted strings,
while permitting me to write the entire string at the same indent
level, e.g.:

    MSG = """\
    blah blah blah

    and some more blah blah blah
    """

I'll also use it sometimes for string formatting operations (either
standalone or as part of print) where sometimes I think it looks nicer
than putting the entire expression in parenthesis), e.g.:

    some_variable = 'This is a formatting string args %s %s %s' % \
                    (argument1, argument2, argument3)


-- David



More information about the Python-list mailing list