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

Viewed 45749

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.

5 Answers

Jon-Eric's answer's is good for dicts, but the title seeks a general equivalent to 's ||= operator.

A common way to do something like ||= in Python is

x = x or new_value

Setting a default makes sense if you're doing it in a middleware or something, but if you need a default value in the context of one request:

request.session.get('thing_for_purpose', 5) # gets a default

bonus: here's how to really do an ||= in Python.

def test_function(self, d=None):
    'a simple test function'
    d = d or {}

    # ... do things with d and return ...
Related