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/