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?
Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.
Ternary Python with Numerical Values In our code, we assign the value 22 to the variable age. We use a ternary operator to check if the value of the age variable is less than 65. Because our customer is 22, the statement age < 65 evaluates to True.
The ternary operator is a way of writing conditional statements in Python. As the name ternary suggests, this Python operator consists of three operands. The ternary operator can be thought of as a simplified, one-line version of the if-else statement to test a condition.
The Python Ternary Operator The operator checks a condition, and returns x if the condition is true or y if it's not. The ternary operator above checks if x is greater than y , and if it is, assigns the value of x (10) to the variable z .
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.
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With