Stefano Borini
Stefano Borini

Reputation: 143785

What is the official name of this construct?

In python:

>>> a = b or {}

Upvotes: 5

Views: 275

Answers (5)

Gumbo
Gumbo

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 nor or restrict the value and type they return to False and True, but rather return the last evaluated argument. This is sometimes useful, e.g., if s is a string that should be replaced by a default value if it is empty, the expression s or 'foo' yields the desired value. Because not 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' yields False, not ''.)

Upvotes: 2

Mark Byers
Mark Byers

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

John La Rooy
John La Rooy

Reputation: 304147

Default Assignment Idiom

Upvotes: 1

YOU
YOU

Reputation: 123821

May be The expression that return last evaluated argument.

Upvotes: 1

Steven Schlansker
Steven Schlansker

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

Related Questions