Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

ruby

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.

like image 681
Sean W. Avatar asked Oct 14 '10 01:10

Sean W.


People also ask

What does || in Ruby mean?

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.

What does |= mean in Python?

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 .


1 Answers

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 
like image 116
Joseph Sheedy Avatar answered Oct 14 '22 16:10

Joseph Sheedy