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

Solution 1:

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

Solution 2:

dict has setdefault().

So if request.session is a dict:

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