Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash ${var:-default} equivalent in Python?

Tags:

python

What's the simplest way to perform default variable substitution?

x = None
... (some process which may set x)
if x is None: use_x = "default"
else:         use_x = x

Is there any way of writing this in one line?

like image 536
vincent Avatar asked Dec 06 '22 23:12

vincent


1 Answers

You can use a conditional expression:

use_x = "default" if x is None else x

You could use a dict defaulting to x if the key did not exist to resemble the bash syntax but the conditional would be the idiomatic way:

use_x = {None: "default"}.get(x, x)
like image 172
Padraic Cunningham Avatar answered Dec 21 '22 14:12

Padraic Cunningham