Contents

Python: Assignments with default values

Contents

Some time ago, Manolowar showed me the operator [“Elvis] from Groovy .

Python

This operator, written like: ?: is called in this way because it looks like an emoticon with toupee, just like Elvis Presley. It can be used like in C or Java (separated) or all together. When it is all together, it means something like: “If value is false, assign me it, and if not, assign me this other one”. Here you are an example:

1
2
Integer i = null;
int a = i ?: 0;

Here we want to assign value of “I” to “A”. This is a problem, because “I” admits nulls but “A” does not. With this easy way I solved the problem.

But… Isn’t this article about Python?

Yes, it does. Yesteray David told me about the way of doing just this with Python and, IMHO, it is more pretty. You only have to use the “OR” operator.

Opposite I was thinking till now, “OR” in Python does not return a boolean value; it evals the expression and returns the first result that is not false. So, we can find:

1
2
i = None
a = i or 7

And “A” will be 7, because “I” is false and the last evaluated value that is not false is 7.

The advantage of using this is that it can be concatenated. Example (do not at home):

1
a = 0 or '' or [] or {} or False or "Everything else is false"

Which one is the resulting value in this case?

As you can see, every condition is false but the last one, so the final A value will be “Everything else is false”.

Use it carefully!!!

Notes

I have been very careful trying to say that it searchs the first that is not false”. This do not mean “the first that is true”, because “truth” is True. It is the very first that do not match “a false condition .