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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With