Ternary operator in Python

The ternary operator is an in-line if/else statement that many languages support natively; however, Python does not have a specific operator. Instead, it uses conditional expression resolution which was added in Python 2.5.

In-line if/else statement

An in-line if/else statement in Python looks like the following:

1
'true' if True else 'false'

Output:

1
'true'

Breaking down the syntax,

1
true_value if condition else false_value

Return the value of the “idle” stage for a blue/green deployment.

1
2
3
4
5
6
def get_active_stage():
    # logic to get the active stage
    return "blue"

idle_stage = "green" if get_active_stage() == "blue" else "blue"
print(stage)

Output:

1
green