Does a Python equivalent to the Ruby ||=
operator ("set the variable if the variable is not set") exist?
Example in Ruby :
variable_not_set ||= 'bla bla'
variable_not_set == 'bla bla'
variable_set = 'pi pi'
variable_set ||= 'bla bla'
variable_set == 'pi pi'
I'm surprised no one offered this answer. It's not as "built-in" as Ruby's ||=
but it's basically equivalent and still a one-liner:
foo = foo if 'foo' in locals() else 'default'
Of course, locals()
is just a dictionary, so you can do:
foo = locals().get('foo', 'default')