TorokLev
TorokLev

Reputation: 789

How should I indent ternary conditional operator in python so that it complies with PEP8?

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

Answers (3)

Mr Fooz
Mr Fooz

Reputation: 111856

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.

Upvotes: 5

Vishnu Upadhyay
Vishnu Upadhyay

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

Daniel Roseman
Daniel Roseman

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

Related Questions