variables – Python conditional assignment operator

variables – Python conditional assignment operator

Im surprised no one offered this answer. Its not as built-in as Rubys ||= but its 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)

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 # Lets 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 guys hack: http://code.activestate.com/recipes/384122-infix-operators/

variables – Python conditional assignment operator

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, youd do the following:

try:
   v = complicated()
except ComplicatedError: # complicated failed
   v = fallback value

and never be unsure whether v is set or not. If its one of many options that can either be set or not, use a dictionary and its get method which allows a default value.

Leave a Reply

Your email address will not be published. Required fields are marked *