Conditional Expressions

Many of the features embraced by modern languages facilitate more concise expression; developers can do more with less. Importantly, they are introducing these features in an elegant, easy to read syntax. A delightful example of this is Kotlin’s .also to swap two variables. In the past we would might do something like this:

tmp = x;
x = y;
y = tmp;

The performance minded, or those put off with the banality of using tmp, might use XOR and do something like this:

x = x ^ y; 
y = x ^ y; 
x = x ^ y;

In Kotlin we can use this wonderful syntax:

x = y.also {y = x}

Concise, expressive, easy to read, simple. Beautiful.

The Tenary Opeator

The tenary operator has been loved by developers for decades because of its conciseness, although it can be hard to read at times if the code formatting is off, or the conditions/expressions are too complex. It looks like this:

x = condition ? true value : false value;

If the condition evaluates to true, x is assigned the true value, otherwise the false value:

text = "";
...
return text = "" ? "unknown" : text;  // returns unknown

text = "fred";
...
return text = "" ? "unknown" : text;  // returns fred

It is essentially a concise representation of an if/else statement:

if (text == "") {
  return "unknown";
} else {
  return text;
}

Conditional Expressions in Python

The good news is, Python has it’s own equivalent of the tenary operator known as a conditional expression, and it is elegant:

return "unknown" if text == "" else text

There’s an even shorter version if you are testing against None, for example:

text = None
...
return text or "unknown"  // returns unknown

This is often useful if you are handling the return result from a function call:

last_login = get_last_login(user) or "No previous logins"
print(last_login)

Finally, here is a nice example of using it to define function parameters with default values:

def display_user(name, nickname=None):
  nickname = nickname or name
  print(nickname)

display_user("fred")

# output: fred

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s