If not, what is the best way to do this?
Right now I'm doing (for a django project):
if not 'thing_for_purpose' in request.session: request.session['thing_for_purpose'] = 5
but its pretty awkward. In Ruby it would be:
request.session['thing_for_purpose'] ||= 5
which is much nicer.
a ||= b is a conditional assignment operator. It means: if a is undefined or falsey, then evaluate b and set a to the result. Otherwise (if a is defined and evaluates to truthy), then b is not evaluated, and no assignment takes place.
For |= , think of the known examples, x +=5 . It means x = x + 5, therefore if we have x |= 5 , it means x = x bitwiseor with 5 .
Jon-Eric's answer's is good for dicts, but the title seeks a general equivalent to ruby's ||=
operator.
A common way to do something like ||=
in Python is
x = x or new_value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With