Multiline code - trailing slash usage

Larry Bates lbates at websafe.com
Thu Mar 15 11:17:06 EDT 2007


abcd wrote:
> When do I need to use a trailing slash to separate code over multiple
> lines.
> 
> For example:
> 
> x = "hello world, this is my multiline " + \
>      "string!!!!"
> 
> x = {'name' : \
>       'bob'}
> 
> Do I need to use the "\" in the above examples?  When do i need to use
> it?
> 
You need to use it when your are not inside some context that makes it
clear to Python that there's more to the line:

You don't need it here because python knows you are inside a list (same is
true for tuple).

a=[1,
   2,
   3
  ]

Same for a dictionary:

a={'a1': 1,
   'a2': 2,
   'a3': 3
  }

Also when you are inside call list of a function

a=foo(a,"this is a very long string",
      arg3, arg4,
      kwarg1='one', kwarg2='two')

Python knows you aren't done because you haven't provided the closing
parenthesis.

I do this in list comprehensions also:

n=[(variable1, variable2) for variable1, variable2 in something
   if variable1.startswith('z')]

You do need it in your first example, but not in your second.

-Larry



More information about the Python-list mailing list