On 04/18/2014 04:14 PM, gwhite wrote:
[snip]
Yeah, I have noticed that they don't seem to be needed, but I think I remember reading 
"someplace-somewhere" that
a backslash means a line continuation, and perhaps I saw some author put them in. So I did it out of trying to be "strict."

I'm not sure when a backslash continuation might be needed, or if that 
requirement has been designed out of Python.


['they' meaning trailing backslashes]

No, 'they' are still definitely in Python, but can usually be avoided.

As already mentioned, strings are automatically concatenated if they are separated by only whitespace (spaces/tabs/newlines). But there is a difference between this concatenation and using a trailing backslash. For example:

print('this, that, '
        'the other')

gives -> 'this, that, the other'

print('this, that, \
        the other')

gives -> 'this, that,         the other'

The leading whitespace in the second example is significant, but is ignored in 
the first.

The other places you can avoid the trailing backslash is within brackets, ie. 
(), [] or {}.
Here you can split at any 'natural' position, that is following a comma, dot or 
an operator.

['spam',
    'eggs',
'bacon']

gives -> ['spam', 'eggs', 'bacon']

---------
[2 +
     3,
          'spam']

gives -> [5, 'spam']

---------
print('this' and
    'that' or
    'other')

gives -> 'that'

---------
print('{}'.
    format('spam'))

gives -> 'spam'

These examples are somewhat contrived, but they do show what I'm talking about.

Of course, you can still use the trailing backslash method, but when you can avoid it it usually looks cleaner. Besides simply using either method to split long lines, it is often used to line things up, either for the appearance or for documentation. Here is a dictionary example of what I mean (and the backslash method will NOT work here):

d = {1 : 'one',        #  Describe this key/value pair
     2 : 'two',        #  Describe this one
     3 : 'three'       #  Etc.
    }

Play around in the interactive mode to check out how this splitting works.

     -=- Larry -=-

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to