Reputation: 789
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?
Upvotes: 17
Views: 7762
Reputation: 111856
some_variable = (some_very_long_value
if very_long_condition_holds else
very_long_condition_doesnt_hold)
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.Upvotes: 5
Reputation: 5061
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
Upvotes: 1
Reputation: 599540
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.
Upvotes: 21