Does a Python equivalent to the Ruby ||= operator (\"set the variable if the variable is not set\") exist?
Example in Ruby :
variable_n
I would use
x = 'default' if not x else x
Much shorter than all of your alternatives suggested here, and straight to the point. Read, "set x to 'default' if x is not set otherwise keep it as x." If you need None, 0, False, or "" to be valid values however, you will need to change this behavior, for instance:
valid_vals = ("", 0, False) # We want None to be the only un-set value
x = 'default' if not x and x not in valid_vals else x
This sort of thing is also just begging to be turned into a function you can use everywhere easily:
setval_if = lambda val: 'default' if not val and val not in valid_vals else val
at which point, you can use it as:
>>> x = None # To set it to something not valid
>>> x = setval_if(x) # Using our special function is short and sweet now!
>>> print x # Let's check to make sure our None valued variable actually got set
'default'
Finally, if you are really missing your Ruby infix notation, you could overload ||=| (or something similar) by following this guy's hack: http://code.activestate.com/recipes/384122-infix-operators/
No, there is no nonsense like that. Something we have not missed in Python for 20 years.
(can't comment or I would just do that) I believe the suggestion to check locals above is not quite right. It should be:
foo = foo if 'foo' in locals() or 'foo' in globals() else 'default'
to be correct in all contexts.
However, despite its upvotes, I don't think even that is a good analog to the Ruby operator. Since the Ruby operator allows more than just a simple name on the left:
foo[12] ||= something
foo.bar ||= something
The exception method is probably closest analog.
No, the replacement is:
try:
v
except NameError:
v = 'bla bla'
However, wanting to use this construct is a sign of overly complicated code flow. Usually, you'd do the following:
try:
v = complicated()
except ComplicatedError: # complicated failed
v = 'fallback value'
and never be unsure whether v is set or not. If it's one of many options that can either be set or not, use a dictionary and its get method which allows a default value.