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'.
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'.
No, it's a common practice. It's only considered bad style for expressions that are considerably longer than yours.
if foo or bar...
, which is quite a common idiom in JS, Python and many other languages) it reads just as naturally, though you may have to think about it for a moment the very first time you see it. However, "falsy" values are a problem in Python, too, as with 'list = []; return list or False` –
Gissing 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.
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
Y = X
. For instance: A = my_main_dictionary.my_sub_dictionary.my_value if my_main_dictionary.my_sub_dictionary.my_value else None
or A = my_main_dictionary.my_sub_dictionary.my_value or None
–
Denadenae my_value
to a local variable –
Folacin 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:
Is there a Python equivalent of the C# null-coalescing operator?
© 2022 - 2024 — McMap. All rights reserved.
or
operator where a boolean result is expected, but conveniently the first true value is returned? – Hulsey