Reputation: 15882
I can't seem to find a python way of saying
x = y or 1
In Perl:
$x = $y || 1;
Is there a nice way to do this in python?
Upvotes: 0
Views: 124
Reputation: 4456
All the solutions mentioned will work if y is defined (it can be None)
If y is not defined Python will throw an exception, while the Perl code will work in non-strict mode.
Upvotes: 2
Reputation: 399871
Python's or
has what I believe are the semantics you're looking for. See the documentation. It's important to realize that it returns the input value(s), not True
or False
.
>>> "" or 12
12
>>> 27 or 9
27
>> None or "default"
'default'
This should mean that x = y or 1
should be what you're after, x
will be y
if y
is non-False
, else it will be 1
.
Upvotes: 7
Reputation:
y = 2
x = y if y else 1
# x == 2
y = None
x = y if y else 1
# x == 1
Upvotes: 4
Reputation: 24720
x = y or 1
is the same as:
if y:
x = y
else:
x = 1
Isn't it what you're trying to do?
Upvotes: 4