-2

This seems like a really simple question; but I can't see how it's actually possible. I normally fairly good my code being PEP8 compliant. 83 characters is fine type of thing. I've got a longish list (dictionary) comprehension combined with an or that I'm trying to take to a new-line but I can't work out how to get the or onto the new-line.

A much simplified version is:

>>> test = {'a' : None, 'b' : None}
>>> b = ','.join([k for k in test
...               if test[k]]) or 'hello'

Whenever ( wherever ) I try to put the or 'hello' on a new-line it fails miserably; the command line interpreter and emacs' parser don't understand either so it may not be possible.

Is it possible to put or 'hello' on a new line and if so where would it go?

Muath
  • 4,351
  • 12
  • 42
  • 69
Ben
  • 51,770
  • 36
  • 127
  • 149
  • Possibly a duplicate of: [Stack Overflow - How can I make my Python code stay under 80 characters a line][1] [1]: http://stackoverflow.com/questions/2070684/how-can-i-make-my-python-code-stay-under-80-characters-a-line – yan Feb 09 '12 at 12:53
  • 1
    "Apparently I've forgotten all python syntax". Please bookmark the following link. http://docs.python.org/reference/lexical_analysis.html#line-structure – S.Lott Feb 09 '12 at 13:27

3 Answers3

4

Enclose in parentheses. This will work.

>>> test = {'a' : None, 'b' : None}
>>> b = (','.join([k for k in test if test[k]])
...      or 'hello')
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
Praveen Gollakota
  • 37,112
  • 11
  • 62
  • 61
2

If a line becomes too long, split it into several statements to enhance readability:

b = ','.join(k for k in test if test[k])
if not b:
    b = 'hello'

(I also changed the list comprehension to a more appropriate generator expression.)

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • I'd love to put it in a new statement but I'm joining this onto another value, which I'd rather not do twice as it'd decrease readability; but that you for the generator tip. – Ben Feb 09 '12 at 12:39
2

You mark the line continuation explicitly with a backslash:

>>> test = {'a' : None, 'b' : None}
>>> b = ','.join([k for k in test if test[k]]) \
...          or 'hello'
dawe
  • 463
  • 2
  • 8