Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent of getOrElse

Tags:

python

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.)

like image 432
Mohan Avatar asked Sep 11 '25 07:09

Mohan


1 Answers

Just use or for equivalent logic:

path = output_directory or '.'
like image 90
Chris_Rands Avatar answered Sep 13 '25 00:09

Chris_Rands