Linked Questions

Popular Questions

Python equivalent of getOrElse

Asked by At

In languages with optional types, you have a fn called orElse or getOrElse which lets you do this:

None.getOrElse(1) == 1
Some(2).getOrElse(1) == 2

I.e. you can specify a default value. In Python, I find I am writing:

if output_directory:
    path = output_directory
else:
    path = '.'

and it would be cleaner with a getOrElse call. Searching for orElse and getOrElse turns up logical operators. Is there a suitable Python fn?

Edit: getOrElse is not the same as a ternary operator call because that requires you to reference output_directory twice. Which is a particular issue if it's replaced with a complex expression. (Quite normal in a functional style.)

Related Questions