Assignment with "or" in python

PythonCoding StyleVariable Assignment

Python Problem Overview


Is it considered bad style to assign values to variables like this?

x = "foobar" or None
y = some_variable or None

In the above example, x gets the value 'foobar'.

Python Solutions


Solution 1 - Python

No, it's a common practice. It's only considered bad style for expressions that are considerably longer than yours.

Solution 2 - Python

The primary danger of doing something like this is the possibility that (in the second case) some_variable is False but not None (the integer 0, for instance) and you don't want to end up with y equal to None in that case.

Solution 3 - Python

I also feel a bit unconfortable using that kind of expressions. In Learning Python 4ed it is called a "somewhat unusual behavior". Later Mark Lutz says:

> ...it turns out to be a fairly common coding paradigm in Python: to > select a nonempty object from among a fixed-size set, simply string > them together in an or expression. In simpler form, this is also > commonly used to designate a default...

In fact, they produce concise one-line expressions that help to eliminate line noise from the code.
This behavior is the basis for a form of the if/else ternary operator:

A = Y if X else Z

Solution 4 - Python

OP's syntax is perfectly fine.
The official name for "assignment with or" is null coalescing and there's actually a Wikipedia page about it now! https://en.wikipedia.org/wiki/Null_coalescing_operator
This question may be useful as well: https://stackoverflow.com/questions/4978738/is-there-a-python-equivalent-of-the-c-sharp-null-coalescing-operator

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTheOneView Question on Stackoverflow
Solution 1 - PythontbackView Answer on Stackoverflow
Solution 2 - PythonFree Monica CellioView Answer on Stackoverflow
Solution 3 - PythonjoaquinView Answer on Stackoverflow
Solution 4 - PythonDonCarleoneView Answer on Stackoverflow