Possible Duplicate:
Python conditional assignment operator
Apologies for such a simple question, but googling ||= isn’t very helpful 😉
Is there an equivalent in Python to the ||= statement that’s present in Ruby and Perl?
For example:
foo = "hey"
foo ||= "what" # assign foo if it's undefined
# foo is still "hey"
bar ||= "yeah"
# bar is "yeah"
Also what’s the general term for something like this? Conditional assignment was my first guess but the Wikipedia page isn’t quite what I had in mind.
A tad bit more verbose, but the easiest is
You can also use the ternary operator
However, if I understand you,
||=assigns variables that weren’t previously defined, without complaint? I had no idea.To do that in the local scope, this ugly duckling could work
EDIT:
Just saw the duplicate, and it has plenty of solutions as well 🙂 For those too lazy to look, they also include a nicer variant on my last one
but this won’t work for undefined variables, only falsy values will be replaced and undefined will raise a
NameError. This next one will, OTOH, ONLY work for undefined and always keep the same preexisting falsy value, which as @Borodin says is like//=in Perland, of course, someone used an exception 🙁