Does Python have an "or equals" function like ||= in Ruby?


Question

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.

1
69
10/14/2010 1:39:29 AM

Accepted Answer

The accepted answer 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
165
11/13/2013 9:05:23 PM

dict has setdefault().

So if request.session is a dict:

request.session.setdefault('thing_for_purpose', 5)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon