Does Python have an "or equals" function like ||= in Ruby?
dict
has setdefault()
.
So if request.session
is a dict
:
request.session.setdefault('thing_for_purpose', 5)
Precise answer: No. Python does not have a single built-in operator op
that can translate x = x or y
into x op y
.
But, it almost does. The bitwise or-equals operator (|=
) will function as described above if both operands are being treated as booleans, with a caveat. (What's the caveat? Answer is below of course.)
First, the basic demonstration of functionality:
x = Truex Out[141]: Truex |= Truex Out[142]: Truex |= Falsex Out[143]: Truex &= Falsex Out[144]: Falsex &= Truex Out[145]: Falsex |= Falsex Out[146]: Falsex |= Truex Out[147]: True
The caveat is due python not being strictly-typed, and thus even if the values are being treated as booleans in an expression they will not be short-circuited if given to a bitwise operator. For example, suppose we had a boolean function which clears a list and returns True
iff there were elements deleted:
def my_clear_list(lst): if not lst: return False else: del lst[:] return True
Now we can see the short-circuited behavior as so:
x = Truelst = [1, 2, 3]x = x or my_clear_list(lst)print(x, lst)Output: True [1, 2, 3]
However, switching the or
to a bitwise or (|
) removes the short-circuit, so the function my_clear_list
executes.
x = Truelst = [1, 2, 3]x = x | my_clear_list(lst)print(x, lst)Output: True []
Above, x = x | my_clear_list(lst)
is equivalent to x |= my_clear_list(lst)
.