Reputation: 143785
In python:
>>> a = b or {}
Upvotes: 5
Views: 275
Reputation: 655219
The expression b or {}
is just a simple boolean OR expression. The special about this is just that this expression does not need return a boolean value per definition like in other languages:
The expression
x or y
first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.(Note that neither
and
noror
restrict the value and type they return toFalse
andTrue
, but rather return the last evaluated argument. This is sometimes useful, e.g., ifs
is a string that should be replaced by a default value if it is empty, the expressions or 'foo'
yields the desired value. Becausenot
has to invent a value anyway, it does not bother to return a value of the same type as its argument, so e.g.,not 'foo'
yieldsFalse
, not''
.)
Upvotes: 2
Reputation: 838116
I don't think it has an official name, it's just a clever/lazy way to be concise. It's roughly equivalent to:
a = b if b else {}
or:
if b:
a = b
else:
a = {}
I wrote this as a comment but I think it's worth mentioning here:
You have to be very careful when using this trick. If your intention is to set a default value when something is None, it would be better to write that is None
test explicitly than use this trick. The reason is that None is not the only thing that evaluates to false in a boolean context. 0, [], {}, ... also evaluate to false. So this trick might not give you the expected results if you didn't think about these special cases.
Here's one way to do it that is safer:
a = b if b is not None else {}
Upvotes: 10
Reputation: 38526
That's not a special construct, at least to my somewhat tired eyes. It's saying to assign the result of
(b or {})
to a.
So, if b is a False value, a gets {} (the empty dictionary literal), otherwise it gets the value of b.
Upvotes: 1