Python conditional assignment operator
Solution 1:
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')
Solution 2:
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/
Solution 3:
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.
Solution 4:
There is conditional assignment in Python 2.5 and later - the syntax is not very obvious hence it's easy to miss. Here's how you do it:
x = true_value if condition else false_value
For further reference, check out the Python 2.5 docs.
Solution 5:
No, not knowing which variables are defined is a bug, not a feature in Python.
Use dicts instead:
d = {}
d.setdefault('key', 1)
d['key'] == 1
d['key'] = 2
d.setdefault('key', 1)
d['key'] == 2