Python conditional assignment operator
foo = "hey"
foo ||= "what" # assign foo if it's undefined
# foo is still "hey"
bar ||= "yeah"
# bar is "yeah"
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 :(
try: v except NameError: v = 'bla bla'