16

PEP8 doesn't say anything about ternary operators, if I am not mistaken. So what do you suggest, how should I write long lines with ternary conditional operators?

some_variable = some_very_long_value \
                if very_long_condition_holds \
                else very_long_condition_doesnt_hold

or

some_variable = some_very_long_value \
                    if very_long_condition_holds \
                        else very_long_condition_doesnt_hold

Which one do you prefer the most?

TorokLev
  • 769
  • 6
  • 8
  • The first is more readible. Btw there is a pep8 program that will check your python files. https://pypi.python.org/pypi/pep8 – Vincent Beltman Oct 07 '14 at 10:07
  • 3
    (1) PEP 8 prefers parentheses over backslashes for expressions spanning several lines. (2) You could always not use the operator if the condition and values are so long. –  Oct 07 '14 at 10:10
  • Unfortunately, questions asking for opinions on something are not on-topic for Stack Overflow. There are several other places where these questions might get a better reception; you should try there instead. – Veedrac Oct 07 '14 at 10:12

3 Answers3

20

Neither. For any long line, it's usually better to use parentheses to allow line breaks. Opinions differ whether you should do this:

some_variable = (some_very_long_value
                if very_long_condition_holds
                else very_long_condition_doesnt_hold)

or this:

some_variable = (
    some_very_long_value
    if very_long_condition_holds
    else very_long_condition_doesnt_hold)

or even this:

some_variable = (
    some_very_long_value
    if very_long_condition_holds
    else very_long_condition_doesnt_hold
)

Personally I prefer the third; Google in-house style is the second.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
5
some_variable = (some_very_long_value
                 if very_long_condition_holds else
                 very_long_condition_doesnt_hold)
  • Use parentheses instead of backslashes for line continuations, per PEP8.
  • By putting the if ... else construct on its own line, there's a clear separation between the three parts of this expression: the then expression, the conditional part, and the else expression. The then and else expressions are formatted uniformly and are separate from the if...else construct.
Mr Fooz
  • 109,094
  • 6
  • 73
  • 101
1
some_variable = some_very_long_value\
                if very_long_condition_holds\
                else othervalue

prefer braces when face such problems. check about Maximum Line Length here. http://legacy.python.org/dev/peps/pep-0008/#maximum-line-length

Vishnu Upadhyay
  • 5,043
  • 1
  • 13
  • 24