In Perl, it’s often nice to be able to assign an object, but specify some fall-back value if the variable being assigned from is ‘undef’. For instance:
my $x = undef;
my $y = 2;
my $a = $x || $y;
After this,
$a == 2
Is there a concise way to achieve this in Python if the value x is None, or would a full-on …
if x is not None
a = x
else
a = y
… be the most Pythonic way to achieve this?
EDIT: Apologies, as has been pointed out by several commenters, I wasn’t really talking about the value being undefined, but ‘undef’ in Perl, which is not really the same thing. But the question as originally worded didn’t make this clear.
Since 2.5:
If you want to fall back only on None:
If you want to fall back also on empty string,
false,0etc.:or
As for undefined (as never defined, a.k.a. not bound):
or a bit more hackish (I’d not really recommend that, but it’s short):