Ben Humphreys Ben Humphreys - 2 months ago 6x
Perl Question

Python equivalent of Perl/Ruby ||=

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

foo = "hey"
foo = foo or "what"
#foo is still "hey"

bar = None
bar = bar or "yeah"
#bar is "yeah"

You can also use the ternary operator

bar = None
bar = bar if bar else "yeah"

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

bar = locals()['bar'] if 'bar' in locals() else 'yeah'


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

foo = foo if 'foo' in locals() else 'hey'

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 Perl

foo = locals().get('foo','hey')

and, of course, someone used an exception :(

except NameError:
   v = 'bla bla'