Python conditional assignment operator

Viewed 145057

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'
10 Answers

I do this... just sharing in case it's useful for the OP or anyone else...

def iff(value, default):
    return default if not value else value

Usage:

z = iff(x,y) # z = x if and only if x is not null otherwise y
Related